@vapi-network/core 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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-profile.d.ts +7 -0
  3. package/dist/agent-profile.d.ts.map +1 -1
  4. package/dist/api-key.js +4 -0
  5. package/dist/api-key.js.map +1 -1
  6. package/dist/backup.js +8 -1
  7. package/dist/backup.js.map +1 -1
  8. package/dist/cloud-backup.js +8 -1
  9. package/dist/cloud-backup.js.map +1 -1
  10. package/dist/config.d.ts +10 -0
  11. package/dist/config.d.ts.map +1 -1
  12. package/dist/index.js +65 -5
  13. package/dist/index.js.map +2 -2
  14. package/dist/router-client.js +7 -1
  15. package/dist/router-client.js.map +1 -1
  16. package/dist/secret-backend.d.ts +5 -1
  17. package/dist/secret-backend.d.ts.map +1 -1
  18. package/dist/secrets.js +6 -1
  19. package/dist/secrets.js.map +1 -1
  20. package/dist/support-report.d.ts +1 -1
  21. package/dist/swarm.d.ts.map +1 -1
  22. package/dist/tasks/availability.d.ts +21 -0
  23. package/dist/tasks/availability.d.ts.map +1 -0
  24. package/dist/tasks/chain.d.ts.map +1 -1
  25. package/dist/tasks/index.d.ts +2 -0
  26. package/dist/tasks/index.d.ts.map +1 -1
  27. package/dist/tasks/operation-support.d.ts +11 -1
  28. package/dist/tasks/operation-support.d.ts.map +1 -1
  29. package/dist/tasks/operations.d.ts +12 -12
  30. package/dist/tasks/operations.d.ts.map +1 -1
  31. package/dist/tasks/pending-transactions.d.ts +3 -0
  32. package/dist/tasks/pending-transactions.d.ts.map +1 -1
  33. package/dist/tasks/post-options.d.ts +10 -0
  34. package/dist/tasks/post-options.d.ts.map +1 -1
  35. package/dist/tasks/v2-execution.d.ts +9 -9
  36. package/dist/tasks/v2-execution.d.ts.map +1 -1
  37. package/dist/tasks/v2-jury.d.ts +6 -6
  38. package/dist/tasks/v2-jury.d.ts.map +1 -1
  39. package/dist/tasks/v2-limits.d.ts +30 -0
  40. package/dist/tasks/v2-limits.d.ts.map +1 -0
  41. package/dist/tasks/v2-plan-guard.d.ts +3 -1
  42. package/dist/tasks/v2-plan-guard.d.ts.map +1 -1
  43. package/dist/tasks/v2-public.d.ts +2 -2
  44. package/dist/tasks/v2-public.d.ts.map +1 -1
  45. package/dist/tasks/v2-write.d.ts +13 -12
  46. package/dist/tasks/v2-write.d.ts.map +1 -1
  47. package/dist/tasks/x402-funding.d.ts +4 -4
  48. package/dist/tasks.js +2078 -1779
  49. package/dist/tasks.js.map +3 -3
  50. package/dist/wallet-store.d.ts +14 -1
  51. package/dist/wallet-store.d.ts.map +1 -1
  52. package/package.json +1 -1
package/dist/tasks.js CHANGED
@@ -39401,9 +39401,11 @@ var taskV2OperationSchema = external_exports.object({
39401
39401
  step: taskV2StepSchema,
39402
39402
  expectedActor: address,
39403
39403
  transactionHash: hash4.nullable(),
39404
- plan: taskV2PlanSchema
39404
+ // The API returns the plan only while the step is prepared and re-validated; once the
39405
+ // transaction is submitted or confirmed, and while a recovery scan runs, it sends null.
39406
+ plan: taskV2PlanSchema.nullable()
39405
39407
  }).refine(
39406
- (v) => v.plan.operationId === v.id && v.plan.step === v.step && v.plan.from === v.expectedActor,
39408
+ (v) => v.plan === null || v.plan.operationId === v.id && v.plan.step === v.step && v.plan.from === v.expectedActor,
39407
39409
  "Operation plan binding mismatch"
39408
39410
  ).refine(
39409
39411
  (v) => !["submitted", "confirmed"].includes(v.state) || v.transactionHash !== null,
@@ -40301,20 +40303,22 @@ function taskFundingIntentNonce(intent, expected) {
40301
40303
  return message.nonce.toLowerCase();
40302
40304
  }
40303
40305
 
40304
- // src/tasks/dispute-fee.ts
40306
+ // src/tasks/operation-support.ts
40307
+ import { readFile as readFile6, stat as stat4 } from "node:fs/promises";
40308
+ import { basename as basename2, extname, join as join6 } from "node:path";
40309
+
40310
+ // src/agent-link.ts
40305
40311
  import { createHash as createHash2 } from "node:crypto";
40306
- function disputeFeeBaseUnits(amount4) {
40307
- if (amount4 < 0n) throw new Error("Dispute amount must be nonnegative.");
40308
- const fee = amount4 * 1000n / 10000n;
40309
- return fee < 20000000n ? 20000000n : fee > 500000000n ? 500000000n : fee;
40310
- }
40311
- function taskFeeReservationKey(milestoneId2, action) {
40312
- const bytes = createHash2("sha256").update(JSON.stringify([milestoneId2, action])).digest().subarray(0, 16);
40313
- bytes[6] = bytes[6] & 15 | 80;
40314
- bytes[8] = bytes[8] & 63 | 128;
40315
- const hex5 = bytes.toString("hex");
40316
- return `${hex5.slice(0, 8)}-${hex5.slice(8, 12)}-${hex5.slice(12, 16)}-${hex5.slice(16, 20)}-${hex5.slice(20)}`;
40317
- }
40312
+ import { mkdir as mkdir3, open as open3, stat as stat2, unlink as unlink2 } from "node:fs/promises";
40313
+ import { dirname as dirname3 } from "node:path";
40314
+
40315
+ // src/audit.ts
40316
+ import { appendFile, chmod, mkdir as mkdir2, readFile as readFile3 } from "node:fs/promises";
40317
+ import { join as join4 } from "node:path";
40318
+
40319
+ // src/config.ts
40320
+ import { homedir } from "node:os";
40321
+ import { dirname as dirname2, join as join3 } from "node:path";
40318
40322
 
40319
40323
  // src/x402-networks.ts
40320
40324
  var BASE_MAINNET_CAIP2 = "eip155:8453";
@@ -40492,544 +40496,811 @@ function formatUsdc(amountAtomic) {
40492
40496
  return formatUnits(amountAtomic, USDC_DECIMALS);
40493
40497
  }
40494
40498
 
40495
- // src/tasks/money.ts
40496
- function formatBaseUnitsUsd(baseUnits2) {
40497
- const [whole, fraction = ""] = formatUsdc(parseBaseUnits(baseUnits2)).split(".");
40498
- return `${whole}.${fraction.padEnd(2, "0")}`;
40499
- }
40500
- function parseUsdToBaseUnits(text) {
40501
- if (!/^\d+(?:\.\d{1,6})?$/u.test(text)) {
40502
- throw new Error(
40503
- "Task USD amount must be a non-negative decimal with at most six decimal places."
40504
- );
40505
- }
40506
- const [whole = "0", fraction = ""] = text.split(".");
40507
- return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
40508
- }
40509
- function parseFeeBp(deploymentOrReadiness) {
40510
- if (typeof deploymentOrReadiness !== "object" || deploymentOrReadiness === null || !("feeBp" in deploymentOrReadiness)) {
40511
- return null;
40499
+ // src/config.ts
40500
+ var DEFAULT_REGISTRY_URL = "https://api.vapinetwork.ai";
40501
+ var DEFAULT_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/services`;
40502
+ var DEFAULT_MARKETPLACE_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/discovery`;
40503
+ var DEFAULT_MAX_PER_TASK_USD = 100;
40504
+ var DEFAULT_AUTO_RELEASE_BELOW_USD = 25;
40505
+ var walletTaskPolicySchema = external_exports.object({
40506
+ maxPerTaskUsd: external_exports.number().min(0).optional(),
40507
+ approveAboveUsd: external_exports.number().min(0).optional()
40508
+ });
40509
+ var atomicString = external_exports.string().regex(/^\d+$/, "Expected non-negative atomic units.");
40510
+ var spendCapsSchema = external_exports.object({
40511
+ perCallAtomic: atomicString,
40512
+ perDayAtomic: atomicString
40513
+ });
40514
+ var configSchema = external_exports.object({
40515
+ discoveryUrl: external_exports.url(),
40516
+ marketplaceDiscoveryUrl: external_exports.url().default(DEFAULT_MARKETPLACE_DISCOVERY_URL),
40517
+ registryFallbacks: external_exports.array(
40518
+ external_exports.object({
40519
+ discoveryUrl: external_exports.url(),
40520
+ marketplaceDiscoveryUrl: external_exports.url()
40521
+ })
40522
+ ).optional(),
40523
+ allowPrivateNetwork: external_exports.boolean().default(false).optional(),
40524
+ tasksEscrowDurationOverrides: external_exports.record(
40525
+ external_exports.string().regex(/^\d+$/),
40526
+ external_exports.object({
40527
+ workDurationSeconds: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
40528
+ reviewWindowSeconds: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional()
40529
+ }).strict()
40530
+ ).optional(),
40531
+ tasksEscrowFactoryOverrides: external_exports.record(external_exports.string().regex(/^\d+$/), external_exports.string()).optional(),
40532
+ networks: external_exports.record(
40533
+ external_exports.string().refine((network) => isSupportedPaymentNetwork(network), {
40534
+ message: "Expected a supported eip155:<chainId> or Solana network identifier."
40535
+ }),
40536
+ external_exports.object({
40537
+ rpcUrl: external_exports.string(),
40538
+ usdc: external_exports.string().trim().min(1),
40539
+ depositUrl: external_exports.url().optional(),
40540
+ depositInstructions: external_exports.string().trim().min(1).max(500).optional(),
40541
+ eip712Domain: external_exports.object({
40542
+ name: external_exports.string().trim().min(1).max(64),
40543
+ version: external_exports.string().trim().min(1).max(32)
40544
+ }).optional()
40545
+ })
40546
+ ),
40547
+ spendCaps: spendCapsSchema,
40548
+ device: external_exports.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/).optional()
40549
+ }).superRefine((config2, context) => {
40550
+ for (const [chainId, factory] of Object.entries(config2.tasksEscrowFactoryOverrides ?? {})) {
40551
+ try {
40552
+ getAddress(factory);
40553
+ } catch {
40554
+ context.addIssue({
40555
+ code: "custom",
40556
+ path: ["tasksEscrowFactoryOverrides", chainId],
40557
+ message: "Expected a valid EVM escrow factory address."
40558
+ });
40559
+ }
40512
40560
  }
40513
- const feeBp = deploymentOrReadiness.feeBp;
40514
- if (feeBp === void 0 || feeBp === null) return null;
40515
- validateFeeBp(feeBp);
40516
- return feeBp;
40517
- }
40518
- function taskMoney(grossBaseUnits, feeBp) {
40519
- const atomic = parseBaseUnits(grossBaseUnits);
40520
- const gross = amount3(atomic);
40521
- if (feeBp === null) {
40522
- return { gross, fee: null, net: null, feeBp, line: `$${gross.usd} gross \xB7 fee unavailable` };
40561
+ for (const [network, configured] of Object.entries(config2.networks)) {
40562
+ if (isSolanaNetwork(network)) {
40563
+ if (configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
40564
+ context.addIssue({
40565
+ code: "custom",
40566
+ path: ["networks", network, "usdc"],
40567
+ message: "Expected canonical Solana mainnet USDC mint."
40568
+ });
40569
+ }
40570
+ continue;
40571
+ }
40572
+ try {
40573
+ const usdc = getAddress(configured.usdc);
40574
+ if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS[network].usdc)) {
40575
+ context.addIssue({
40576
+ code: "custom",
40577
+ path: ["networks", network, "usdc"],
40578
+ message: "Expected the canonical Arc USDC predeploy."
40579
+ });
40580
+ }
40581
+ } catch {
40582
+ context.addIssue({
40583
+ code: "custom",
40584
+ path: ["networks", network, "usdc"],
40585
+ message: "Expected a valid EVM USDC contract address."
40586
+ });
40587
+ }
40523
40588
  }
40524
- validateFeeBp(feeBp);
40525
- const feeAtomic = atomic * BigInt(feeBp) / 10000n;
40526
- const fee = amount3(feeAtomic);
40527
- const net = amount3(atomic - feeAtomic);
40589
+ });
40590
+ function getVapiPaths(directory = process.env.VAPI_HOME?.trim() || join3(homedir(), ".vapi")) {
40528
40591
  return {
40529
- gross,
40530
- fee,
40531
- net,
40532
- feeBp,
40533
- line: `$${gross.usd} gross \xB7 $${fee.usd} fee \xB7 $${net.usd} net`
40592
+ directory,
40593
+ agentsDir: join3(directory, "agents"),
40594
+ config: join3(directory, "config.json"),
40595
+ keystore: join3(directory, "keystore.json"),
40596
+ receipts: join3(directory, "receipts.jsonl"),
40597
+ searches: join3(directory, "searches.jsonl"),
40598
+ ledger: join3(directory, "spend-ledger.json"),
40599
+ updateCheck: join3(directory, "update-check.json")
40534
40600
  };
40535
40601
  }
40536
- function amount3(atomic) {
40537
- return { usd: formatBaseUnitsUsd(atomic), baseUnits: atomic.toString() };
40602
+ function isMissingFile(error61) {
40603
+ return error61 instanceof Error && "code" in error61 && error61.code === "ENOENT";
40538
40604
  }
40539
- function validateFeeBp(value) {
40540
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 1e4) {
40541
- throw new Error("Task fee basis points must be an integer from 0 to 10000.");
40542
- }
40605
+
40606
+ // src/audit.ts
40607
+ var AUDIT_FILE = "audit.log";
40608
+ function auditLogPath(home) {
40609
+ return join4(home, AUDIT_FILE);
40543
40610
  }
40544
- function parseBaseUnits(value) {
40545
- if (typeof value === "string" && !/^\d+$/u.test(value) || typeof value !== "bigint" && typeof value !== "string") {
40546
- throw new Error("Task base units must be a non-negative integer.");
40611
+ async function appendAudit(home, record3, options = {}) {
40612
+ const entry = {
40613
+ time: (options.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
40614
+ event: record3.event,
40615
+ ...record3.run === void 0 ? {} : { run: record3.run },
40616
+ ...record3.wallet === void 0 ? {} : { wallet: record3.wallet },
40617
+ ...record3.owner === void 0 ? {} : { owner: record3.owner },
40618
+ tty: record3.tty,
40619
+ ...record3.agentMarker === void 0 ? {} : { agentMarker: record3.agentMarker },
40620
+ ...record3.detail === void 0 ? {} : { detail: record3.detail }
40621
+ };
40622
+ const path = auditLogPath(home);
40623
+ await mkdir2(home, { recursive: true, mode: 448 });
40624
+ await appendFile(path, `${JSON.stringify(entry)}
40625
+ `, { encoding: "utf8", mode: 384 });
40626
+ await chmod(path, 384);
40627
+ return entry;
40628
+ }
40629
+
40630
+ // src/agent-link.ts
40631
+ var AGENT_LINK_REVOKED_MESSAGE = "This agent's link was revoked or has expired. Run vapi login to link it again.";
40632
+ var REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE = "The Railway run's short-lived vAPI access token expired. Start a new Railway run from the owner machine.";
40633
+ var AgentLinkError = class extends Error {
40634
+ constructor(code, message) {
40635
+ super(message);
40636
+ this.code = code;
40637
+ this.name = "AgentLinkError";
40547
40638
  }
40548
- const atomic = BigInt(value);
40549
- if (atomic < 0n) throw new Error("Task base units must be a non-negative integer.");
40550
- return atomic;
40639
+ code;
40640
+ };
40641
+ var DEFAULT_AGENT_SCOPES = ["mcp:call", "router.use"];
40642
+ var ALLOWED_AGENT_SCOPES = /* @__PURE__ */ new Set([
40643
+ ...DEFAULT_AGENT_SCOPES,
40644
+ "call.publish",
40645
+ "tasks:read",
40646
+ "tasks:write"
40647
+ ]);
40648
+ var publicFetch2 = createPublicFetch({ allowPrivateNetwork: false });
40649
+ var agentSecretAccounts = (wallet) => ({
40650
+ tokens: `vapi.agent.${wallet}.tokens`,
40651
+ routerStake: `vapi.agent.${wallet}.router.stake`,
40652
+ routerBalance: `vapi.agent.${wallet}.router.balance`
40653
+ });
40654
+ async function withCredentialPublishLock(wallets, wallet, operation) {
40655
+ const digest2 = createHash2("sha256").update(wallet).digest("hex").slice(0, 24);
40656
+ const lockPath = `${wallets.registryPath}.${digest2}.agent-publish.lock`;
40657
+ return await withCredentialLockFile(lockPath, operation);
40551
40658
  }
40552
- function taskPolicyAtomic(value) {
40553
- if (!Number.isFinite(value) || value < 0)
40554
- throw new Error("Task policy USD amounts must be finite and non-negative.");
40555
- const [mantissa = "0", exponent = "0"] = value.toString().split("e");
40556
- const [whole = "0", fraction = ""] = mantissa.split(".");
40557
- const digits = BigInt(whole + fraction);
40558
- const scale = 6 + Number(exponent) - fraction.length;
40559
- return scale >= 0 ? digits * 10n ** BigInt(scale) : digits / 10n ** BigInt(-scale);
40659
+ async function agentAccessToken(args) {
40660
+ return await resolveAgentAccessToken(args, {});
40560
40661
  }
40561
-
40562
- // src/tasks/plan-guard.ts
40563
- var TASKS_CHAIN_ABI = [
40564
- {
40565
- type: "function",
40566
- name: "createEscrow",
40567
- stateMutability: "nonpayable",
40568
- inputs: [
40569
- { name: "buyer", type: "address" },
40570
- { name: "token", type: "address" },
40571
- { name: "amount", type: "uint256" },
40572
- { name: "workDuration", type: "uint64" },
40573
- { name: "acceptanceWindow", type: "uint64" },
40574
- { name: "termsHash", type: "bytes32" },
40575
- { name: "salt", type: "bytes32" }
40576
- ],
40577
- outputs: [{ name: "escrow", type: "address" }]
40578
- },
40579
- {
40580
- type: "function",
40581
- name: "fundWithAuthorization",
40582
- stateMutability: "nonpayable",
40583
- inputs: [
40584
- { name: "validAfter", type: "uint256" },
40585
- { name: "validBefore", type: "uint256" },
40586
- { name: "nonce", type: "bytes32" },
40587
- { name: "signature", type: "bytes" }
40588
- ],
40589
- outputs: []
40590
- },
40591
- {
40592
- type: "function",
40593
- name: "approve",
40594
- stateMutability: "nonpayable",
40595
- inputs: [
40596
- { name: "spender", type: "address" },
40597
- { name: "amount", type: "uint256" }
40598
- ],
40599
- outputs: [{ name: "ok", type: "bool" }]
40600
- },
40601
- {
40602
- type: "function",
40603
- name: "depositFunds",
40604
- stateMutability: "nonpayable",
40605
- inputs: [],
40606
- outputs: []
40607
- },
40608
- {
40609
- type: "function",
40610
- name: "submitDelivery",
40611
- stateMutability: "nonpayable",
40612
- inputs: [{ name: "manifestHash", type: "bytes32" }],
40613
- outputs: []
40614
- },
40615
- {
40616
- type: "function",
40617
- name: "releaseFunds",
40618
- stateMutability: "nonpayable",
40619
- inputs: [],
40620
- outputs: []
40621
- },
40622
- { type: "function", name: "refundBuyer", stateMutability: "nonpayable", inputs: [], outputs: [] },
40623
- {
40624
- type: "function",
40625
- name: "raiseDispute",
40626
- stateMutability: "nonpayable",
40627
- inputs: [{ name: "evidenceHash", type: "bytes32" }],
40628
- outputs: []
40629
- },
40630
- {
40631
- type: "function",
40632
- name: "submitCounterEvidence",
40633
- stateMutability: "nonpayable",
40634
- inputs: [{ name: "evidenceHash", type: "bytes32" }],
40635
- outputs: []
40636
- },
40637
- {
40638
- type: "function",
40639
- name: "resolveUnmatchedDispute",
40640
- stateMutability: "nonpayable",
40641
- inputs: [],
40642
- outputs: []
40643
- },
40644
- {
40645
- type: "function",
40646
- name: "timeoutRefund",
40647
- stateMutability: "nonpayable",
40648
- inputs: [],
40649
- outputs: []
40650
- },
40651
- { type: "function", name: "finalize", stateMutability: "nonpayable", inputs: [], outputs: [] },
40652
- {
40653
- type: "function",
40654
- name: "disputeFee",
40655
- stateMutability: "view",
40656
- inputs: [],
40657
- outputs: [{ name: "fee", type: "uint256" }]
40658
- },
40659
- {
40660
- type: "function",
40661
- name: "allowance",
40662
- stateMutability: "view",
40663
- inputs: [
40664
- { name: "owner", type: "address" },
40665
- { name: "spender", type: "address" }
40666
- ],
40667
- outputs: [{ name: "amount", type: "uint256" }]
40662
+ async function resolveAgentAccessToken(args, options) {
40663
+ await args.wallets.reload();
40664
+ const link2 = args.wallets.entry(args.wallet)?.link;
40665
+ if (link2 === void 0 || !args.secrets.available) throw notLinkedError();
40666
+ const accounts = agentSecretAccounts(args.wallet);
40667
+ const tokens = parseTokens(await safeGetSecret(args.secrets, accounts.tokens));
40668
+ if (tokens === void 0) throw notLinkedError();
40669
+ const now = args.now ?? Date.now;
40670
+ if (options.rejectedAccessToken === void 0 && tokens.expiresAt - 6e4 > now()) {
40671
+ return tokens.accessToken;
40668
40672
  }
40669
- ];
40670
- var TASKS_READ_ABI = parseAbi([
40671
- "function paymentToken() view returns (address)",
40672
- "function isEscrow(address escrow) view returns (bool)",
40673
- "function name() view returns (string)",
40674
- "function version() view returns (string)",
40675
- "function buyer() view returns (address)",
40676
- "function seller() view returns (address)",
40677
- "function token() view returns (address)",
40678
- "function amount() view returns (uint256)",
40679
- "function termsHash() view returns (bytes32)",
40680
- "function state() view returns (uint8)",
40681
- "function offerDeadline() view returns (uint64)",
40682
- "function workDeadline() view returns (uint64)",
40683
- "function reviewDeadline() view returns (uint64)",
40684
- "function disputedAt() view returns (uint64)",
40685
- "function counterEvidenceDeadline() view returns (uint64)",
40686
- "function resolution() view returns (uint8)",
40687
- "function disputeFee() view returns (uint256)",
40688
- "function predictEscrow(address seller, bytes32 salt) view returns (address)"
40689
- ]);
40690
- function verifyPlan(operation, expectation) {
40691
- const fail2 = (message) => {
40692
- throw new TasksChainError(`Unsafe transaction plan: ${message}`, false);
40693
- };
40694
- const plan = operation.plan;
40695
- if (!plan) throw new TasksChainError("Unsafe transaction plan: missing plan", false);
40696
- if (plan.operationId !== operation.id || plan.step !== operation.step) fail2("operation mismatch");
40697
- if (!expectation.steps.includes(plan.step)) fail2("unexpected step");
40698
- if (!operation.expectedActor || getAddress(operation.expectedActor) !== getAddress(expectation.signer) || getAddress(plan.from) !== getAddress(expectation.signer))
40699
- fail2("unexpected signer");
40700
- if (plan.chainId !== expectation.deployment.chainId || plan.network !== expectation.deployment.network || plan.network !== `eip155:${plan.chainId}` || plan.value !== "0")
40701
- fail2("unexpected network or value");
40702
- if (expectation.milestone.network !== plan.network || expectation.milestone.asset.toLowerCase() !== `${plan.network}/erc20:${expectation.deployment.usdc}`.toLowerCase())
40703
- fail2("milestone asset mismatch");
40704
- const target = plan.step === "create-escrow" ? expectation.deployment.escrowContract : plan.step === "approve-usdc" ? expectation.deployment.usdc : expectation.milestone.escrowContract;
40705
- if (getAddress(plan.to) !== getAddress(target)) fail2("unexpected target");
40706
- const decoded = (() => {
40673
+ return await withAgentCredentialLock(args.wallets, link2.clientId, async () => {
40674
+ options.signal?.throwIfAborted();
40675
+ const { currentLink, currentAccounts, current } = await withCredentialPublishLock(
40676
+ args.wallets,
40677
+ args.wallet,
40678
+ async () => {
40679
+ await args.wallets.reload();
40680
+ const currentLink2 = args.wallets.entry(args.wallet)?.link;
40681
+ if (currentLink2 === void 0) throw notLinkedError();
40682
+ const currentAccounts2 = agentSecretAccounts(args.wallet);
40683
+ const current2 = parseTokens(await safeGetSecret(args.secrets, currentAccounts2.tokens));
40684
+ if (current2 === void 0) throw notLinkedError();
40685
+ return { currentLink: currentLink2, currentAccounts: currentAccounts2, current: current2 };
40686
+ }
40687
+ );
40688
+ if (options.rejectedAccessToken !== void 0 && current.accessToken !== options.rejectedAccessToken) {
40689
+ return current.accessToken;
40690
+ }
40691
+ if (options.rejectedAccessToken === void 0 && current.expiresAt - 6e4 > now()) {
40692
+ return current.accessToken;
40693
+ }
40694
+ const refreshToken = current.refreshToken;
40695
+ if (refreshToken === void 0) {
40696
+ throw new AgentLinkError("not_linked", REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE);
40697
+ }
40698
+ const { response, payload } = await abortable(options.signal, async () => {
40699
+ const response2 = await safeFetch(
40700
+ args.fetchImpl ?? publicFetch2,
40701
+ apiEndpoint(currentLink.apiBase, "/oauth/token"),
40702
+ {
40703
+ method: "POST",
40704
+ headers: { "content-type": "application/x-www-form-urlencoded" },
40705
+ body: new URLSearchParams({
40706
+ grant_type: "refresh_token",
40707
+ refresh_token: refreshToken,
40708
+ client_id: currentLink.clientId
40709
+ }),
40710
+ ...options.signal === void 0 ? {} : { signal: options.signal }
40711
+ }
40712
+ );
40713
+ return { response: response2, payload: await responseRecord(response2) };
40714
+ });
40715
+ if (!response.ok) {
40716
+ if (response.status === 400 && stringField(payload, "error") === "invalid_grant") {
40717
+ throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
40718
+ }
40719
+ throw httpError("The vAPI agent token refresh failed.");
40720
+ }
40721
+ const refreshed = {
40722
+ accessToken: requiredString(payload, "access_token"),
40723
+ refreshToken: stringField(payload, "refresh_token") ?? refreshToken,
40724
+ expiresAt: now() + requiredNumber(payload, "expires_in") * 1e3,
40725
+ scopes: stringField(payload, "scope") === void 0 ? [...current.scopes] : splitScopes(requiredString(payload, "scope"))
40726
+ };
40727
+ return await withCredentialPublishLock(args.wallets, args.wallet, async () => {
40728
+ await args.wallets.reload();
40729
+ if (args.wallets.entry(args.wallet)?.link === void 0) throw notLinkedError();
40730
+ const stored = parseTokens(await safeGetSecret(args.secrets, currentAccounts.tokens));
40731
+ if (stored === void 0 || stored.refreshToken !== refreshToken || stored.accessToken !== current.accessToken) {
40732
+ throw notLinkedError();
40733
+ }
40734
+ options.signal?.throwIfAborted();
40735
+ await safeSetSecret(args.secrets, currentAccounts.tokens, JSON.stringify(refreshed));
40736
+ return refreshed.accessToken;
40737
+ });
40738
+ });
40739
+ }
40740
+ async function abortable(signal, operation) {
40741
+ if (signal === void 0) return await operation();
40742
+ signal.throwIfAborted();
40743
+ let onAbort = () => void 0;
40744
+ const aborted2 = new Promise((_, reject) => {
40745
+ onAbort = () => reject(signal.reason);
40746
+ signal.addEventListener("abort", onAbort, { once: true });
40747
+ });
40748
+ try {
40749
+ return await Promise.race([operation(), aborted2]);
40750
+ } finally {
40751
+ signal.removeEventListener("abort", onAbort);
40752
+ }
40753
+ }
40754
+ async function withAgentCredentialLock(wallets, clientId, operation) {
40755
+ const digest2 = createHash2("sha256").update(clientId).digest("hex").slice(0, 24);
40756
+ const lockPath = `${wallets.registryPath}.${digest2}.agent-link.lock`;
40757
+ return await withCredentialLockFile(lockPath, operation);
40758
+ }
40759
+ async function withCredentialLockFile(lockPath, operation) {
40760
+ await mkdir3(dirname3(lockPath), { recursive: true, mode: 448 });
40761
+ const deadline = Date.now() + 3e4;
40762
+ let handle;
40763
+ while (!handle) {
40707
40764
  try {
40708
- return decodeFunctionData({ abi: TASKS_CHAIN_ABI, data: plan.data });
40709
- } catch {
40710
- return fail2("invalid calldata");
40765
+ handle = await open3(lockPath, "wx", 384);
40766
+ } catch (error61) {
40767
+ if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
40768
+ await removeStaleCredentialLock(lockPath);
40769
+ if (Date.now() >= deadline) {
40770
+ throw httpError("Timed out waiting to update the agent credentials.");
40771
+ }
40772
+ await new Promise((resolve) => setTimeout(resolve, 20));
40711
40773
  }
40712
- })();
40713
- const expectedName = {
40714
- "create-escrow": "createEscrow",
40715
- "fund-with-authorization": "fundWithAuthorization",
40716
- "approve-usdc": "approve",
40717
- "deposit-funds": "depositFunds",
40718
- "submit-delivery": "submitDelivery",
40719
- "release-funds": "releaseFunds",
40720
- "refund-buyer": "refundBuyer",
40721
- "raise-dispute": "raiseDispute",
40722
- "submit-counter-evidence": "submitCounterEvidence",
40723
- "resolve-unmatched-dispute": "resolveUnmatchedDispute",
40724
- "timeout-refund": "timeoutRefund",
40725
- finalize: "finalize"
40726
- };
40727
- if (decoded.functionName !== expectedName[plan.step]) fail2("unexpected selector");
40728
- const args = [...decoded.args ?? []];
40729
- const eq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
40730
- const requireArgs = (values) => {
40731
- if (args.length !== values.length || args.some((v, i2) => !eq(v, values[i2])))
40732
- fail2("unexpected arguments");
40733
- };
40734
- if (plan.step === "create-escrow") {
40735
- if (!expectation.seller || getAddress(expectation.signer) !== getAddress(expectation.seller))
40736
- fail2("createEscrow requires the locally bound seller");
40737
- const workDuration = expectation.workDurationSeconds ?? expectation.milestone.terms.workDurationSeconds ?? getTrustedTasksDurations(expectation.deployment.chainId).workDurationSeconds;
40738
- if (workDuration === void 0) fail2("missing trusted work duration");
40739
- requireArgs([
40740
- expectation.buyer,
40741
- expectation.deployment.usdc,
40742
- BigInt(expectation.milestone.amountBaseUnits),
40743
- BigInt(workDuration),
40744
- BigInt(
40745
- expectation.reviewWindowSeconds ?? expectation.milestone.terms.acceptanceWindowSeconds
40746
- ),
40747
- expectation.milestone.termsHash,
40748
- keccak256(stringToHex(expectation.milestone.id))
40749
- ]);
40750
- } else if (plan.step === "fund-with-authorization") {
40751
- const a = expectation.authorization;
40752
- if (!a)
40753
- throw new TasksChainError("Unsafe transaction plan: missing local authorization", false);
40754
- requireArgs([BigInt(a.validAfter), BigInt(a.validBefore), a.nonce, a.signature]);
40755
- } else if (plan.step === "approve-usdc") {
40756
- if (expectation.approveAmount === void 0) fail2("missing verified approval amount");
40757
- requireArgs([expectation.milestone.escrowContract, expectation.approveAmount]);
40758
- } else if (plan.step === "submit-delivery") {
40759
- if (!expectation.manifestHash) fail2("missing manifest hash");
40760
- requireArgs([expectation.manifestHash]);
40761
- } else if (plan.step === "raise-dispute" || plan.step === "submit-counter-evidence") {
40762
- if (!expectation.evidenceHash) fail2("missing evidence hash");
40763
- requireArgs([expectation.evidenceHash]);
40764
- } else requireArgs([]);
40774
+ }
40775
+ try {
40776
+ return await operation();
40777
+ } finally {
40778
+ await handle.close().catch(() => void 0);
40779
+ await unlink2(lockPath).catch(() => void 0);
40780
+ }
40765
40781
  }
40766
-
40767
- // src/tasks/chain-verification.ts
40768
- var TasksPartiesNotBoundError = class extends TasksValidationError {
40769
- constructor() {
40770
- super(
40771
- "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."
40772
- );
40773
- this.name = "TasksPartiesNotBoundError";
40782
+ async function removeStaleCredentialLock(path) {
40783
+ try {
40784
+ const metadata = await stat2(path);
40785
+ if (Date.now() - metadata.mtimeMs > 5 * 6e4) await unlink2(path);
40786
+ } catch {
40774
40787
  }
40775
- };
40776
- async function verifyDeployment(ready, rpc, overrides) {
40777
- const factory = getTrustedTasksFactory(ready.chainId, overrides);
40778
- if (!factory)
40779
- throw new TasksChainError(
40780
- `No trusted Tasks escrow factory is configured for chain ${ready.chainId}. Set VAPI_TASKS_ESCROW_FACTORY_${ready.chainId}.`,
40781
- false,
40782
- { authorizationExposed: false }
40783
- );
40784
- if (!isAddressEqual(factory, ready.escrowContract))
40785
- throw new TasksValidationError(
40786
- "The Tasks readiness factory does not match the trusted factory."
40787
- );
40788
- if (await rpc.getChainId() !== ready.chainId)
40789
- throw new TasksValidationError("The RPC chain ID does not match the task deployment.");
40790
- const token = await rpc.readContract({
40791
- address: factory,
40792
- abi: TASKS_READ_ABI,
40793
- functionName: "paymentToken"
40794
- });
40795
- if (!isAddressEqual(token, ready.usdc))
40796
- throw new TasksValidationError(
40797
- "The Tasks readiness token does not match the trusted factory payment token."
40798
- );
40799
- const [name, version5] = await Promise.all([
40800
- rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "name" }),
40801
- rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "version" })
40802
- ]);
40803
- const domain2 = { name, version: version5, chainId: ready.chainId, verifyingContract: getAddress(token) };
40804
- if (ready.eip3009Domain && (ready.eip3009Domain.name !== name || ready.eip3009Domain.version !== version5 || ready.eip3009Domain.chainId !== ready.chainId || !isAddressEqual(ready.eip3009Domain.verifyingContract, token)))
40805
- throw new TasksValidationError(
40806
- "The funding authorization domain does not match the onchain token domain."
40807
- );
40808
- return {
40809
- ...ready,
40810
- escrowContract: getAddress(factory),
40811
- usdc: getAddress(token),
40812
- eip3009Domain: domain2
40813
- };
40814
40788
  }
40815
- async function verifyScope(client, signer, selected, ready, verb, steps, options = {}) {
40816
- const { scopes } = await client.getScopes(selected.workOrderId);
40817
- const matches = scopes.filter(
40818
- (scope2) => scope2.state === "accepted" && scope2.milestoneId === selected.id
40819
- );
40820
- if (matches.length !== 1)
40821
- throw new TasksValidationError("The task milestone requires one accepted signed scope.");
40822
- const scope = matches[0];
40823
- const payload = scope.signingPayload;
40824
- const frozen = freezeScopeTerms(scope.structuredTerms, scope.brief);
40825
- 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)
40826
- throw new TasksValidationError(
40827
- "The accepted task scope does not match its locally verified terms hash and milestone."
40828
- );
40829
- if (!scope.counterpartyAddress || !scope.counterpartySignature || isAddressEqual(scope.proposerAddress, scope.counterpartyAddress) || !(isAddressEqual(signer, scope.proposerAddress) || isAddressEqual(signer, scope.counterpartyAddress)))
40830
- throw new TasksValidationError(
40831
- "The local signer is not one of the two accepted scope parties."
40832
- );
40833
- const message = canonicalJson(payload);
40834
- const signatures = await Promise.all([
40835
- verifyMessage({
40836
- address: scope.proposerAddress,
40837
- message,
40838
- signature: scope.proposerSignature
40839
- }),
40840
- verifyMessage({
40841
- address: scope.counterpartyAddress,
40842
- message,
40843
- signature: scope.counterpartySignature
40844
- })
40845
- ]);
40846
- if (signatures.some((valid) => !valid))
40847
- throw new TasksValidationError("Both accepted task scope signatures must verify.");
40848
- const terms = frozen.structured;
40849
- 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)
40850
- throw new TasksValidationError(
40851
- "The signed task scope asset, factory or amount does not match the deployment and milestone."
40852
- );
40853
- const identity = {
40854
- orderId: selected.workOrderId,
40855
- trancheOrdinal: selected.ordinal,
40856
- scopeVersion: scope.version,
40857
- termsHash: frozen.termsHash,
40858
- self: getAddress(signer)
40859
- };
40860
- const binding = await options.bindings?.get(identity);
40861
- if (!binding) throw new TasksPartiesNotBoundError();
40862
- if (options.counterparty && !isAddressEqual(binding.counterparty, options.counterparty))
40863
- throw new TasksValidationError(
40864
- "The confirmed counterparty differs from the locally bound parties."
40865
- );
40866
- 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(
40867
- (address9) => isAddressEqual(address9, binding.self) || isAddressEqual(address9, binding.counterparty)
40868
- ))
40869
- throw new TasksValidationError(
40870
- "The accepted scope parties do not match the locally bound parties."
40871
- );
40872
- const buyer = getAddress(binding.role === "client" ? binding.self : binding.counterparty);
40873
- const seller = getAddress(binding.role === "provider" ? binding.self : binding.counterparty);
40874
- if (verb === "createEscrow" && !isAddressEqual(signer, seller))
40875
- throw new TasksValidationError("Task createEscrow requires the locally bound seller's wallet.");
40876
- const workDurationSeconds = terms.workDurationSeconds ?? getTrustedTasksDurations(ready.chainId, options.trustedDurations).workDurationSeconds;
40877
- if (workDurationSeconds === void 0)
40878
- throw new TasksValidationError(
40879
- "The signed task scope has no work duration and no trusted default is configured."
40880
- );
40789
+ async function safeGetSecret(secrets, account) {
40790
+ try {
40791
+ return await secrets.get(account);
40792
+ } catch {
40793
+ throw httpError("The agent tokens could not be read from the OS secret store.");
40794
+ }
40795
+ }
40796
+ async function safeSetSecret(secrets, account, value) {
40797
+ try {
40798
+ await secrets.set(account, value);
40799
+ } catch {
40800
+ throw httpError("The agent credentials could not be stored in the OS secret store.");
40801
+ }
40802
+ }
40803
+ function parseTokens(value) {
40804
+ if (value === void 0) return void 0;
40805
+ let parsed;
40806
+ try {
40807
+ parsed = JSON.parse(value);
40808
+ } catch {
40809
+ return void 0;
40810
+ }
40811
+ if (!isRecord(parsed)) return void 0;
40812
+ const accessToken = stringField(parsed, "accessToken");
40813
+ const refreshToken = stringField(parsed, "refreshToken");
40814
+ const refreshable = parsed.refreshable;
40815
+ const expiresAt = numberField(parsed, "expiresAt");
40816
+ const scopes = parsed.scopes;
40817
+ if (accessToken === void 0 || expiresAt === void 0 || !Array.isArray(scopes) || scopes.some((scope) => typeof scope !== "string") || (refreshToken === void 0 ? refreshable !== false : refreshable === false)) {
40818
+ return void 0;
40819
+ }
40881
40820
  return {
40882
- signer,
40883
- buyer,
40884
- seller,
40885
- parties: [buyer, seller],
40886
- workDurationSeconds,
40887
- ...verb === "fund" ? { approveAmount: BigInt(terms.budget.amountBaseUnits) } : {},
40888
- reviewWindowSeconds: terms.acceptanceWindowSeconds,
40889
- nowSeconds: BigInt(Math.floor((options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() / 1e3)),
40890
- verb,
40891
- deployment: ready,
40892
- milestone: {
40893
- ...selected,
40894
- terms,
40895
- termsHash: frozen.termsHash,
40896
- amountBaseUnits: terms.budget.amountBaseUnits
40897
- },
40898
- steps
40821
+ accessToken,
40822
+ ...refreshToken === void 0 ? {} : { refreshToken },
40823
+ expiresAt,
40824
+ scopes
40899
40825
  };
40900
40826
  }
40901
- async function verifyClone(rpc, expected, checkState) {
40902
- if (expected.verb === "createEscrow") return;
40903
- const clone2 = expected.milestone.escrowContract;
40904
- const registered = await rpc.readContract({
40905
- address: expected.deployment.escrowContract,
40906
- abi: TASKS_READ_ABI,
40907
- functionName: "isEscrow",
40908
- args: [clone2]
40909
- });
40910
- if (!registered)
40911
- throw new TasksValidationError(
40912
- "The task escrow clone is not registered by the trusted factory."
40913
- );
40914
- const predicted = await rpc.readContract({
40915
- address: expected.deployment.escrowContract,
40916
- abi: TASKS_READ_ABI,
40917
- functionName: "predictEscrow",
40918
- args: [expected.seller, keccak256(stringToHex(expected.milestone.id))]
40919
- });
40920
- if (!isAddressEqual(predicted, clone2))
40921
- throw new TasksValidationError(
40922
- "The escrow clone does not match the signed milestone salt and bound seller."
40923
- );
40924
- const read = (functionName) => rpc.readContract({ address: clone2, abi: TASKS_READ_ABI, functionName });
40925
- const [
40926
- buyer,
40927
- seller,
40928
- token,
40929
- amount4,
40930
- termsHash,
40931
- state,
40932
- resolution,
40933
- offerDeadline,
40934
- workDeadline,
40935
- reviewDeadline,
40936
- disputedAt,
40937
- counterEvidenceDeadline,
40938
- slot0,
40939
- slot6,
40940
- slot7
40941
- ] = await Promise.all([
40942
- read("buyer"),
40943
- read("seller"),
40944
- read("token"),
40945
- read("amount"),
40946
- read("termsHash"),
40947
- read("state"),
40948
- read("resolution"),
40949
- read("offerDeadline"),
40950
- read("workDeadline"),
40951
- read("reviewDeadline"),
40952
- read("disputedAt"),
40953
- read("counterEvidenceDeadline"),
40954
- rpc.getStorageAt({ address: clone2, slot: "0x0" }),
40955
- rpc.getStorageAt({ address: clone2, slot: "0x6" }),
40956
- rpc.getStorageAt({ address: clone2, slot: "0x7" })
40957
- ]);
40958
- 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())
40959
- throw new TasksValidationError(
40960
- "The onchain escrow parties, token, amount or terms hash do not match the signed scope."
40961
- );
40962
- const s0 = storageWord(slot0);
40963
- const s6 = storageWord(slot6);
40964
- const s7 = storageWord(slot7);
40965
- 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)
40966
- throw new TasksValidationError("unsupported escrow layout");
40967
- if (field(s7, 8, 8) !== BigInt(expected.workDurationSeconds) || field(s7, 16, 8) !== BigInt(expected.reviewWindowSeconds))
40968
- throw new TasksValidationError(
40969
- "The onchain escrow durations do not match the signed terms and trusted defaults."
40970
- );
40971
- const actor = expected.verb === "fund" || expected.verb === "release" ? buyer : expected.verb === "deliver" || expected.verb === "refund" ? seller : expected.signer;
40972
- if (!isAddressEqual(actor, expected.signer))
40973
- throw new TasksValidationError(
40974
- `Task ${expected.verb} requires the onchain escrow party's local wallet.`
40975
- );
40976
- const states = {
40977
- fund: [1],
40978
- deliver: [2],
40979
- release: [3],
40980
- refund: [2, 3],
40981
- dispute: [2, 3],
40982
- "counter-evidence": [4],
40983
- "resolve-unmatched": [4]
40984
- };
40985
- if (checkState && !states[expected.verb]?.includes(state))
40986
- throw new TasksValidationError(
40987
- `The onchain escrow state is not eligible for task ${expected.verb}.`
40988
- );
40989
- if (["dispute", "counter-evidence"].includes(expected.verb)) {
40990
- const fee = disputeFeeBaseUnits(amount4);
40991
- if (await read("disputeFee") !== fee)
40992
- throw new TasksValidationError(
40993
- "The onchain dispute fee does not match the verified amount fee rule."
40827
+ async function safeFetch(fetchImpl, input2, init) {
40828
+ try {
40829
+ return await fetchImpl(input2, init);
40830
+ } catch (error61) {
40831
+ throw httpError(`The vAPI agent link request failed: ${networkFailure(error61, input2)}`);
40832
+ }
40833
+ }
40834
+ function networkFailure(error61, input2) {
40835
+ let url2;
40836
+ try {
40837
+ url2 = new URL(input2 instanceof Request ? input2.url : input2);
40838
+ } catch {
40839
+ return "the request did not reach vAPI.";
40840
+ }
40841
+ return describeNetworkFailure(error61, url2);
40842
+ }
40843
+ function notLinkedError() {
40844
+ return new AgentLinkError("not_linked", "Run vapi login first.");
40845
+ }
40846
+ function httpError(message) {
40847
+ return new AgentLinkError("http", message);
40848
+ }
40849
+ function apiEndpoint(apiBase, path) {
40850
+ return new URL(path, new URL(apiBase).origin).toString();
40851
+ }
40852
+ async function responseRecord(response) {
40853
+ let payload;
40854
+ try {
40855
+ payload = await response.json();
40856
+ } catch {
40857
+ if (!response.ok) return {};
40858
+ throw httpError("The vAPI agent link response was invalid.");
40859
+ }
40860
+ if (!isRecord(payload)) {
40861
+ if (!response.ok) return {};
40862
+ throw httpError("The vAPI agent link response was invalid.");
40863
+ }
40864
+ return payload;
40865
+ }
40866
+ function isRecord(value) {
40867
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40868
+ }
40869
+ function stringField(record3, key2) {
40870
+ const value = record3[key2];
40871
+ return typeof value === "string" ? value : void 0;
40872
+ }
40873
+ function numberField(record3, key2) {
40874
+ const value = record3[key2];
40875
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
40876
+ }
40877
+ function requiredString(record3, key2) {
40878
+ const value = stringField(record3, key2);
40879
+ if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
40880
+ return value;
40881
+ }
40882
+ function requiredNumber(record3, key2) {
40883
+ const value = numberField(record3, key2);
40884
+ if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
40885
+ return value;
40886
+ }
40887
+ function splitScopes(scope) {
40888
+ return scope.split(/\s+/u).filter(Boolean);
40889
+ }
40890
+
40891
+ // src/agent-profile.ts
40892
+ import { mkdir as mkdir4, readFile as readFile4, readdir as readdir2, rename as rename2, unlink as unlink3, writeFile } from "node:fs/promises";
40893
+ import { join as join5 } from "node:path";
40894
+
40895
+ // src/wallet-name.ts
40896
+ var DEFAULT_WALLET_NAME = "main";
40897
+ var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
40898
+ var walletNameSchema = external_exports.string().regex(
40899
+ WALLET_NAME_PATTERN,
40900
+ "A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
40901
+ );
40902
+
40903
+ // src/agent-profile.ts
40904
+ var DEFAULT_APPROVE_ABOVE_USD = 0.5;
40905
+ var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
40906
+ var AGENT_GRANTS = ["read", "delegate", "allocate"];
40907
+ var agentProfileShape = {
40908
+ version: external_exports.literal(1),
40909
+ name: walletNameSchema,
40910
+ wallet: external_exports.string(),
40911
+ model: external_exports.string().min(1),
40912
+ instructions: external_exports.string().max(2e4),
40913
+ verifiedOnly: external_exports.boolean().default(true),
40914
+ approveAboveUsd: external_exports.number().min(0).default(DEFAULT_APPROVE_ABOVE_USD),
40915
+ maxPerTaskUsd: external_exports.number().min(0).default(DEFAULT_MAX_PER_TASK_USD),
40916
+ autoReleaseBelowUsd: external_exports.number().min(0).default(DEFAULT_AUTO_RELEASE_BELOW_USD),
40917
+ maxSteps: external_exports.number().int().min(1).max(50).default(12),
40918
+ paused: external_exports.boolean().default(false),
40919
+ grants: external_exports.array(external_exports.enum(AGENT_GRANTS)).default([]),
40920
+ createdAt: external_exports.string()
40921
+ };
40922
+ function createAgentProfileSchema(toolNames) {
40923
+ if (toolNames.length === 0) {
40924
+ throw new Error("Agent profiles require at least one registered tool.");
40925
+ }
40926
+ const tools = [...toolNames];
40927
+ return external_exports.object({ ...agentProfileShape, tools: external_exports.array(external_exports.enum(tools)).default(tools) });
40928
+ }
40929
+ var agentProfileSchema = createAgentProfileSchema(DEFAULT_AGENT_TOOLS);
40930
+ async function listAgentProfiles(home, options = {}) {
40931
+ const directory = getVapiPaths(home).agentsDir;
40932
+ let files;
40933
+ try {
40934
+ files = await readdir2(directory);
40935
+ } catch (error61) {
40936
+ if (isMissingFile(error61)) return [];
40937
+ throw error61;
40938
+ }
40939
+ const warn = options.warn ?? ((message) => console.warn(message));
40940
+ const profiles = [];
40941
+ for (const file2 of files) {
40942
+ if (!file2.endsWith(".json")) continue;
40943
+ try {
40944
+ profiles.push(
40945
+ (options.schema ?? agentProfileSchema).parse(
40946
+ JSON.parse(await readFile4(join5(directory, file2), "utf8"))
40947
+ )
40994
40948
  );
40995
- expected.disputeFee = fee;
40996
- expected.approveAmount = fee;
40949
+ } catch {
40950
+ options.onInvalid?.(file2);
40951
+ warn(`Skipping invalid agent profile ${file2}.`);
40952
+ }
40997
40953
  }
40998
- if (checkState && ["counter-evidence", "resolve-unmatched"].includes(expected.verb)) {
40999
- const slot8 = storageWord(await rpc.getStorageAt({ address: clone2, slot: "0x8" }));
41000
- const opener = storageAddress(slot8, 0);
41001
- const submitted = field(slot8, 20, 1);
41002
- if (!isAddressEqual(opener, buyer) && !isAddressEqual(opener, seller) || submitted > 1n || field(slot8, 21, 11) !== 0n)
41003
- throw new TasksValidationError("unsupported escrow layout");
41004
- const now = expected.nowSeconds;
41005
- if (now === void 0)
41006
- throw new TasksValidationError("A trusted clock is required for dispute eligibility.");
41007
- if (submitted === 1n)
41008
- throw new TasksValidationError(
41009
- "Counter-evidence has already been submitted for this dispute."
40954
+ profiles.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
40955
+ return profiles;
40956
+ }
40957
+
40958
+ // src/spend-policy.ts
40959
+ import { randomBytes as randomBytes3 } from "node:crypto";
40960
+ import { mkdir as mkdir5, open as open4, readFile as readFile5, rename as rename3, stat as stat3, unlink as unlink4, writeFile as writeFile2 } from "node:fs/promises";
40961
+ import { dirname as dirname4 } from "node:path";
40962
+ var ledgerSchema = external_exports.object({
40963
+ date: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
40964
+ spentAtomic: external_exports.string().regex(/^\d+$/)
40965
+ });
40966
+ var spendReservationSchema = external_exports.object({
40967
+ id: external_exports.string().min(1),
40968
+ amountAtomic: external_exports.string().regex(/^\d+$/),
40969
+ kind: external_exports.enum(["payment", "escrow-funding", "dispute-fee"]).optional(),
40970
+ taskKey: external_exports.string().optional()
40971
+ });
40972
+ var ledgerRowSchema = ledgerSchema.extend({
40973
+ wallet: walletNameSchema.optional(),
40974
+ reservations: external_exports.array(spendReservationSchema).optional()
40975
+ });
40976
+ var ledgerFileSchema = external_exports.union([
40977
+ external_exports.object({ version: external_exports.literal(1), rows: external_exports.array(ledgerRowSchema) }),
40978
+ ledgerRowSchema
40979
+ ]);
40980
+ var SpendCapError = class extends Error {
40981
+ constructor(code, message, details) {
40982
+ super(message);
40983
+ this.code = code;
40984
+ this.details = details;
40985
+ this.name = "SpendCapError";
40986
+ }
40987
+ code;
40988
+ details;
40989
+ };
40990
+ function utcDateKey(now = /* @__PURE__ */ new Date()) {
40991
+ return now.toISOString().slice(0, 10);
40992
+ }
40993
+ async function escrowFundingDayRemainingAtomic(input2) {
40994
+ const perDayAtomic = parseAtomicCap(input2.caps.perDayAtomic, "per-day");
40995
+ const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now);
40996
+ const row = rows.find((candidate) => candidate.wallet === input2.wallet);
40997
+ const reserved = input2.reservationId ? row?.reservations?.find((candidate) => candidate.id === input2.reservationId) : void 0;
40998
+ const remaining = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
40999
+ return remaining > 0n ? remaining : 0n;
41000
+ }
41001
+ async function taskReservedAtomic(input2) {
41002
+ const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now, true);
41003
+ return sumTaskReservations(rows, input2.wallet, input2.taskKey, input2.excludeReservationId);
41004
+ }
41005
+ function sumTaskReservations(rows, wallet, taskKey, excludeReservationId) {
41006
+ let total = 0n;
41007
+ for (const row of rows) {
41008
+ if (row.wallet !== wallet) continue;
41009
+ for (const reservation of row.reservations ?? []) {
41010
+ if (reservation.taskKey === taskKey && reservation.id !== excludeReservationId)
41011
+ total += BigInt(reservation.amountAtomic);
41012
+ }
41013
+ }
41014
+ return total;
41015
+ }
41016
+ async function readStoredSpendLedgerRows(path, now, allDays = false) {
41017
+ let raw;
41018
+ try {
41019
+ raw = await readFile5(path, "utf8");
41020
+ } catch (error61) {
41021
+ if (isMissingFile(error61)) return [];
41022
+ throw error61;
41023
+ }
41024
+ const parsed = ledgerFileSchema.parse(JSON.parse(raw));
41025
+ const rows = "rows" in parsed ? parsed.rows : [parsed];
41026
+ const today = utcDateKey(now);
41027
+ return rows.filter((row) => allDays || row.date === today).map((row) => ({
41028
+ date: row.date,
41029
+ spentAtomic: row.spentAtomic,
41030
+ wallet: row.wallet ?? DEFAULT_WALLET_NAME,
41031
+ ...row.reservations === void 0 ? {} : { reservations: row.reservations }
41032
+ }));
41033
+ }
41034
+ async function reserveSpend(amountAtomic, caps, options) {
41035
+ if (amountAtomic < 0n) {
41036
+ throw new Error("Spend amount cannot be negative.");
41037
+ }
41038
+ const kind = options?.kind ?? "payment";
41039
+ let perDayAtomic;
41040
+ if (kind === "escrow-funding" || kind === "dispute-fee") {
41041
+ const maxPerTaskAtomic = options?.maxPerTaskAtomic;
41042
+ if (maxPerTaskAtomic === void 0 || maxPerTaskAtomic < 0n) {
41043
+ throw new Error("Escrow funding requires a non-negative per-task cap.");
41044
+ }
41045
+ if (amountAtomic > maxPerTaskAtomic) {
41046
+ throw new SpendCapError(
41047
+ "per_task_cap_exceeded",
41048
+ `Escrow funding ${amountAtomic} atomic USDC exceeds the per-task cap ${maxPerTaskAtomic}. Refusing to sign.`
41010
41049
  );
41011
- if (expected.verb === "counter-evidence") {
41012
- if (isAddressEqual(opener, expected.signer))
41013
- throw new TasksValidationError("Only the non-opener party can submit counter-evidence.");
41014
- if (now >= counterEvidenceDeadline)
41015
- throw new TasksValidationError("The counter-evidence deadline has passed.");
41016
- } else if (now <= counterEvidenceDeadline)
41017
- throw new TasksValidationError(
41018
- "The counter-evidence deadline has not passed; unmatched resolution is unavailable."
41050
+ }
41051
+ perDayAtomic = parseAtomicCap(caps.perDayAtomic, "per-day");
41052
+ } else {
41053
+ const perCallAtomic = parseAtomicCap(caps.perCallAtomic, "per-call");
41054
+ perDayAtomic = parseAtomicCap(caps.perDayAtomic, "per-day");
41055
+ if (amountAtomic > perCallAtomic) {
41056
+ throw new SpendCapError(
41057
+ "per_call_cap_exceeded",
41058
+ `Payment quote ${amountAtomic} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`,
41059
+ { amountAtomic, limitAtomic: perCallAtomic, wallet: options?.wallet }
41060
+ );
41061
+ }
41062
+ }
41063
+ const ledgerPath = options?.ledgerPath ?? getVapiPaths().ledger;
41064
+ const now = options?.now ?? /* @__PURE__ */ new Date();
41065
+ const wallet = options?.wallet ?? DEFAULT_WALLET_NAME;
41066
+ return await withLedgerLock(ledgerPath, async () => {
41067
+ const rows = await readStoredSpendLedgerRows(ledgerPath, now, true);
41068
+ const today = utcDateKey(now);
41069
+ const current = rows.find((row) => row.wallet === wallet && row.date === today);
41070
+ if ((kind === "escrow-funding" || kind === "dispute-fee") && options?.taskKey !== void 0) {
41071
+ const taskTotal = sumTaskReservations(
41072
+ rows,
41073
+ wallet,
41074
+ options.taskKey,
41075
+ options.reuseExistingEscrowReservation || options.resumeEscrowReservation ? options.reservationId : void 0
41076
+ ) + amountAtomic;
41077
+ if (taskTotal > options.maxPerTaskAtomic)
41078
+ throw new SpendCapError(
41079
+ "per_task_cap_exceeded",
41080
+ `New spend ${amountAtomic} atomic USDC would raise the running total for task ${options.taskKey} and wallet ${wallet} to ${taskTotal}, above the per-task cap ${options.maxPerTaskAtomic}. Refusing to sign.`
41081
+ );
41082
+ }
41083
+ if (options?.reservationId !== void 0) {
41084
+ const existing = current?.reservations?.find(
41085
+ (reservation) => reservation.id === options.reservationId
41086
+ );
41087
+ if (existing && options.reuseExistingEscrowReservation) {
41088
+ if (kind !== "escrow-funding" && kind !== "dispute-fee" || existing.kind !== kind || existing.amountAtomic !== amountAtomic.toString() || existing.taskKey !== void 0 && existing.taskKey !== options.taskKey)
41089
+ throw new Error(
41090
+ `Spend reservation ${options.reservationId} does not match this funding.`
41091
+ );
41092
+ if (existing.taskKey === void 0 && options.taskKey !== void 0) {
41093
+ existing.taskKey = options.taskKey;
41094
+ await writeLedgerAtomically(ledgerPath, rows);
41095
+ }
41096
+ return {
41097
+ date: current.date,
41098
+ spentAtomic: current.spentAtomic,
41099
+ reservationReused: true
41100
+ };
41101
+ }
41102
+ if (existing) {
41103
+ throw new Error(`Spend reservation ${options.reservationId} already exists.`);
41104
+ }
41105
+ if (options.resumeEscrowReservation) {
41106
+ const resumed = options.resumeEscrowReservation;
41107
+ const historical = rows.find((row) => row.wallet === wallet && row.date === resumed.date);
41108
+ const stored = historical?.reservations?.find(
41109
+ (reservation) => reservation.id === resumed.id
41110
+ );
41111
+ if (kind !== "escrow-funding" && kind !== "dispute-fee" || resumed.id !== options.reservationId || resumed.wallet !== wallet || resumed.amountAtomic !== amountAtomic.toString() || resumed.date >= utcDateKey(now) || resumed.exposed !== true || resumed.invalidated === true || stored !== void 0 && (stored.kind !== kind || stored.amountAtomic !== amountAtomic.toString() || stored.taskKey !== void 0 && stored.taskKey !== options.taskKey))
41112
+ throw new Error(
41113
+ `Spend reservation ${options.reservationId} does not match this funding.`
41114
+ );
41115
+ if (stored?.taskKey === void 0 && options.taskKey !== void 0) {
41116
+ if (stored) stored.taskKey = options.taskKey;
41117
+ else {
41118
+ const reservation = {
41119
+ id: resumed.id,
41120
+ amountAtomic: resumed.amountAtomic,
41121
+ kind,
41122
+ taskKey: options.taskKey
41123
+ };
41124
+ if (historical)
41125
+ historical.reservations = [...historical.reservations ?? [], reservation];
41126
+ else
41127
+ rows.push({
41128
+ date: resumed.date,
41129
+ spentAtomic: resumed.amountAtomic,
41130
+ wallet,
41131
+ reservations: [reservation]
41132
+ });
41133
+ }
41134
+ await writeLedgerAtomically(ledgerPath, rows);
41135
+ }
41136
+ return {
41137
+ date: resumed.date,
41138
+ spentAtomic: current?.spentAtomic ?? "0",
41139
+ reservationReused: true
41140
+ };
41141
+ }
41142
+ }
41143
+ const spentAtomic = current?.spentAtomic ?? "0";
41144
+ const nextSpent = BigInt(spentAtomic) + amountAtomic;
41145
+ if (nextSpent > perDayAtomic) {
41146
+ throw new SpendCapError(
41147
+ "per_day_cap_exceeded",
41148
+ `${kind === "escrow-funding" ? "Escrow funding" : "Payment quote"} ${amountAtomic} atomic USDC would raise today's spend to ${nextSpent} for wallet ${wallet}, above the per-day cap ${perDayAtomic}. Refusing to sign.`,
41149
+ { amountAtomic, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
41150
+ );
41151
+ }
41152
+ const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes3(16).toString("hex"));
41153
+ const nextRow = {
41154
+ date: utcDateKey(now),
41155
+ spentAtomic: nextSpent.toString(),
41156
+ wallet,
41157
+ ...(current?.reservations?.length ?? 0) === 0 && reservationId === void 0 ? {} : {
41158
+ reservations: [
41159
+ ...current?.reservations ?? [],
41160
+ ...reservationId === void 0 ? [] : [
41161
+ {
41162
+ id: reservationId,
41163
+ amountAtomic: amountAtomic.toString(),
41164
+ ...kind !== "payment" ? { kind } : {},
41165
+ ...options?.taskKey === void 0 ? {} : { taskKey: options.taskKey }
41166
+ }
41167
+ ]
41168
+ ]
41169
+ }
41170
+ };
41171
+ const otherRows = rows.filter((row) => row.wallet !== wallet || row.date !== today).map((row) => {
41172
+ if (row.wallet !== wallet || !options?.reuseExistingEscrowReservation || options.reservationId === void 0)
41173
+ return row;
41174
+ const previous = row.reservations?.find(
41175
+ (reservation) => reservation.id === options.reservationId
41019
41176
  );
41177
+ if (!previous) return row;
41178
+ if (kind !== "escrow-funding" && kind !== "dispute-fee" || previous.kind !== kind || previous.amountAtomic !== amountAtomic.toString() || previous.taskKey !== void 0 && previous.taskKey !== options.taskKey)
41179
+ throw new Error(
41180
+ `Spend reservation ${options.reservationId} does not match this funding.`
41181
+ );
41182
+ return {
41183
+ ...row,
41184
+ reservations: row.reservations.filter(
41185
+ (reservation) => reservation.id !== options.reservationId
41186
+ )
41187
+ };
41188
+ });
41189
+ const nextRows = [...otherRows, nextRow].sort(
41190
+ (a, b) => a.wallet.localeCompare(b.wallet) || a.date.localeCompare(b.date)
41191
+ );
41192
+ await writeLedgerAtomically(ledgerPath, nextRows);
41193
+ return {
41194
+ date: nextRow.date,
41195
+ spentAtomic: nextRow.spentAtomic,
41196
+ ...options?.reservationId === void 0 && reservationId !== void 0 ? { reservationId } : {}
41197
+ };
41198
+ });
41199
+ }
41200
+ async function releaseSpend(amountAtomic, options) {
41201
+ if (amountAtomic < 0n) {
41202
+ throw new Error("Spend amount cannot be negative.");
41020
41203
  }
41021
- expected.offerDeadline = offerDeadline;
41204
+ const ledgerPath = options.ledgerPath ?? getVapiPaths().ledger;
41205
+ const now = options.now ?? /* @__PURE__ */ new Date();
41206
+ const wallet = options.wallet ?? DEFAULT_WALLET_NAME;
41207
+ return await withLedgerLock(ledgerPath, async () => {
41208
+ const today = utcDateKey(now);
41209
+ const rows = await readStoredSpendLedgerRows(ledgerPath, now, true);
41210
+ const current = rows.find((row) => row.wallet === wallet && row.date === today);
41211
+ if (options.reservedOn !== today && options.reservationId === void 0) {
41212
+ return { date: today, spentAtomic: current?.spentAtomic ?? "0" };
41213
+ }
41214
+ const reserved = rows.find((row) => row.wallet === wallet && row.date === options.reservedOn);
41215
+ const reservation = options.reservationId === void 0 ? void 0 : reserved?.reservations?.find((candidate) => candidate.id === options.reservationId);
41216
+ if (options.reservationId !== void 0 && reservation === void 0) {
41217
+ return { date: today, spentAtomic: current?.spentAtomic ?? "0" };
41218
+ }
41219
+ if (reservation !== void 0 && reservation.amountAtomic !== amountAtomic.toString()) {
41220
+ throw new Error(`Spend reservation ${options.reservationId} has a different amount.`);
41221
+ }
41222
+ const spentAtomic = BigInt(reserved?.spentAtomic ?? "0");
41223
+ const releasedAmount = reservation === void 0 ? amountAtomic : BigInt(reservation.amountAtomic);
41224
+ const nextSpent = spentAtomic > releasedAmount ? spentAtomic - releasedAmount : 0n;
41225
+ const remainingReservations = reserved?.reservations?.filter(
41226
+ (candidate) => candidate.id !== options.reservationId
41227
+ );
41228
+ const nextRow = {
41229
+ date: options.reservedOn,
41230
+ spentAtomic: nextSpent.toString(),
41231
+ wallet,
41232
+ ...remainingReservations === void 0 || remainingReservations.length === 0 ? {} : { reservations: remainingReservations }
41233
+ };
41234
+ const nextRows = [
41235
+ ...rows.filter((row) => row.wallet !== wallet || row.date !== options.reservedOn),
41236
+ nextRow
41237
+ ].sort((a, b) => a.wallet.localeCompare(b.wallet) || a.date.localeCompare(b.date));
41238
+ await writeLedgerAtomically(ledgerPath, nextRows);
41239
+ return {
41240
+ date: today,
41241
+ spentAtomic: options.reservedOn === today ? nextRow.spentAtomic : current?.spentAtomic ?? "0"
41242
+ };
41243
+ });
41022
41244
  }
41023
- function storageWord(value) {
41024
- if (!value || !/^0x[0-9a-fA-F]{64}$/.test(value))
41025
- throw new TasksValidationError("unsupported escrow layout");
41245
+ function parseAtomicCap(value, label2) {
41246
+ if (!/^\d+$/.test(value)) {
41247
+ throw new Error(`Invalid ${label2} spend cap ${JSON.stringify(value)}.`);
41248
+ }
41026
41249
  return BigInt(value);
41027
41250
  }
41028
- function field(word, offset, bytes) {
41029
- return word >> BigInt(offset * 8) & (1n << BigInt(bytes * 8)) - 1n;
41251
+ async function writeLedgerAtomically(path, rows) {
41252
+ const ledger = rows.length === 1 && rows[0].wallet === DEFAULT_WALLET_NAME ? {
41253
+ date: rows[0].date,
41254
+ spentAtomic: rows[0].spentAtomic,
41255
+ ...rows[0].reservations === void 0 ? {} : { reservations: rows[0].reservations }
41256
+ } : { version: 1, rows };
41257
+ await mkdir5(dirname4(path), { recursive: true, mode: 448 });
41258
+ const temporaryPath = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}.tmp`;
41259
+ await writeFile2(temporaryPath, `${JSON.stringify(ledger, null, 2)}
41260
+ `, {
41261
+ encoding: "utf8",
41262
+ mode: 384,
41263
+ flag: "wx"
41264
+ });
41265
+ await rename3(temporaryPath, path);
41030
41266
  }
41031
- function storageAddress(word, offset) {
41032
- return getAddress(`0x${field(word, offset, 20).toString(16).padStart(40, "0")}`);
41267
+ async function withLedgerLock(path, operation) {
41268
+ await mkdir5(dirname4(path), { recursive: true, mode: 448 });
41269
+ const lockPath = `${path}.lock`;
41270
+ const deadline = Date.now() + 2e3;
41271
+ let handle;
41272
+ while (!handle) {
41273
+ try {
41274
+ handle = await open4(lockPath, "wx", 384);
41275
+ } catch (error61) {
41276
+ if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) {
41277
+ throw error61;
41278
+ }
41279
+ await removeStaleLock2(lockPath);
41280
+ if (Date.now() >= deadline) {
41281
+ throw new Error("Timed out waiting for the spend ledger lock.");
41282
+ }
41283
+ await new Promise((resolve) => setTimeout(resolve, 20));
41284
+ }
41285
+ }
41286
+ try {
41287
+ return await operation();
41288
+ } finally {
41289
+ await handle.close().catch(() => void 0);
41290
+ await unlink4(lockPath).catch(() => void 0);
41291
+ }
41292
+ }
41293
+ async function removeStaleLock2(path) {
41294
+ try {
41295
+ const metadata = await stat3(path);
41296
+ if (Date.now() - metadata.mtimeMs > 3e4) {
41297
+ await unlink4(path);
41298
+ }
41299
+ } catch (error61) {
41300
+ if (!isMissingFile(error61)) {
41301
+ throw error61;
41302
+ }
41303
+ }
41033
41304
  }
41034
41305
 
41035
41306
  // src/tasks/v2-abi.generated.ts
@@ -44223,1278 +44494,1074 @@ var feeRouterV1Abi = [
44223
44494
  {
44224
44495
  type: "error",
44225
44496
  name: "SafeERC20FailedOperation",
44226
- inputs: [{ name: "token", type: "address", internalType: "address" }]
44227
- }
44228
- ];
44229
-
44230
- // src/tasks/v2-abi.ts
44231
- var TASK_V2_CASE_STATE = {
44232
- None: 0,
44233
- Raised: 1,
44234
- Matched: 2,
44235
- JuryDrawPending: 3,
44236
- Voting: 4,
44237
- Resolved: 5,
44238
- Snapshotting: 6
44239
- };
44240
-
44241
- // src/tasks/operation-support.ts
44242
- import { readFile as readFile6, stat as stat4 } from "node:fs/promises";
44243
- import { basename as basename2, extname } from "node:path";
44244
-
44245
- // src/agent-link.ts
44246
- import { createHash as createHash3 } from "node:crypto";
44247
- import { mkdir as mkdir3, open as open3, stat as stat2, unlink as unlink2 } from "node:fs/promises";
44248
- import { dirname as dirname3 } from "node:path";
44249
-
44250
- // src/audit.ts
44251
- import { appendFile, chmod, mkdir as mkdir2, readFile as readFile3 } from "node:fs/promises";
44252
- import { join as join4 } from "node:path";
44253
-
44254
- // src/config.ts
44255
- import { homedir } from "node:os";
44256
- import { dirname as dirname2, join as join3 } from "node:path";
44257
- var DEFAULT_REGISTRY_URL = "https://api.vapinetwork.ai";
44258
- var DEFAULT_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/services`;
44259
- var DEFAULT_MARKETPLACE_DISCOVERY_URL = `${DEFAULT_REGISTRY_URL}/api/call/discovery`;
44260
- var DEFAULT_MAX_PER_TASK_USD = 100;
44261
- var DEFAULT_AUTO_RELEASE_BELOW_USD = 25;
44262
- var atomicString = external_exports.string().regex(/^\d+$/, "Expected non-negative atomic units.");
44263
- var spendCapsSchema = external_exports.object({
44264
- perCallAtomic: atomicString,
44265
- perDayAtomic: atomicString
44266
- });
44267
- var configSchema = external_exports.object({
44268
- discoveryUrl: external_exports.url(),
44269
- marketplaceDiscoveryUrl: external_exports.url().default(DEFAULT_MARKETPLACE_DISCOVERY_URL),
44270
- registryFallbacks: external_exports.array(
44271
- external_exports.object({
44272
- discoveryUrl: external_exports.url(),
44273
- marketplaceDiscoveryUrl: external_exports.url()
44274
- })
44275
- ).optional(),
44276
- allowPrivateNetwork: external_exports.boolean().default(false).optional(),
44277
- tasksEscrowDurationOverrides: external_exports.record(
44278
- external_exports.string().regex(/^\d+$/),
44279
- external_exports.object({
44280
- workDurationSeconds: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
44281
- reviewWindowSeconds: external_exports.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional()
44282
- }).strict()
44283
- ).optional(),
44284
- tasksEscrowFactoryOverrides: external_exports.record(external_exports.string().regex(/^\d+$/), external_exports.string()).optional(),
44285
- networks: external_exports.record(
44286
- external_exports.string().refine((network) => isSupportedPaymentNetwork(network), {
44287
- message: "Expected a supported eip155:<chainId> or Solana network identifier."
44288
- }),
44289
- external_exports.object({
44290
- rpcUrl: external_exports.string(),
44291
- usdc: external_exports.string().trim().min(1),
44292
- depositUrl: external_exports.url().optional(),
44293
- depositInstructions: external_exports.string().trim().min(1).max(500).optional(),
44294
- eip712Domain: external_exports.object({
44295
- name: external_exports.string().trim().min(1).max(64),
44296
- version: external_exports.string().trim().min(1).max(32)
44297
- }).optional()
44298
- })
44299
- ),
44300
- spendCaps: spendCapsSchema,
44301
- device: external_exports.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/).optional()
44302
- }).superRefine((config2, context) => {
44303
- for (const [chainId, factory] of Object.entries(config2.tasksEscrowFactoryOverrides ?? {})) {
44304
- try {
44305
- getAddress(factory);
44306
- } catch {
44307
- context.addIssue({
44308
- code: "custom",
44309
- path: ["tasksEscrowFactoryOverrides", chainId],
44310
- message: "Expected a valid EVM escrow factory address."
44311
- });
44312
- }
44313
- }
44314
- for (const [network, configured] of Object.entries(config2.networks)) {
44315
- if (isSolanaNetwork(network)) {
44316
- if (configured.usdc !== NETWORKS[SOLANA_MAINNET_CAIP2].usdc) {
44317
- context.addIssue({
44318
- code: "custom",
44319
- path: ["networks", network, "usdc"],
44320
- message: "Expected canonical Solana mainnet USDC mint."
44321
- });
44322
- }
44323
- continue;
44324
- }
44325
- try {
44326
- const usdc = getAddress(configured.usdc);
44327
- if ((network === ARC_MAINNET_CAIP2 || network === ARC_TESTNET_CAIP2) && usdc !== getAddress(NETWORKS[network].usdc)) {
44328
- context.addIssue({
44329
- code: "custom",
44330
- path: ["networks", network, "usdc"],
44331
- message: "Expected the canonical Arc USDC predeploy."
44332
- });
44333
- }
44334
- } catch {
44335
- context.addIssue({
44336
- code: "custom",
44337
- path: ["networks", network, "usdc"],
44338
- message: "Expected a valid EVM USDC contract address."
44339
- });
44340
- }
44341
- }
44342
- });
44343
- function getVapiPaths(directory = process.env.VAPI_HOME?.trim() || join3(homedir(), ".vapi")) {
44344
- return {
44345
- directory,
44346
- agentsDir: join3(directory, "agents"),
44347
- config: join3(directory, "config.json"),
44348
- keystore: join3(directory, "keystore.json"),
44349
- receipts: join3(directory, "receipts.jsonl"),
44350
- searches: join3(directory, "searches.jsonl"),
44351
- ledger: join3(directory, "spend-ledger.json"),
44352
- updateCheck: join3(directory, "update-check.json")
44353
- };
44354
- }
44355
- function isMissingFile(error61) {
44356
- return error61 instanceof Error && "code" in error61 && error61.code === "ENOENT";
44357
- }
44497
+ inputs: [{ name: "token", type: "address", internalType: "address" }]
44498
+ }
44499
+ ];
44358
44500
 
44359
- // src/audit.ts
44360
- var AUDIT_FILE = "audit.log";
44361
- function auditLogPath(home) {
44362
- return join4(home, AUDIT_FILE);
44363
- }
44364
- async function appendAudit(home, record3, options = {}) {
44365
- const entry = {
44366
- time: (options.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
44367
- event: record3.event,
44368
- ...record3.run === void 0 ? {} : { run: record3.run },
44369
- ...record3.wallet === void 0 ? {} : { wallet: record3.wallet },
44370
- ...record3.owner === void 0 ? {} : { owner: record3.owner },
44371
- tty: record3.tty,
44372
- ...record3.agentMarker === void 0 ? {} : { agentMarker: record3.agentMarker },
44373
- ...record3.detail === void 0 ? {} : { detail: record3.detail }
44374
- };
44375
- const path = auditLogPath(home);
44376
- await mkdir2(home, { recursive: true, mode: 448 });
44377
- await appendFile(path, `${JSON.stringify(entry)}
44378
- `, { encoding: "utf8", mode: 384 });
44379
- await chmod(path, 384);
44380
- return entry;
44381
- }
44501
+ // src/tasks/v2-abi.ts
44502
+ var TASK_V2_CASE_STATE = {
44503
+ None: 0,
44504
+ Raised: 1,
44505
+ Matched: 2,
44506
+ JuryDrawPending: 3,
44507
+ Voting: 4,
44508
+ Resolved: 5,
44509
+ Snapshotting: 6
44510
+ };
44382
44511
 
44383
- // src/agent-link.ts
44384
- var AGENT_LINK_REVOKED_MESSAGE = "This agent's link was revoked or has expired. Run vapi login to link it again.";
44385
- var REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE = "The Railway run's short-lived vAPI access token expired. Start a new Railway run from the owner machine.";
44386
- var AgentLinkError = class extends Error {
44387
- constructor(code, message) {
44388
- super(message);
44389
- this.code = code;
44390
- this.name = "AgentLinkError";
44391
- }
44392
- code;
44512
+ // src/tasks/v2-events.ts
44513
+ var TASKS_V2_EVENT_ABIS = {
44514
+ EscrowFactoryV2: escrowFactoryV2Abi,
44515
+ EscrowV2: escrowV2Abi,
44516
+ BountyEscrowV2: bountyEscrowV2Abi,
44517
+ DisputeResolverV3: disputeResolverV3Abi,
44518
+ BountyPoolFactoryV1: bountyPoolFactoryV1Abi,
44519
+ BountyPoolV1: bountyPoolV1Abi,
44520
+ ReviewerRegistryV2: reviewerRegistryV2Abi,
44521
+ OutcomeRegistryV1: outcomeRegistryV1Abi,
44522
+ FeeRouterV1: feeRouterV1Abi
44393
44523
  };
44394
- var DEFAULT_AGENT_SCOPES = ["mcp:call", "router.use"];
44395
- var ALLOWED_AGENT_SCOPES = /* @__PURE__ */ new Set([
44396
- ...DEFAULT_AGENT_SCOPES,
44397
- "call.publish",
44398
- "tasks:read",
44399
- "tasks:write"
44400
- ]);
44401
- var publicFetch2 = createPublicFetch({ allowPrivateNetwork: false });
44402
- var agentSecretAccounts = (wallet) => ({
44403
- tokens: `vapi.agent.${wallet}.tokens`,
44404
- routerStake: `vapi.agent.${wallet}.router.stake`,
44405
- routerBalance: `vapi.agent.${wallet}.router.balance`
44406
- });
44407
- async function withCredentialPublishLock(wallets, wallet, operation) {
44408
- const digest2 = createHash3("sha256").update(wallet).digest("hex").slice(0, 24);
44409
- const lockPath = `${wallets.registryPath}.${digest2}.agent-publish.lock`;
44410
- return await withCredentialLockFile(lockPath, operation);
44411
- }
44412
- async function agentAccessToken(args) {
44413
- return await resolveAgentAccessToken(args, {});
44524
+ function decodeTaskV2Event(contract, log) {
44525
+ const decoded = decodeEventLog({ abi: TASKS_V2_EVENT_ABIS[contract], ...log, strict: true });
44526
+ return normalizeTaskV2Outcomes(decoded);
44414
44527
  }
44415
- async function resolveAgentAccessToken(args, options) {
44416
- await args.wallets.reload();
44417
- const link2 = args.wallets.entry(args.wallet)?.link;
44418
- if (link2 === void 0 || !args.secrets.available) throw notLinkedError();
44419
- const accounts = agentSecretAccounts(args.wallet);
44420
- const tokens = parseTokens(await safeGetSecret(args.secrets, accounts.tokens));
44421
- if (tokens === void 0) throw notLinkedError();
44422
- const now = args.now ?? Date.now;
44423
- if (options.rejectedAccessToken === void 0 && tokens.expiresAt - 6e4 > now()) {
44424
- return tokens.accessToken;
44425
- }
44426
- return await withAgentCredentialLock(args.wallets, link2.clientId, async () => {
44427
- options.signal?.throwIfAborted();
44428
- const { currentLink, currentAccounts, current } = await withCredentialPublishLock(
44429
- args.wallets,
44430
- args.wallet,
44431
- async () => {
44432
- await args.wallets.reload();
44433
- const currentLink2 = args.wallets.entry(args.wallet)?.link;
44434
- if (currentLink2 === void 0) throw notLinkedError();
44435
- const currentAccounts2 = agentSecretAccounts(args.wallet);
44436
- const current2 = parseTokens(await safeGetSecret(args.secrets, currentAccounts2.tokens));
44437
- if (current2 === void 0) throw notLinkedError();
44438
- return { currentLink: currentLink2, currentAccounts: currentAccounts2, current: current2 };
44439
- }
44528
+ var TASK_V2_NO_VERDICT_SUMMARY = "Disputed: status quo final after round 2 without a verdict; no dispute winner.";
44529
+ var TASK_V2_REVIEWER_GUIDANCE = "mayVote reports jury membership only. Do not touch your stake until you have revealed; even a cancelled unstake can cost the vote.";
44530
+ var TASK_V2_JURY_RULES = "Fewer than 3 eligible reviewers ends the round immediately. With 3 to 20 eligible reviewers everyone eligible is in the jury; above 20, 5 are drawn. A verdict needs at least 3 reveals and a strict majority. Round 1 without a verdict restores the pre-dispute state. Round 2 without a verdict makes the status quo final: disputed, with no dispute winner. Draw strictly after the seed block through HISTORY_WINDOW (8,191 blocks); rearm only after that window, at most 3 times. The next expired attempt ends the round. No mediation or appeal.";
44531
+ function normalizeTaskV2Outcomes(value) {
44532
+ const walk3 = (item) => {
44533
+ if (Array.isArray(item)) return item.map(walk3);
44534
+ if (item === null || typeof item !== "object") return item;
44535
+ const source = item;
44536
+ const result = Object.fromEntries(
44537
+ Object.entries(source).map(([key2, entry]) => [key2, walk3(entry)])
44440
44538
  );
44441
- if (options.rejectedAccessToken !== void 0 && current.accessToken !== options.rejectedAccessToken) {
44442
- return current.accessToken;
44443
- }
44444
- if (options.rejectedAccessToken === void 0 && current.expiresAt - 6e4 > now()) {
44445
- return current.accessToken;
44446
- }
44447
- const refreshToken = current.refreshToken;
44448
- if (refreshToken === void 0) {
44449
- throw new AgentLinkError("not_linked", REMOTE_AGENT_TOKEN_EXPIRED_MESSAGE);
44450
- }
44451
- const { response, payload } = await abortable(options.signal, async () => {
44452
- const response2 = await safeFetch(
44453
- args.fetchImpl ?? publicFetch2,
44454
- apiEndpoint(currentLink.apiBase, "/oauth/token"),
44455
- {
44456
- method: "POST",
44457
- headers: { "content-type": "application/x-www-form-urlencoded" },
44458
- body: new URLSearchParams({
44459
- grant_type: "refresh_token",
44460
- refresh_token: refreshToken,
44461
- client_id: currentLink.clientId
44462
- }),
44463
- ...options.signal === void 0 ? {} : { signal: options.signal }
44464
- }
44465
- );
44466
- return { response: response2, payload: await responseRecord(response2) };
44467
- });
44468
- if (!response.ok) {
44469
- if (response.status === 400 && stringField(payload, "error") === "invalid_grant") {
44470
- throw new AgentLinkError("not_linked", AGENT_LINK_REVOKED_MESSAGE);
44471
- }
44472
- throw httpError("The vAPI agent token refresh failed.");
44539
+ if (source.cause === 6 || source.cause === "6" || source.cause === 6n) {
44540
+ result.disputed = true;
44541
+ result.disputeWinner = 0;
44542
+ result.summary = TASK_V2_NO_VERDICT_SUMMARY;
44473
44543
  }
44474
- const refreshed = {
44475
- accessToken: requiredString(payload, "access_token"),
44476
- refreshToken: stringField(payload, "refresh_token") ?? refreshToken,
44477
- expiresAt: now() + requiredNumber(payload, "expires_in") * 1e3,
44478
- scopes: stringField(payload, "scope") === void 0 ? [...current.scopes] : splitScopes(requiredString(payload, "scope"))
44479
- };
44480
- return await withCredentialPublishLock(args.wallets, args.wallet, async () => {
44481
- await args.wallets.reload();
44482
- if (args.wallets.entry(args.wallet)?.link === void 0) throw notLinkedError();
44483
- const stored = parseTokens(await safeGetSecret(args.secrets, currentAccounts.tokens));
44484
- if (stored === void 0 || stored.refreshToken !== refreshToken || stored.accessToken !== current.accessToken) {
44485
- throw notLinkedError();
44486
- }
44487
- options.signal?.throwIfAborted();
44488
- await safeSetSecret(args.secrets, currentAccounts.tokens, JSON.stringify(refreshed));
44489
- return refreshed.accessToken;
44490
- });
44491
- });
44492
- }
44493
- async function abortable(signal, operation) {
44494
- if (signal === void 0) return await operation();
44495
- signal.throwIfAborted();
44496
- let onAbort = () => void 0;
44497
- const aborted2 = new Promise((_, reject) => {
44498
- onAbort = () => reject(signal.reason);
44499
- signal.addEventListener("abort", onAbort, { once: true });
44500
- });
44501
- try {
44502
- return await Promise.race([operation(), aborted2]);
44503
- } finally {
44504
- signal.removeEventListener("abort", onAbort);
44505
- }
44506
- }
44507
- async function withAgentCredentialLock(wallets, clientId, operation) {
44508
- const digest2 = createHash3("sha256").update(clientId).digest("hex").slice(0, 24);
44509
- const lockPath = `${wallets.registryPath}.${digest2}.agent-link.lock`;
44510
- return await withCredentialLockFile(lockPath, operation);
44511
- }
44512
- async function withCredentialLockFile(lockPath, operation) {
44513
- await mkdir3(dirname3(lockPath), { recursive: true, mode: 448 });
44514
- const deadline = Date.now() + 3e4;
44515
- let handle;
44516
- while (!handle) {
44517
- try {
44518
- handle = await open3(lockPath, "wx", 384);
44519
- } catch (error61) {
44520
- if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) throw error61;
44521
- await removeStaleCredentialLock(lockPath);
44522
- if (Date.now() >= deadline) {
44523
- throw httpError("Timed out waiting to update the agent credentials.");
44524
- }
44525
- await new Promise((resolve) => setTimeout(resolve, 20));
44544
+ if (typeof source.mayVote === "boolean") {
44545
+ result.juryMember = source.mayVote;
44546
+ result.mayVoteMeaning = "jury membership only";
44547
+ result.reviewerGuidance = TASK_V2_REVIEWER_GUIDANCE;
44526
44548
  }
44527
- }
44528
- try {
44529
- return await operation();
44530
- } finally {
44531
- await handle.close().catch(() => void 0);
44532
- await unlink2(lockPath).catch(() => void 0);
44533
- }
44534
- }
44535
- async function removeStaleCredentialLock(path) {
44536
- try {
44537
- const metadata = await stat2(path);
44538
- if (Date.now() - metadata.mtimeMs > 5 * 6e4) await unlink2(path);
44539
- } catch {
44540
- }
44541
- }
44542
- async function safeGetSecret(secrets, account) {
44543
- try {
44544
- return await secrets.get(account);
44545
- } catch {
44546
- throw httpError("The agent tokens could not be read from the OS secret store.");
44547
- }
44548
- }
44549
- async function safeSetSecret(secrets, account, value) {
44550
- try {
44551
- await secrets.set(account, value);
44552
- } catch {
44553
- throw httpError("The agent credentials could not be stored in the OS secret store.");
44554
- }
44555
- }
44556
- function parseTokens(value) {
44557
- if (value === void 0) return void 0;
44558
- let parsed;
44559
- try {
44560
- parsed = JSON.parse(value);
44561
- } catch {
44562
- return void 0;
44563
- }
44564
- if (!isRecord(parsed)) return void 0;
44565
- const accessToken = stringField(parsed, "accessToken");
44566
- const refreshToken = stringField(parsed, "refreshToken");
44567
- const refreshable = parsed.refreshable;
44568
- const expiresAt = numberField(parsed, "expiresAt");
44569
- const scopes = parsed.scopes;
44570
- if (accessToken === void 0 || expiresAt === void 0 || !Array.isArray(scopes) || scopes.some((scope) => typeof scope !== "string") || (refreshToken === void 0 ? refreshable !== false : refreshable === false)) {
44571
- return void 0;
44572
- }
44573
- return {
44574
- accessToken,
44575
- ...refreshToken === void 0 ? {} : { refreshToken },
44576
- expiresAt,
44577
- scopes
44549
+ return result;
44578
44550
  };
44551
+ return walk3(value);
44579
44552
  }
44580
- async function safeFetch(fetchImpl, input2, init) {
44581
- try {
44582
- return await fetchImpl(input2, init);
44583
- } catch (error61) {
44584
- throw httpError(`The vAPI agent link request failed: ${networkFailure(error61, input2)}`);
44585
- }
44586
- }
44587
- function networkFailure(error61, input2) {
44588
- let url2;
44589
- try {
44590
- url2 = new URL(input2 instanceof Request ? input2.url : input2);
44591
- } catch {
44592
- return "the request did not reach vAPI.";
44593
- }
44594
- return describeNetworkFailure(error61, url2);
44595
- }
44596
- function notLinkedError() {
44597
- return new AgentLinkError("not_linked", "Run vapi login first.");
44598
- }
44599
- function httpError(message) {
44600
- return new AgentLinkError("http", message);
44553
+ function taskV2OutcomeLines(value) {
44554
+ if (!value || typeof value !== "object") return [];
44555
+ const source = value;
44556
+ if (source.cause === 6 || source.cause === "6" || source.cause === 6n)
44557
+ return [TASK_V2_NO_VERDICT_SUMMARY];
44558
+ return [...new Set(Object.values(source).flatMap(taskV2OutcomeLines))];
44601
44559
  }
44602
- function apiEndpoint(apiBase, path) {
44603
- return new URL(path, new URL(apiBase).origin).toString();
44560
+
44561
+ // src/tasks/money.ts
44562
+ function formatBaseUnitsUsd(baseUnits2) {
44563
+ const [whole, fraction = ""] = formatUsdc(parseBaseUnits(baseUnits2)).split(".");
44564
+ return `${whole}.${fraction.padEnd(2, "0")}`;
44604
44565
  }
44605
- async function responseRecord(response) {
44606
- let payload;
44607
- try {
44608
- payload = await response.json();
44609
- } catch {
44610
- if (!response.ok) return {};
44611
- throw httpError("The vAPI agent link response was invalid.");
44612
- }
44613
- if (!isRecord(payload)) {
44614
- if (!response.ok) return {};
44615
- throw httpError("The vAPI agent link response was invalid.");
44566
+ function parseUsdToBaseUnits(text) {
44567
+ if (!/^\d+(?:\.\d{1,6})?$/u.test(text)) {
44568
+ throw new Error(
44569
+ "Task USD amount must be a non-negative decimal with at most six decimal places."
44570
+ );
44616
44571
  }
44617
- return payload;
44618
- }
44619
- function isRecord(value) {
44620
- return typeof value === "object" && value !== null && !Array.isArray(value);
44621
- }
44622
- function stringField(record3, key2) {
44623
- const value = record3[key2];
44624
- return typeof value === "string" ? value : void 0;
44625
- }
44626
- function numberField(record3, key2) {
44627
- const value = record3[key2];
44628
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
44572
+ const [whole = "0", fraction = ""] = text.split(".");
44573
+ return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
44629
44574
  }
44630
- function requiredString(record3, key2) {
44631
- const value = stringField(record3, key2);
44632
- if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
44633
- return value;
44575
+ function parseFeeBp(deploymentOrReadiness) {
44576
+ if (typeof deploymentOrReadiness !== "object" || deploymentOrReadiness === null || !("feeBp" in deploymentOrReadiness)) {
44577
+ return null;
44578
+ }
44579
+ const feeBp = deploymentOrReadiness.feeBp;
44580
+ if (feeBp === void 0 || feeBp === null) return null;
44581
+ validateFeeBp(feeBp);
44582
+ return feeBp;
44634
44583
  }
44635
- function requiredNumber(record3, key2) {
44636
- const value = numberField(record3, key2);
44637
- if (value === void 0) throw httpError("The vAPI agent link response was invalid.");
44638
- return value;
44584
+ function taskMoney(grossBaseUnits, feeBp) {
44585
+ const atomic = parseBaseUnits(grossBaseUnits);
44586
+ const gross = amount3(atomic);
44587
+ if (feeBp === null) {
44588
+ return { gross, fee: null, net: null, feeBp, line: `$${gross.usd} gross \xB7 fee unavailable` };
44589
+ }
44590
+ validateFeeBp(feeBp);
44591
+ const feeAtomic = atomic * BigInt(feeBp) / 10000n;
44592
+ const fee = amount3(feeAtomic);
44593
+ const net = amount3(atomic - feeAtomic);
44594
+ return {
44595
+ gross,
44596
+ fee,
44597
+ net,
44598
+ feeBp,
44599
+ line: `$${gross.usd} gross \xB7 $${fee.usd} fee \xB7 $${net.usd} net`
44600
+ };
44639
44601
  }
44640
- function splitScopes(scope) {
44641
- return scope.split(/\s+/u).filter(Boolean);
44602
+ function amount3(atomic) {
44603
+ return { usd: formatBaseUnitsUsd(atomic), baseUnits: atomic.toString() };
44642
44604
  }
44643
-
44644
- // src/agent-profile.ts
44645
- import { mkdir as mkdir4, readFile as readFile4, readdir as readdir2, rename as rename2, unlink as unlink3, writeFile } from "node:fs/promises";
44646
- import { join as join5 } from "node:path";
44647
-
44648
- // src/wallet-name.ts
44649
- var DEFAULT_WALLET_NAME = "main";
44650
- var WALLET_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/;
44651
- var walletNameSchema = external_exports.string().regex(
44652
- WALLET_NAME_PATTERN,
44653
- "A wallet name is 1 to 32 characters of lowercase letters, digits and dashes, starting with a letter or digit."
44654
- );
44655
-
44656
- // src/agent-profile.ts
44657
- var DEFAULT_AGENT_TOOLS = ["call.search", "call.inspect", "call.pay"];
44658
- var AGENT_GRANTS = ["read", "delegate", "allocate"];
44659
- var agentProfileShape = {
44660
- version: external_exports.literal(1),
44661
- name: walletNameSchema,
44662
- wallet: external_exports.string(),
44663
- model: external_exports.string().min(1),
44664
- instructions: external_exports.string().max(2e4),
44665
- verifiedOnly: external_exports.boolean().default(true),
44666
- approveAboveUsd: external_exports.number().min(0).default(0.5),
44667
- maxPerTaskUsd: external_exports.number().min(0).default(DEFAULT_MAX_PER_TASK_USD),
44668
- autoReleaseBelowUsd: external_exports.number().min(0).default(DEFAULT_AUTO_RELEASE_BELOW_USD),
44669
- maxSteps: external_exports.number().int().min(1).max(50).default(12),
44670
- paused: external_exports.boolean().default(false),
44671
- grants: external_exports.array(external_exports.enum(AGENT_GRANTS)).default([]),
44672
- createdAt: external_exports.string()
44673
- };
44674
- function createAgentProfileSchema(toolNames) {
44675
- if (toolNames.length === 0) {
44676
- throw new Error("Agent profiles require at least one registered tool.");
44605
+ function validateFeeBp(value) {
44606
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 1e4) {
44607
+ throw new Error("Task fee basis points must be an integer from 0 to 10000.");
44677
44608
  }
44678
- const tools = [...toolNames];
44679
- return external_exports.object({ ...agentProfileShape, tools: external_exports.array(external_exports.enum(tools)).default(tools) });
44680
44609
  }
44681
- var agentProfileSchema = createAgentProfileSchema(DEFAULT_AGENT_TOOLS);
44682
- async function listAgentProfiles(home, options = {}) {
44683
- const directory = getVapiPaths(home).agentsDir;
44684
- let files;
44685
- try {
44686
- files = await readdir2(directory);
44687
- } catch (error61) {
44688
- if (isMissingFile(error61)) return [];
44689
- throw error61;
44690
- }
44691
- const warn = options.warn ?? ((message) => console.warn(message));
44692
- const profiles = [];
44693
- for (const file2 of files) {
44694
- if (!file2.endsWith(".json")) continue;
44695
- try {
44696
- profiles.push(
44697
- (options.schema ?? agentProfileSchema).parse(
44698
- JSON.parse(await readFile4(join5(directory, file2), "utf8"))
44699
- )
44700
- );
44701
- } catch {
44702
- options.onInvalid?.(file2);
44703
- warn(`Skipping invalid agent profile ${file2}.`);
44704
- }
44610
+ function parseBaseUnits(value) {
44611
+ if (typeof value === "string" && !/^\d+$/u.test(value) || typeof value !== "bigint" && typeof value !== "string") {
44612
+ throw new Error("Task base units must be a non-negative integer.");
44705
44613
  }
44706
- profiles.sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
44707
- return profiles;
44614
+ const atomic = BigInt(value);
44615
+ if (atomic < 0n) throw new Error("Task base units must be a non-negative integer.");
44616
+ return atomic;
44617
+ }
44618
+ function taskPolicyAtomic(value) {
44619
+ if (!Number.isFinite(value) || value < 0)
44620
+ throw new Error("Task policy USD amounts must be finite and non-negative.");
44621
+ const [mantissa = "0", exponent = "0"] = value.toString().split("e");
44622
+ const [whole = "0", fraction = ""] = mantissa.split(".");
44623
+ const digits = BigInt(whole + fraction);
44624
+ const scale = 6 + Number(exponent) - fraction.length;
44625
+ return scale >= 0 ? digits * 10n ** BigInt(scale) : digits / 10n ** BigInt(-scale);
44708
44626
  }
44709
44627
 
44710
- // src/spend-policy.ts
44711
- import { randomBytes as randomBytes3 } from "node:crypto";
44712
- import { mkdir as mkdir5, open as open4, readFile as readFile5, rename as rename3, stat as stat3, unlink as unlink4, writeFile as writeFile2 } from "node:fs/promises";
44713
- import { dirname as dirname4 } from "node:path";
44714
- var ledgerSchema = external_exports.object({
44715
- date: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
44716
- spentAtomic: external_exports.string().regex(/^\d+$/)
44717
- });
44718
- var spendReservationSchema = external_exports.object({
44719
- id: external_exports.string().min(1),
44720
- amountAtomic: external_exports.string().regex(/^\d+$/),
44721
- kind: external_exports.enum(["payment", "escrow-funding", "dispute-fee"]).optional(),
44722
- taskKey: external_exports.string().optional()
44723
- });
44724
- var ledgerRowSchema = ledgerSchema.extend({
44725
- wallet: walletNameSchema.optional(),
44726
- reservations: external_exports.array(spendReservationSchema).optional()
44727
- });
44728
- var ledgerFileSchema = external_exports.union([
44729
- external_exports.object({ version: external_exports.literal(1), rows: external_exports.array(ledgerRowSchema) }),
44730
- ledgerRowSchema
44731
- ]);
44732
- var SpendCapError = class extends Error {
44733
- constructor(code, message, details) {
44628
+ // src/tasks/operation-support.ts
44629
+ var TaskOperationError = class extends Error {
44630
+ constructor(code, message, manifestHash, details) {
44734
44631
  super(message);
44735
44632
  this.code = code;
44633
+ this.manifestHash = manifestHash;
44736
44634
  this.details = details;
44737
- this.name = "SpendCapError";
44635
+ this.name = "TaskOperationError";
44738
44636
  }
44739
44637
  code;
44638
+ manifestHash;
44740
44639
  details;
44741
44640
  };
44742
- function utcDateKey(now = /* @__PURE__ */ new Date()) {
44743
- return now.toISOString().slice(0, 10);
44744
- }
44745
- async function escrowFundingDayRemainingAtomic(input2) {
44746
- const perDayAtomic = parseAtomicCap(input2.caps.perDayAtomic, "per-day");
44747
- const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now);
44748
- const row = rows.find((candidate) => candidate.wallet === input2.wallet);
44749
- const reserved = input2.reservationId ? row?.reservations?.find((candidate) => candidate.id === input2.reservationId) : void 0;
44750
- const remaining = perDayAtomic - BigInt(row?.spentAtomic ?? "0") + BigInt(reserved?.amountAtomic ?? "0");
44751
- return remaining > 0n ? remaining : 0n;
44752
- }
44753
- async function taskReservedAtomic(input2) {
44754
- const rows = await readStoredSpendLedgerRows(input2.ledgerPath, input2.now, true);
44755
- return sumTaskReservations(rows, input2.wallet, input2.taskKey, input2.excludeReservationId);
44641
+ var TaskInputError = class extends TaskOperationError {
44642
+ constructor(message) {
44643
+ super("invalid_input", message);
44644
+ this.name = "TaskInputError";
44645
+ }
44646
+ };
44647
+ var PENDING_SERVER_ROUTES = /* @__PURE__ */ new Set([
44648
+ "board",
44649
+ "publicTask",
44650
+ "receipt",
44651
+ "events",
44652
+ "submit",
44653
+ "feed",
44654
+ "show",
44655
+ "post",
44656
+ "checkin",
44657
+ "pending"
44658
+ ]);
44659
+ function isMissingTaskEntity(code, message) {
44660
+ return typeof code === "string" && /^(?:task|work_order|receipt|order)_not_found$/iu.test(code) || typeof message === "string" && /\b(?:task|work order|order|receipt)\b.*\bnot found\b/iu.test(message);
44756
44661
  }
44757
- function sumTaskReservations(rows, wallet, taskKey, excludeReservationId) {
44758
- let total = 0n;
44759
- for (const row of rows) {
44760
- if (row.wallet !== wallet) continue;
44761
- for (const reservation of row.reservations ?? []) {
44762
- if (reservation.taskKey === taskKey && reservation.id !== excludeReservationId)
44763
- total += BigInt(reservation.amountAtomic);
44662
+ function publicNotFoundFetch(fetchImpl, baseUrl) {
44663
+ const base2 = baseUrl.replace(/\/+$/u, "");
44664
+ return async (input2, init) => {
44665
+ const response = await fetchImpl(input2, init);
44666
+ const url2 = input2 instanceof Request ? input2.url : String(input2);
44667
+ if (response.status !== 404 || ![`${base2}/api/tasks/`, `${base2}/api/receipts/`].some((prefix) => url2.startsWith(prefix)))
44668
+ return response;
44669
+ let body;
44670
+ try {
44671
+ body = await response.clone().json();
44672
+ } catch {
44764
44673
  }
44765
- }
44766
- return total;
44674
+ const record3 = typeof body === "object" && body !== null ? body : void 0;
44675
+ const nested = typeof record3?.error === "object" && record3.error !== null ? record3.error : void 0;
44676
+ const code = nested?.code ?? record3?.code;
44677
+ const message = typeof record3?.error === "string" ? record3.error : nested?.message ?? record3?.message;
44678
+ if (isMissingTaskEntity(code, message)) return response;
44679
+ await response.body?.cancel();
44680
+ throw new TasksClientError(
44681
+ "http",
44682
+ "The public task route is unavailable.",
44683
+ 404,
44684
+ typeof code === "string" ? code : void 0
44685
+ );
44686
+ };
44767
44687
  }
44768
- async function readStoredSpendLedgerRows(path, now, allDays = false) {
44769
- let raw;
44688
+ async function taskRequest(verb, route, operation, options) {
44770
44689
  try {
44771
- raw = await readFile5(path, "utf8");
44690
+ return await operation();
44772
44691
  } catch (error61) {
44773
- if (isMissingFile(error61)) return [];
44774
- throw error61;
44775
- }
44776
- const parsed = ledgerFileSchema.parse(JSON.parse(raw));
44777
- const rows = "rows" in parsed ? parsed.rows : [parsed];
44778
- const today = utcDateKey(now);
44779
- return rows.filter((row) => allDays || row.date === today).map((row) => ({
44780
- date: row.date,
44781
- spentAtomic: row.spentAtomic,
44782
- wallet: row.wallet ?? DEFAULT_WALLET_NAME,
44783
- ...row.reservations === void 0 ? {} : { reservations: row.reservations }
44784
- }));
44785
- }
44786
- async function reserveSpend(amountAtomic, caps, options) {
44787
- if (amountAtomic < 0n) {
44788
- throw new Error("Spend amount cannot be negative.");
44789
- }
44790
- const kind = options?.kind ?? "payment";
44791
- let perDayAtomic;
44792
- if (kind === "escrow-funding" || kind === "dispute-fee") {
44793
- const maxPerTaskAtomic = options?.maxPerTaskAtomic;
44794
- if (maxPerTaskAtomic === void 0 || maxPerTaskAtomic < 0n) {
44795
- throw new Error("Escrow funding requires a non-negative per-task cap.");
44796
- }
44797
- if (amountAtomic > maxPerTaskAtomic) {
44798
- throw new SpendCapError(
44799
- "per_task_cap_exceeded",
44800
- `Escrow funding ${amountAtomic} atomic USDC exceeds the per-task cap ${maxPerTaskAtomic}. Refusing to sign.`
44801
- );
44802
- }
44803
- perDayAtomic = parseAtomicCap(caps.perDayAtomic, "per-day");
44804
- } else {
44805
- const perCallAtomic = parseAtomicCap(caps.perCallAtomic, "per-call");
44806
- perDayAtomic = parseAtomicCap(caps.perDayAtomic, "per-day");
44807
- if (amountAtomic > perCallAtomic) {
44808
- throw new SpendCapError(
44809
- "per_call_cap_exceeded",
44810
- `Payment quote ${amountAtomic} atomic USDC exceeds the per-call cap ${perCallAtomic}. Refusing to sign.`,
44811
- { amountAtomic, limitAtomic: perCallAtomic, wallet: options?.wallet }
44692
+ if (error61 instanceof TasksChainUnavailableError || error61 instanceof Error && "code" in error61 && error61.code === "chain_unavailable") {
44693
+ const hash9 = typeof error61 === "object" && error61 !== null && "manifestHash" in error61 && typeof error61.manifestHash === "string" ? error61.manifestHash : void 0;
44694
+ throw new TaskOperationError(
44695
+ "chain_unavailable",
44696
+ "An acting wallet is required for task chain operations.",
44697
+ hash9
44812
44698
  );
44813
44699
  }
44814
- }
44815
- const ledgerPath = options?.ledgerPath ?? getVapiPaths().ledger;
44816
- const now = options?.now ?? /* @__PURE__ */ new Date();
44817
- const wallet = options?.wallet ?? DEFAULT_WALLET_NAME;
44818
- return await withLedgerLock(ledgerPath, async () => {
44819
- const rows = await readStoredSpendLedgerRows(ledgerPath, now, true);
44820
- const today = utcDateKey(now);
44821
- const current = rows.find((row) => row.wallet === wallet && row.date === today);
44822
- if ((kind === "escrow-funding" || kind === "dispute-fee") && options?.taskKey !== void 0) {
44823
- const taskTotal = sumTaskReservations(
44824
- rows,
44825
- wallet,
44826
- options.taskKey,
44827
- options.reuseExistingEscrowReservation || options.resumeEscrowReservation ? options.reservationId : void 0
44828
- ) + amountAtomic;
44829
- if (taskTotal > options.maxPerTaskAtomic)
44830
- throw new SpendCapError(
44831
- "per_task_cap_exceeded",
44832
- `New spend ${amountAtomic} atomic USDC would raise the running total for task ${options.taskKey} and wallet ${wallet} to ${taskTotal}, above the per-task cap ${options.maxPerTaskAtomic}. Refusing to sign.`
44700
+ if (error61 instanceof TasksClientError) {
44701
+ if (error61.code === "invalid_input") throw new TaskInputError(error61.message);
44702
+ if (error61.status === 403 && error61.serverCode === "insufficient_scope") {
44703
+ throw new TaskOperationError(
44704
+ "insufficient_scope",
44705
+ options.signInHint.includes("auth.link") ? "This sign-in lacks Tasks access. Call auth.link again." : "This sign-in lacks Tasks access. Run vapi login again."
44833
44706
  );
44834
- }
44835
- if (options?.reservationId !== void 0) {
44836
- const existing = current?.reservations?.find(
44837
- (reservation) => reservation.id === options.reservationId
44838
- );
44839
- if (existing && options.reuseExistingEscrowReservation) {
44840
- if (kind !== "escrow-funding" && kind !== "dispute-fee" || existing.kind !== kind || existing.amountAtomic !== amountAtomic.toString() || existing.taskKey !== void 0 && existing.taskKey !== options.taskKey)
44841
- throw new Error(
44842
- `Spend reservation ${options.reservationId} does not match this funding.`
44843
- );
44844
- if (existing.taskKey === void 0 && options.taskKey !== void 0) {
44845
- existing.taskKey = options.taskKey;
44846
- await writeLedgerAtomically(ledgerPath, rows);
44847
- }
44848
- return {
44849
- date: current.date,
44850
- spentAtomic: current.spentAtomic,
44851
- reservationReused: true
44852
- };
44853
- }
44854
- if (existing) {
44855
- throw new Error(`Spend reservation ${options.reservationId} already exists.`);
44856
44707
  }
44857
- if (options.resumeEscrowReservation) {
44858
- const resumed = options.resumeEscrowReservation;
44859
- const historical = rows.find((row) => row.wallet === wallet && row.date === resumed.date);
44860
- const stored = historical?.reservations?.find(
44861
- (reservation) => reservation.id === resumed.id
44708
+ if (error61.status === 404 && PENDING_SERVER_ROUTES.has(route) && !isMissingTaskEntity(error61.serverCode, error61.message))
44709
+ throw new TaskOperationError(
44710
+ "not_available",
44711
+ `${verb} is not available on this server yet.`
44862
44712
  );
44863
- if (kind !== "escrow-funding" && kind !== "dispute-fee" || resumed.id !== options.reservationId || resumed.wallet !== wallet || resumed.amountAtomic !== amountAtomic.toString() || resumed.date >= utcDateKey(now) || resumed.exposed !== true || resumed.invalidated === true || stored !== void 0 && (stored.kind !== kind || stored.amountAtomic !== amountAtomic.toString() || stored.taskKey !== void 0 && stored.taskKey !== options.taskKey))
44864
- throw new Error(
44865
- `Spend reservation ${options.reservationId} does not match this funding.`
44866
- );
44867
- if (stored?.taskKey === void 0 && options.taskKey !== void 0) {
44868
- if (stored) stored.taskKey = options.taskKey;
44869
- else {
44870
- const reservation = {
44871
- id: resumed.id,
44872
- amountAtomic: resumed.amountAtomic,
44873
- kind,
44874
- taskKey: options.taskKey
44875
- };
44876
- if (historical)
44877
- historical.reservations = [...historical.reservations ?? [], reservation];
44878
- else
44879
- rows.push({
44880
- date: resumed.date,
44881
- spentAtomic: resumed.amountAtomic,
44882
- wallet,
44883
- reservations: [reservation]
44884
- });
44885
- }
44886
- await writeLedgerAtomically(ledgerPath, rows);
44887
- }
44888
- return {
44889
- date: resumed.date,
44890
- spentAtomic: current?.spentAtomic ?? "0",
44891
- reservationReused: true
44892
- };
44893
- }
44894
- }
44895
- const spentAtomic = current?.spentAtomic ?? "0";
44896
- const nextSpent = BigInt(spentAtomic) + amountAtomic;
44897
- if (nextSpent > perDayAtomic) {
44898
- throw new SpendCapError(
44899
- "per_day_cap_exceeded",
44900
- `${kind === "escrow-funding" ? "Escrow funding" : "Payment quote"} ${amountAtomic} atomic USDC would raise today's spend to ${nextSpent} for wallet ${wallet}, above the per-day cap ${perDayAtomic}. Refusing to sign.`,
44901
- { amountAtomic, limitAtomic: perDayAtomic, spentAtomic: BigInt(spentAtomic), wallet }
44713
+ if ((error61.status === 401 || error61.status === 403) && !["board", "publicTask", "receipt", "feed", "deployment"].includes(route))
44714
+ throw new TaskOperationError(
44715
+ "not_signed_in",
44716
+ `${verb} needs sign-in. ${options.signInHint}`
44717
+ );
44718
+ throw new TaskOperationError(
44719
+ error61.serverCode ?? (error61.status ? `http_${error61.status}` : error61.code),
44720
+ error61.message
44902
44721
  );
44903
44722
  }
44904
- const reservationId = options?.reservationId ?? (options?.taskKey === void 0 ? void 0 : randomBytes3(16).toString("hex"));
44905
- const nextRow = {
44906
- date: utcDateKey(now),
44907
- spentAtomic: nextSpent.toString(),
44908
- wallet,
44909
- ...(current?.reservations?.length ?? 0) === 0 && reservationId === void 0 ? {} : {
44910
- reservations: [
44911
- ...current?.reservations ?? [],
44912
- ...reservationId === void 0 ? [] : [
44913
- {
44914
- id: reservationId,
44915
- amountAtomic: amountAtomic.toString(),
44916
- ...kind !== "payment" ? { kind } : {},
44917
- ...options?.taskKey === void 0 ? {} : { taskKey: options.taskKey }
44918
- }
44919
- ]
44920
- ]
44921
- }
44922
- };
44923
- const otherRows = rows.filter((row) => row.wallet !== wallet || row.date !== today).map((row) => {
44924
- if (row.wallet !== wallet || !options?.reuseExistingEscrowReservation || options.reservationId === void 0)
44925
- return row;
44926
- const previous = row.reservations?.find(
44927
- (reservation) => reservation.id === options.reservationId
44928
- );
44929
- if (!previous) return row;
44930
- if (kind !== "escrow-funding" && kind !== "dispute-fee" || previous.kind !== kind || previous.amountAtomic !== amountAtomic.toString() || previous.taskKey !== void 0 && previous.taskKey !== options.taskKey)
44931
- throw new Error(
44932
- `Spend reservation ${options.reservationId} does not match this funding.`
44933
- );
44934
- return {
44935
- ...row,
44936
- reservations: row.reservations.filter(
44937
- (reservation) => reservation.id !== options.reservationId
44938
- )
44939
- };
44723
+ throw error61;
44724
+ }
44725
+ }
44726
+ async function resolveTaskBearer(args) {
44727
+ const link2 = args.wallets.entry(args.wallet)?.link;
44728
+ if (!link2) return void 0;
44729
+ if (new URL(link2.apiBase).origin !== new URL(args.baseUrl).origin)
44730
+ throw new TaskOperationError(
44731
+ "not_signed_in",
44732
+ `The acting wallet is linked to a different server. ${args.signInHint}`
44733
+ );
44734
+ try {
44735
+ const token = await agentAccessToken({
44736
+ secrets: args.secrets,
44737
+ wallets: args.wallets,
44738
+ wallet: args.wallet,
44739
+ ...args.fetchImpl ? { fetchImpl: args.fetchImpl } : {},
44740
+ ...args.now ? { now: args.now } : {}
44940
44741
  });
44941
- const nextRows = [...otherRows, nextRow].sort(
44942
- (a, b) => a.wallet.localeCompare(b.wallet) || a.date.localeCompare(b.date)
44742
+ const current = args.wallets.entry(args.wallet)?.link;
44743
+ if (current?.clientId !== link2.clientId || current.apiBase !== link2.apiBase)
44744
+ throw new TaskOperationError(
44745
+ "not_signed_in",
44746
+ "The acting wallet's sign-in changed. Retry with its current server."
44747
+ );
44748
+ return token;
44749
+ } catch (error61) {
44750
+ if (error61 instanceof AgentLinkError && error61.code === "not_linked") return void 0;
44751
+ throw error61;
44752
+ }
44753
+ }
44754
+ var TASK_LIMITS = {
44755
+ postDeadlineMinMs: 6e5,
44756
+ proposalDurationMinMs: 6e5,
44757
+ proposalDurationMaxMs: 7776e6,
44758
+ proposalDurationUnitMs: 1e3,
44759
+ proposalNoteMin: 1,
44760
+ proposalNoteMax: 8e3,
44761
+ titleMin: 3,
44762
+ titleMax: 120,
44763
+ briefMin: 10,
44764
+ briefMax: 8e3,
44765
+ maxAwardsMin: 1,
44766
+ maxAwardsMax: 50,
44767
+ deliveryFilesMin: 1,
44768
+ deliveryFilesMax: 20,
44769
+ deliveryNoteMax: 32e3,
44770
+ messageMin: 1,
44771
+ messageMax: 1e4,
44772
+ searchTabs: ["trending", "new", "closing", "paid"],
44773
+ disputeEvidenceHash: /^0x[0-9a-fA-F]{64}$/u,
44774
+ uploadBytesMin: 1,
44775
+ uploadBytesMax: 50 * 1024 * 1024,
44776
+ watchIntervalMinMs: 1e3
44777
+ };
44778
+ function parseTaskDuration(text, now) {
44779
+ const match = /^(\d+)(s|m|h|d)$/u.exec(text);
44780
+ const units = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
44781
+ let milliseconds;
44782
+ if (match) milliseconds = Number(match[1]) * units[match[2]];
44783
+ else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/u.test(text)) {
44784
+ const datePart = text.slice(0, 10), day = /* @__PURE__ */ new Date(`${datePart}T00:00:00Z`);
44785
+ if (!Number.isFinite(day.getTime()) || day.toISOString().slice(0, 10) !== datePart)
44786
+ throw new TaskInputError("Expected a valid ISO-8601 timestamp.");
44787
+ milliseconds = Date.parse(text) - now.getTime();
44788
+ } else
44789
+ throw new TaskInputError(
44790
+ "Expected a duration such as 10m, 48h or 7d, or an ISO-8601 timestamp."
44943
44791
  );
44944
- await writeLedgerAtomically(ledgerPath, nextRows);
44945
- return {
44946
- date: nextRow.date,
44947
- spentAtomic: nextRow.spentAtomic,
44948
- ...options?.reservationId === void 0 && reservationId !== void 0 ? { reservationId } : {}
44949
- };
44950
- });
44792
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0 || !Number.isFinite(now.getTime()) || !Number.isFinite(new Date(now.getTime() + milliseconds).getTime()))
44793
+ throw new TaskInputError(
44794
+ "The duration or timestamp must be in the future and within the supported date range."
44795
+ );
44796
+ return milliseconds;
44951
44797
  }
44952
- async function releaseSpend(amountAtomic, options) {
44953
- if (amountAtomic < 0n) {
44954
- throw new Error("Spend amount cannot be negative.");
44798
+ async function readTaskFile(path) {
44799
+ let details;
44800
+ try {
44801
+ details = await stat4(path);
44802
+ } catch {
44803
+ throw new TaskInputError(`Task file ${JSON.stringify(path)} could not be read.`);
44955
44804
  }
44956
- const ledgerPath = options.ledgerPath ?? getVapiPaths().ledger;
44957
- const now = options.now ?? /* @__PURE__ */ new Date();
44958
- const wallet = options.wallet ?? DEFAULT_WALLET_NAME;
44959
- return await withLedgerLock(ledgerPath, async () => {
44960
- const today = utcDateKey(now);
44961
- const rows = await readStoredSpendLedgerRows(ledgerPath, now, true);
44962
- const current = rows.find((row) => row.wallet === wallet && row.date === today);
44963
- if (options.reservedOn !== today && options.reservationId === void 0) {
44964
- return { date: today, spentAtomic: current?.spentAtomic ?? "0" };
44965
- }
44966
- const reserved = rows.find((row) => row.wallet === wallet && row.date === options.reservedOn);
44967
- const reservation = options.reservationId === void 0 ? void 0 : reserved?.reservations?.find((candidate) => candidate.id === options.reservationId);
44968
- if (options.reservationId !== void 0 && reservation === void 0) {
44969
- return { date: today, spentAtomic: current?.spentAtomic ?? "0" };
44970
- }
44971
- if (reservation !== void 0 && reservation.amountAtomic !== amountAtomic.toString()) {
44972
- throw new Error(`Spend reservation ${options.reservationId} has a different amount.`);
44973
- }
44974
- const spentAtomic = BigInt(reserved?.spentAtomic ?? "0");
44975
- const releasedAmount = reservation === void 0 ? amountAtomic : BigInt(reservation.amountAtomic);
44976
- const nextSpent = spentAtomic > releasedAmount ? spentAtomic - releasedAmount : 0n;
44977
- const remainingReservations = reserved?.reservations?.filter(
44978
- (candidate) => candidate.id !== options.reservationId
44805
+ if (!details.isFile())
44806
+ throw new TaskInputError(
44807
+ `Task file ${JSON.stringify(path)} must be a regular file, not a directory.`
44979
44808
  );
44980
- const nextRow = {
44981
- date: options.reservedOn,
44982
- spentAtomic: nextSpent.toString(),
44983
- wallet,
44984
- ...remainingReservations === void 0 || remainingReservations.length === 0 ? {} : { reservations: remainingReservations }
44985
- };
44986
- const nextRows = [
44987
- ...rows.filter((row) => row.wallet !== wallet || row.date !== options.reservedOn),
44988
- nextRow
44989
- ].sort((a, b) => a.wallet.localeCompare(b.wallet) || a.date.localeCompare(b.date));
44990
- await writeLedgerAtomically(ledgerPath, nextRows);
44991
- return {
44992
- date: today,
44993
- spentAtomic: options.reservedOn === today ? nextRow.spentAtomic : current?.spentAtomic ?? "0"
44994
- };
44995
- });
44809
+ const types = {
44810
+ ".png": "image/png",
44811
+ ".jpg": "image/jpeg",
44812
+ ".jpeg": "image/jpeg",
44813
+ ".webp": "image/webp",
44814
+ ".gif": "image/gif",
44815
+ ".pdf": "application/pdf",
44816
+ ".zip": "application/zip",
44817
+ ".txt": "text/plain",
44818
+ ".md": "text/markdown",
44819
+ ".json": "application/json",
44820
+ ".csv": "text/csv"
44821
+ };
44822
+ const contentType = types[extname(path).toLowerCase()];
44823
+ if (!contentType)
44824
+ throw new TaskInputError("Task files must be images, PDF, ZIP, text, Markdown, JSON or CSV.");
44825
+ const bytes = await readFile6(path);
44826
+ if (bytes.length < TASK_LIMITS.uploadBytesMin || bytes.length > TASK_LIMITS.uploadBytesMax)
44827
+ throw new TaskInputError("Task files must contain between 1 byte and 50 MiB.");
44828
+ return {
44829
+ fileName: basename2(path),
44830
+ bytes: Uint8Array.from(bytes),
44831
+ contentType,
44832
+ purpose: "delivery"
44833
+ };
44996
44834
  }
44997
- function parseAtomicCap(value, label2) {
44998
- if (!/^\d+$/.test(value)) {
44999
- throw new Error(`Invalid ${label2} spend cap ${JSON.stringify(value)}.`);
45000
- }
45001
- return BigInt(value);
44835
+ function validTaskBrief(title, description) {
44836
+ return title.trim().length >= TASK_LIMITS.titleMin && title.trim().length <= TASK_LIMITS.titleMax && description.trim().length >= TASK_LIMITS.briefMin && description.trim().length <= TASK_LIMITS.briefMax;
45002
44837
  }
45003
- async function writeLedgerAtomically(path, rows) {
45004
- const ledger = rows.length === 1 && rows[0].wallet === DEFAULT_WALLET_NAME ? {
45005
- date: rows[0].date,
45006
- spentAtomic: rows[0].spentAtomic,
45007
- ...rows[0].reservations === void 0 ? {} : { reservations: rows[0].reservations }
45008
- } : { version: 1, rows };
45009
- await mkdir5(dirname4(path), { recursive: true, mode: 448 });
45010
- const temporaryPath = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}.tmp`;
45011
- await writeFile2(temporaryPath, `${JSON.stringify(ledger, null, 2)}
45012
- `, {
45013
- encoding: "utf8",
45014
- mode: 384,
45015
- flag: "wx"
44838
+ function proposalTerms(id, address9, deployment, terms) {
44839
+ return {
44840
+ version: "work-proposal-v1",
44841
+ workOrderId: id,
44842
+ // The server lowercases addresses before canonicalizing the signed payload.
44843
+ providerAddress: address9.toLowerCase(),
44844
+ pricingModel: "fixed",
44845
+ milestones: [
44846
+ {
44847
+ version: "work-milestone-terms-v1",
44848
+ title: terms.title,
44849
+ description: terms.description,
44850
+ acceptanceCriteria: ["Complete the task described in these terms."],
44851
+ workDurationSeconds: terms.durationSeconds,
44852
+ acceptanceWindowSeconds: 604800,
44853
+ budget: {
44854
+ network: deployment.network,
44855
+ asset: `${deployment.network}/erc20:${deployment.usdc}`,
44856
+ amountBaseUnits: terms.amount.toString()
44857
+ },
44858
+ escrow: { protocol: "escrow-v1", contract: deployment.escrowContract },
44859
+ evidenceRules: { acceptedInputs: ["text", "private-file"], exactCommitRequired: false }
44860
+ }
44861
+ ]
44862
+ };
44863
+ }
44864
+ function orderReceipts(order, baseUrl) {
44865
+ if (order.version !== "work-order-view-v1") return [];
44866
+ return order.milestones.filter(
44867
+ (m) => ["released", "refunded"].includes(m.state) || m.escrowState === "resolved" && m.resolution !== null
44868
+ ).map((m) => ({
44869
+ receiptUrl: `${baseUrl.replace(/\/+$/u, "")}/receipts/${m.escrowContract}`,
44870
+ receiptUrlSource: "escrow"
44871
+ }));
44872
+ }
44873
+ var TASK_WATCH_STATES = [
44874
+ "open",
44875
+ "awarded",
44876
+ "funded",
44877
+ "delivered",
44878
+ "paid",
44879
+ "released",
44880
+ "refunded",
44881
+ "disputed",
44882
+ "expired",
44883
+ "closed",
44884
+ "completed",
44885
+ "cancelled",
44886
+ "checkin",
44887
+ "stalled",
44888
+ "claimed",
44889
+ "judging",
44890
+ "milestone"
44891
+ ];
44892
+ function taskEventState(event) {
44893
+ return typeof event.payload.state === "string" ? event.payload.state.toLowerCase() : event.type.split(".").at(-1)?.toLowerCase() ?? event.type.toLowerCase();
44894
+ }
44895
+ function taskStateMatches(until, state) {
44896
+ return until === state || until === "paid" && state === "released";
44897
+ }
44898
+ function nextTaskEvents(page, cursor) {
44899
+ if (!Number.isSafeInteger(page.nextAfter) || page.nextAfter < cursor)
44900
+ throw new TaskOperationError(
44901
+ "invalid_response",
44902
+ "The task event cursor regressed or is malformed."
44903
+ );
44904
+ for (const event of page.events)
44905
+ if (!Number.isSafeInteger(event.sequence) || event.sequence < 0)
44906
+ throw new TaskOperationError("invalid_response", "A task event sequence is malformed.");
44907
+ const seen = /* @__PURE__ */ new Set();
44908
+ const events = [...page.events].sort((a, b) => a.sequence - b.sequence).filter((event) => {
44909
+ if (event.sequence <= cursor || seen.has(event.sequence)) return false;
44910
+ seen.add(event.sequence);
44911
+ return true;
45016
44912
  });
45017
- await rename3(temporaryPath, path);
44913
+ return {
44914
+ events,
44915
+ nextCursor: Math.max(cursor, page.nextAfter, ...page.events.map((e3) => e3.sequence))
44916
+ };
45018
44917
  }
45019
- async function withLedgerLock(path, operation) {
45020
- await mkdir5(dirname4(path), { recursive: true, mode: 448 });
45021
- const lockPath = `${path}.lock`;
45022
- const deadline = Date.now() + 2e3;
45023
- let handle;
45024
- while (!handle) {
45025
- try {
45026
- handle = await open4(lockPath, "wx", 384);
45027
- } catch (error61) {
45028
- if (!(error61 instanceof Error && "code" in error61 && error61.code === "EEXIST")) {
45029
- throw error61;
45030
- }
45031
- await removeStaleLock2(lockPath);
45032
- if (Date.now() >= deadline) {
45033
- throw new Error("Timed out waiting for the spend ledger lock.");
45034
- }
45035
- await new Promise((resolve) => setTimeout(resolve, 20));
45036
- }
44918
+ async function accountTaskPolicy(directory, wallet, warn) {
44919
+ let raw;
44920
+ try {
44921
+ raw = await readFile6(join6(directory, "wallets.json"), "utf8");
44922
+ } catch {
44923
+ return void 0;
45037
44924
  }
45038
44925
  try {
45039
- return await operation();
45040
- } finally {
45041
- await handle.close().catch(() => void 0);
45042
- await unlink4(lockPath).catch(() => void 0);
44926
+ const wallets = JSON.parse(raw).wallets;
44927
+ const stored = wallets && Object.hasOwn(wallets, wallet) ? wallets[wallet]?.taskPolicy : void 0;
44928
+ return stored === void 0 ? void 0 : walletTaskPolicySchema.parse(stored);
44929
+ } catch {
44930
+ warn?.(`The task limits stored for account ${wallet} are unreadable; using the defaults.`);
44931
+ return void 0;
45043
44932
  }
45044
44933
  }
45045
- async function removeStaleLock2(path) {
44934
+ async function taskPolicyForWallet(args) {
44935
+ let invalid = false;
44936
+ const profiles = await listAgentProfiles(args.directory, {
44937
+ schema: args.schema,
44938
+ ...args.warn ? { warn: args.warn } : {},
44939
+ onInvalid: () => {
44940
+ invalid = true;
44941
+ }
44942
+ });
44943
+ if (invalid) throw new TaskInputError("An invalid agent profile prevents task policy selection.");
44944
+ const matches = profiles.filter((profile2) => profile2.wallet === args.wallet);
44945
+ if (matches.length > 1)
44946
+ throw new TaskInputError(
44947
+ `More than one agent profile uses wallet ${args.wallet}; task policy is ambiguous.`
44948
+ );
44949
+ const profile = matches[0];
44950
+ if (profile)
44951
+ return {
44952
+ maxPerTaskUsd: profile.maxPerTaskUsd,
44953
+ approveAboveUsd: profile.approveAboveUsd,
44954
+ autoReleaseBelowUsd: profile.autoReleaseBelowUsd,
44955
+ source: "agent-profile"
44956
+ };
44957
+ const account = await accountTaskPolicy(args.directory, args.wallet, args.warn);
44958
+ const stored = account?.maxPerTaskUsd !== void 0 || account?.approveAboveUsd !== void 0;
44959
+ return {
44960
+ maxPerTaskUsd: account?.maxPerTaskUsd ?? DEFAULT_MAX_PER_TASK_USD,
44961
+ approveAboveUsd: account?.approveAboveUsd ?? agentProfileSchema.shape.approveAboveUsd.parse(void 0),
44962
+ autoReleaseBelowUsd: DEFAULT_AUTO_RELEASE_BELOW_USD,
44963
+ source: stored ? "account" : "defaults"
44964
+ };
44965
+ }
44966
+ async function taskMoneySnapshot(client, orderId, escrowId, options = { signInHint: "" }) {
44967
+ const order = await taskRequest(
44968
+ "task money",
44969
+ "getOrder",
44970
+ () => client.getOrder(orderId),
44971
+ options
44972
+ ), workOrder = order.workOrder;
44973
+ if (workOrder.id !== orderId || workOrder.version !== "work-order-view-v1")
44974
+ throw new TaskOperationError(
44975
+ "invalid_response",
44976
+ "A private task order matching the requested ID is required."
44977
+ );
44978
+ const matches = escrowId ? workOrder.milestones.filter((m) => m.id === escrowId) : workOrder.milestones;
44979
+ if (matches.length !== 1)
44980
+ throw new TaskOperationError("invalid_response", "Select one task milestone by escrow ID.");
44981
+ const milestone = matches[0];
44982
+ if (milestone.workOrderId !== orderId)
44983
+ throw new TaskOperationError("invalid_response", "The milestone belongs to a different task.");
44984
+ let readiness;
45046
44985
  try {
45047
- const metadata = await stat3(path);
45048
- if (Date.now() - metadata.mtimeMs > 3e4) {
45049
- await unlink4(path);
45050
- }
44986
+ readiness = { ok: true, value: await client.deployment() };
45051
44987
  } catch (error61) {
45052
- if (!isMissingFile(error61)) {
45053
- throw error61;
44988
+ readiness = { ok: false, error: error61 };
44989
+ }
44990
+ return {
44991
+ order,
44992
+ escrowId: milestone.id,
44993
+ money: taskMoney(milestone.amountBaseUnits, readiness.ok ? parseFeeBp(readiness.value) : null),
44994
+ readiness
44995
+ };
44996
+ }
44997
+ function cachedMoneyClient(client, snapshot) {
44998
+ return new Proxy(client, {
44999
+ get(target, property) {
45000
+ if (property === "getOrder")
45001
+ return async (id) => {
45002
+ if (id !== snapshot.order.workOrder.id)
45003
+ throw new Error("The cached task order does not match the requested ID.");
45004
+ return snapshot.order;
45005
+ };
45006
+ if (property === "deployment")
45007
+ return async () => {
45008
+ if (snapshot.readiness.ok) return snapshot.readiness.value;
45009
+ throw snapshot.readiness.error;
45010
+ };
45011
+ const value = Reflect.get(target, property, target);
45012
+ return typeof value === "function" ? value.bind(target) : value;
45054
45013
  }
45014
+ });
45015
+ }
45016
+ function fundingRefusalReason(error61) {
45017
+ if (error61 instanceof Error && error61.name === "SpendCapExceededError") {
45018
+ const fromCause = fundingRefusalReason(error61.cause);
45019
+ if (fromCause) return fromCause;
45020
+ return "cap" in error61 && error61.cap === "per_day" ? "policy.perDay" : void 0;
45055
45021
  }
45022
+ if (!(error61 instanceof SpendCapError || error61 instanceof Error && error61.name === "SpendCapError"))
45023
+ return void 0;
45024
+ const code = "code" in error61 ? error61.code : void 0;
45025
+ return code === "per_task_cap_exceeded" ? "policy.perTask" : code === "per_day_cap_exceeded" ? "policy.perDay" : void 0;
45026
+ }
45027
+ function taskEventLine(event) {
45028
+ 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;
45029
+ return `${event.sequence}: ${[label2, ...taskV2OutcomeLines(event.payload)].join(" \xB7 ")}`;
45030
+ }
45031
+ function requireTaskMethod(client, name) {
45032
+ const method = client[name];
45033
+ if (typeof method !== "function")
45034
+ throw new TaskOperationError(
45035
+ "not_supported",
45036
+ `Task method ${name} is not supported by this SDK adapter.`
45037
+ );
45038
+ return method.bind(client);
45056
45039
  }
45057
45040
 
45058
- // src/tasks/v2-events.ts
45059
- var TASKS_V2_EVENT_ABIS = {
45060
- EscrowFactoryV2: escrowFactoryV2Abi,
45061
- EscrowV2: escrowV2Abi,
45062
- BountyEscrowV2: bountyEscrowV2Abi,
45063
- DisputeResolverV3: disputeResolverV3Abi,
45064
- BountyPoolFactoryV1: bountyPoolFactoryV1Abi,
45065
- BountyPoolV1: bountyPoolV1Abi,
45066
- ReviewerRegistryV2: reviewerRegistryV2Abi,
45067
- OutcomeRegistryV1: outcomeRegistryV1Abi,
45068
- FeeRouterV1: feeRouterV1Abi
45041
+ // src/tasks/availability.ts
45042
+ var TASK_V2_NEW_WORK_ACTIONS = [
45043
+ "fund",
45044
+ "approve-bond",
45045
+ "award",
45046
+ "award-consent"
45047
+ ];
45048
+ var NETWORK_NAMES = {
45049
+ 8453: "Base",
45050
+ 84532: "Base Sepolia",
45051
+ 5042002: "Arc testnet"
45069
45052
  };
45070
- function decodeTaskV2Event(contract, log) {
45071
- const decoded = decodeEventLog({ abi: TASKS_V2_EVENT_ABIS[contract], ...log, strict: true });
45072
- return normalizeTaskV2Outcomes(decoded);
45053
+ function taskNetworkName(chainId) {
45054
+ return NETWORK_NAMES[chainId] ?? `chain ${chainId}`;
45073
45055
  }
45074
- var TASK_V2_NO_VERDICT_SUMMARY = "Disputed: status quo final after round 2 without a verdict; no dispute winner.";
45075
- var TASK_V2_REVIEWER_GUIDANCE = "mayVote reports jury membership only. Do not touch your stake until you have revealed; even a cancelled unstake can cost the vote.";
45076
- var TASK_V2_JURY_RULES = "Fewer than 3 eligible reviewers ends the round immediately. With 3 to 20 eligible reviewers everyone eligible is in the jury; above 20, 5 are drawn. A verdict needs at least 3 reveals and a strict majority. Round 1 without a verdict restores the pre-dispute state. Round 2 without a verdict makes the status quo final: disputed, with no dispute winner. Draw strictly after the seed block through HISTORY_WINDOW (8,191 blocks); rearm only after that window, at most 3 times. The next expired attempt ends the round. No mediation or appeal.";
45077
- function normalizeTaskV2Outcomes(value) {
45078
- const walk3 = (item) => {
45079
- if (Array.isArray(item)) return item.map(walk3);
45080
- if (item === null || typeof item !== "object") return item;
45081
- const source = item;
45082
- const result = Object.fromEntries(
45083
- Object.entries(source).map(([key2, entry]) => [key2, walk3(entry)])
45056
+ function tasksUnavailableError(chainId, untouched = "Nothing was signed and no money moved.", code = "tasks_unavailable") {
45057
+ return new TaskOperationError(
45058
+ code,
45059
+ `vAPI reports Tasks as unavailable on ${taskNetworkName(chainId)} right now. ${untouched} Try again later.`
45060
+ );
45061
+ }
45062
+ async function readTasksReadiness(client) {
45063
+ try {
45064
+ return await client.deployment();
45065
+ } catch {
45066
+ return void 0;
45067
+ }
45068
+ }
45069
+ function requireTasksAvailable(action, readiness, untouched) {
45070
+ if (!TASK_V2_NEW_WORK_ACTIONS.includes(action)) return;
45071
+ if (!readiness)
45072
+ throw new TaskOperationError(
45073
+ "tasks_unavailable",
45074
+ `vAPI's Tasks status could not be read. ${untouched ?? "Nothing was signed and no money moved."} Try again later.`
45084
45075
  );
45085
- if (source.cause === 6 || source.cause === "6" || source.cause === 6n) {
45086
- result.disputed = true;
45087
- result.disputeWinner = 0;
45088
- result.summary = TASK_V2_NO_VERDICT_SUMMARY;
45089
- }
45090
- if (typeof source.mayVote === "boolean") {
45091
- result.juryMember = source.mayVote;
45092
- result.mayVoteMeaning = "jury membership only";
45093
- result.reviewerGuidance = TASK_V2_REVIEWER_GUIDANCE;
45094
- }
45095
- return result;
45096
- };
45097
- return walk3(value);
45076
+ if (!readiness.configured) throw tasksUnavailableError(readiness.chainId, untouched);
45098
45077
  }
45099
- function taskV2OutcomeLines(value) {
45100
- if (!value || typeof value !== "object") return [];
45101
- const source = value;
45102
- if (source.cause === 6 || source.cause === "6" || source.cause === 6n)
45103
- return [TASK_V2_NO_VERDICT_SUMMARY];
45104
- return [...new Set(Object.values(source).flatMap(taskV2OutcomeLines))];
45078
+
45079
+ // src/tasks/dispute-fee.ts
45080
+ import { createHash as createHash3 } from "node:crypto";
45081
+ function disputeFeeBaseUnits(amount4) {
45082
+ if (amount4 < 0n) throw new Error("Dispute amount must be nonnegative.");
45083
+ const fee = amount4 * 1000n / 10000n;
45084
+ return fee < 20000000n ? 20000000n : fee > 500000000n ? 500000000n : fee;
45085
+ }
45086
+ function taskFeeReservationKey(milestoneId2, action) {
45087
+ const bytes = createHash3("sha256").update(JSON.stringify([milestoneId2, action])).digest().subarray(0, 16);
45088
+ bytes[6] = bytes[6] & 15 | 80;
45089
+ bytes[8] = bytes[8] & 63 | 128;
45090
+ const hex5 = bytes.toString("hex");
45091
+ return `${hex5.slice(0, 8)}-${hex5.slice(8, 12)}-${hex5.slice(12, 16)}-${hex5.slice(16, 20)}-${hex5.slice(20)}`;
45105
45092
  }
45106
45093
 
45107
- // src/tasks/operation-support.ts
45108
- var TaskOperationError = class extends Error {
45109
- constructor(code, message, manifestHash, details) {
45110
- super(message);
45111
- this.code = code;
45112
- this.manifestHash = manifestHash;
45113
- this.details = details;
45114
- this.name = "TaskOperationError";
45115
- }
45116
- code;
45117
- manifestHash;
45118
- details;
45119
- };
45120
- var TaskInputError = class extends TaskOperationError {
45121
- constructor(message) {
45122
- super("invalid_input", message);
45123
- this.name = "TaskInputError";
45094
+ // src/tasks/plan-guard.ts
45095
+ var TASKS_CHAIN_ABI = [
45096
+ {
45097
+ type: "function",
45098
+ name: "createEscrow",
45099
+ stateMutability: "nonpayable",
45100
+ inputs: [
45101
+ { name: "buyer", type: "address" },
45102
+ { name: "token", type: "address" },
45103
+ { name: "amount", type: "uint256" },
45104
+ { name: "workDuration", type: "uint64" },
45105
+ { name: "acceptanceWindow", type: "uint64" },
45106
+ { name: "termsHash", type: "bytes32" },
45107
+ { name: "salt", type: "bytes32" }
45108
+ ],
45109
+ outputs: [{ name: "escrow", type: "address" }]
45110
+ },
45111
+ {
45112
+ type: "function",
45113
+ name: "fundWithAuthorization",
45114
+ stateMutability: "nonpayable",
45115
+ inputs: [
45116
+ { name: "validAfter", type: "uint256" },
45117
+ { name: "validBefore", type: "uint256" },
45118
+ { name: "nonce", type: "bytes32" },
45119
+ { name: "signature", type: "bytes" }
45120
+ ],
45121
+ outputs: []
45122
+ },
45123
+ {
45124
+ type: "function",
45125
+ name: "approve",
45126
+ stateMutability: "nonpayable",
45127
+ inputs: [
45128
+ { name: "spender", type: "address" },
45129
+ { name: "amount", type: "uint256" }
45130
+ ],
45131
+ outputs: [{ name: "ok", type: "bool" }]
45132
+ },
45133
+ {
45134
+ type: "function",
45135
+ name: "depositFunds",
45136
+ stateMutability: "nonpayable",
45137
+ inputs: [],
45138
+ outputs: []
45139
+ },
45140
+ {
45141
+ type: "function",
45142
+ name: "submitDelivery",
45143
+ stateMutability: "nonpayable",
45144
+ inputs: [{ name: "manifestHash", type: "bytes32" }],
45145
+ outputs: []
45146
+ },
45147
+ {
45148
+ type: "function",
45149
+ name: "releaseFunds",
45150
+ stateMutability: "nonpayable",
45151
+ inputs: [],
45152
+ outputs: []
45153
+ },
45154
+ { type: "function", name: "refundBuyer", stateMutability: "nonpayable", inputs: [], outputs: [] },
45155
+ {
45156
+ type: "function",
45157
+ name: "raiseDispute",
45158
+ stateMutability: "nonpayable",
45159
+ inputs: [{ name: "evidenceHash", type: "bytes32" }],
45160
+ outputs: []
45161
+ },
45162
+ {
45163
+ type: "function",
45164
+ name: "submitCounterEvidence",
45165
+ stateMutability: "nonpayable",
45166
+ inputs: [{ name: "evidenceHash", type: "bytes32" }],
45167
+ outputs: []
45168
+ },
45169
+ {
45170
+ type: "function",
45171
+ name: "resolveUnmatchedDispute",
45172
+ stateMutability: "nonpayable",
45173
+ inputs: [],
45174
+ outputs: []
45175
+ },
45176
+ {
45177
+ type: "function",
45178
+ name: "timeoutRefund",
45179
+ stateMutability: "nonpayable",
45180
+ inputs: [],
45181
+ outputs: []
45182
+ },
45183
+ { type: "function", name: "finalize", stateMutability: "nonpayable", inputs: [], outputs: [] },
45184
+ {
45185
+ type: "function",
45186
+ name: "disputeFee",
45187
+ stateMutability: "view",
45188
+ inputs: [],
45189
+ outputs: [{ name: "fee", type: "uint256" }]
45190
+ },
45191
+ {
45192
+ type: "function",
45193
+ name: "allowance",
45194
+ stateMutability: "view",
45195
+ inputs: [
45196
+ { name: "owner", type: "address" },
45197
+ { name: "spender", type: "address" }
45198
+ ],
45199
+ outputs: [{ name: "amount", type: "uint256" }]
45124
45200
  }
45125
- };
45126
- var PENDING_SERVER_ROUTES = /* @__PURE__ */ new Set([
45127
- "board",
45128
- "publicTask",
45129
- "receipt",
45130
- "events",
45131
- "submit",
45132
- "feed",
45133
- "show",
45134
- "post",
45135
- "checkin",
45136
- "pending"
45201
+ ];
45202
+ var TASKS_READ_ABI = parseAbi([
45203
+ "function paymentToken() view returns (address)",
45204
+ "function isEscrow(address escrow) view returns (bool)",
45205
+ "function name() view returns (string)",
45206
+ "function version() view returns (string)",
45207
+ "function buyer() view returns (address)",
45208
+ "function seller() view returns (address)",
45209
+ "function token() view returns (address)",
45210
+ "function amount() view returns (uint256)",
45211
+ "function termsHash() view returns (bytes32)",
45212
+ "function state() view returns (uint8)",
45213
+ "function offerDeadline() view returns (uint64)",
45214
+ "function workDeadline() view returns (uint64)",
45215
+ "function reviewDeadline() view returns (uint64)",
45216
+ "function disputedAt() view returns (uint64)",
45217
+ "function counterEvidenceDeadline() view returns (uint64)",
45218
+ "function resolution() view returns (uint8)",
45219
+ "function disputeFee() view returns (uint256)",
45220
+ "function predictEscrow(address seller, bytes32 salt) view returns (address)"
45137
45221
  ]);
45138
- function isMissingTaskEntity(code, message) {
45139
- return typeof code === "string" && /^(?:task|work_order|receipt|order)_not_found$/iu.test(code) || typeof message === "string" && /\b(?:task|work order|order|receipt)\b.*\bnot found\b/iu.test(message);
45140
- }
45141
- function publicNotFoundFetch(fetchImpl, baseUrl) {
45142
- const base2 = baseUrl.replace(/\/+$/u, "");
45143
- return async (input2, init) => {
45144
- const response = await fetchImpl(input2, init);
45145
- const url2 = input2 instanceof Request ? input2.url : String(input2);
45146
- if (response.status !== 404 || ![`${base2}/api/tasks/`, `${base2}/api/receipts/`].some((prefix) => url2.startsWith(prefix)))
45147
- return response;
45148
- let body;
45222
+ function verifyPlan(operation, expectation) {
45223
+ const fail2 = (message) => {
45224
+ throw new TasksChainError(`Unsafe transaction plan: ${message}`, false);
45225
+ };
45226
+ const plan = operation.plan;
45227
+ if (!plan) throw new TasksChainError("Unsafe transaction plan: missing plan", false);
45228
+ if (plan.operationId !== operation.id || plan.step !== operation.step) fail2("operation mismatch");
45229
+ if (!expectation.steps.includes(plan.step)) fail2("unexpected step");
45230
+ if (!operation.expectedActor || getAddress(operation.expectedActor) !== getAddress(expectation.signer) || getAddress(plan.from) !== getAddress(expectation.signer))
45231
+ fail2("unexpected signer");
45232
+ if (plan.chainId !== expectation.deployment.chainId || plan.network !== expectation.deployment.network || plan.network !== `eip155:${plan.chainId}` || plan.value !== "0")
45233
+ fail2("unexpected network or value");
45234
+ if (expectation.milestone.network !== plan.network || expectation.milestone.asset.toLowerCase() !== `${plan.network}/erc20:${expectation.deployment.usdc}`.toLowerCase())
45235
+ fail2("milestone asset mismatch");
45236
+ const target = plan.step === "create-escrow" ? expectation.deployment.escrowContract : plan.step === "approve-usdc" ? expectation.deployment.usdc : expectation.milestone.escrowContract;
45237
+ if (getAddress(plan.to) !== getAddress(target)) fail2("unexpected target");
45238
+ const decoded = (() => {
45149
45239
  try {
45150
- body = await response.clone().json();
45240
+ return decodeFunctionData({ abi: TASKS_CHAIN_ABI, data: plan.data });
45151
45241
  } catch {
45242
+ return fail2("invalid calldata");
45152
45243
  }
45153
- const record3 = typeof body === "object" && body !== null ? body : void 0;
45154
- const nested = typeof record3?.error === "object" && record3.error !== null ? record3.error : void 0;
45155
- const code = nested?.code ?? record3?.code;
45156
- const message = typeof record3?.error === "string" ? record3.error : nested?.message ?? record3?.message;
45157
- if (isMissingTaskEntity(code, message)) return response;
45158
- await response.body?.cancel();
45159
- throw new TasksClientError(
45160
- "http",
45161
- "The public task route is unavailable.",
45162
- 404,
45163
- typeof code === "string" ? code : void 0
45164
- );
45244
+ })();
45245
+ const expectedName = {
45246
+ "create-escrow": "createEscrow",
45247
+ "fund-with-authorization": "fundWithAuthorization",
45248
+ "approve-usdc": "approve",
45249
+ "deposit-funds": "depositFunds",
45250
+ "submit-delivery": "submitDelivery",
45251
+ "release-funds": "releaseFunds",
45252
+ "refund-buyer": "refundBuyer",
45253
+ "raise-dispute": "raiseDispute",
45254
+ "submit-counter-evidence": "submitCounterEvidence",
45255
+ "resolve-unmatched-dispute": "resolveUnmatchedDispute",
45256
+ "timeout-refund": "timeoutRefund",
45257
+ finalize: "finalize"
45165
45258
  };
45259
+ if (decoded.functionName !== expectedName[plan.step]) fail2("unexpected selector");
45260
+ const args = [...decoded.args ?? []];
45261
+ const eq = (a, b) => typeof a === "string" && typeof b === "string" ? a.toLowerCase() === b.toLowerCase() : a === b;
45262
+ const requireArgs = (values) => {
45263
+ if (args.length !== values.length || args.some((v, i2) => !eq(v, values[i2])))
45264
+ fail2("unexpected arguments");
45265
+ };
45266
+ if (plan.step === "create-escrow") {
45267
+ if (!expectation.seller || getAddress(expectation.signer) !== getAddress(expectation.seller))
45268
+ fail2("createEscrow requires the locally bound seller");
45269
+ const workDuration = expectation.workDurationSeconds ?? expectation.milestone.terms.workDurationSeconds ?? getTrustedTasksDurations(expectation.deployment.chainId).workDurationSeconds;
45270
+ if (workDuration === void 0) fail2("missing trusted work duration");
45271
+ requireArgs([
45272
+ expectation.buyer,
45273
+ expectation.deployment.usdc,
45274
+ BigInt(expectation.milestone.amountBaseUnits),
45275
+ BigInt(workDuration),
45276
+ BigInt(
45277
+ expectation.reviewWindowSeconds ?? expectation.milestone.terms.acceptanceWindowSeconds
45278
+ ),
45279
+ expectation.milestone.termsHash,
45280
+ keccak256(stringToHex(expectation.milestone.id))
45281
+ ]);
45282
+ } else if (plan.step === "fund-with-authorization") {
45283
+ const a = expectation.authorization;
45284
+ if (!a)
45285
+ throw new TasksChainError("Unsafe transaction plan: missing local authorization", false);
45286
+ requireArgs([BigInt(a.validAfter), BigInt(a.validBefore), a.nonce, a.signature]);
45287
+ } else if (plan.step === "approve-usdc") {
45288
+ if (expectation.approveAmount === void 0) fail2("missing verified approval amount");
45289
+ requireArgs([expectation.milestone.escrowContract, expectation.approveAmount]);
45290
+ } else if (plan.step === "submit-delivery") {
45291
+ if (!expectation.manifestHash) fail2("missing manifest hash");
45292
+ requireArgs([expectation.manifestHash]);
45293
+ } else if (plan.step === "raise-dispute" || plan.step === "submit-counter-evidence") {
45294
+ if (!expectation.evidenceHash) fail2("missing evidence hash");
45295
+ requireArgs([expectation.evidenceHash]);
45296
+ } else requireArgs([]);
45166
45297
  }
45167
- async function taskRequest(verb, route, operation, options) {
45168
- try {
45169
- return await operation();
45170
- } catch (error61) {
45171
- if (error61 instanceof TasksChainUnavailableError || error61 instanceof Error && "code" in error61 && error61.code === "chain_unavailable") {
45172
- const hash9 = typeof error61 === "object" && error61 !== null && "manifestHash" in error61 && typeof error61.manifestHash === "string" ? error61.manifestHash : void 0;
45173
- throw new TaskOperationError(
45174
- "chain_unavailable",
45175
- "An acting wallet is required for task chain operations.",
45176
- hash9
45177
- );
45178
- }
45179
- if (error61 instanceof TasksClientError) {
45180
- if (error61.code === "invalid_input") throw new TaskInputError(error61.message);
45181
- if (error61.status === 403 && error61.serverCode === "insufficient_scope") {
45182
- throw new TaskOperationError(
45183
- "insufficient_scope",
45184
- options.signInHint.includes("auth.link") ? "This sign-in lacks Tasks access. Call auth.link again." : "This sign-in lacks Tasks access. Run vapi login again."
45185
- );
45186
- }
45187
- if (error61.status === 404 && PENDING_SERVER_ROUTES.has(route) && !isMissingTaskEntity(error61.serverCode, error61.message))
45188
- throw new TaskOperationError(
45189
- "not_available",
45190
- `${verb} is not available on this server yet.`
45191
- );
45192
- if ((error61.status === 401 || error61.status === 403) && !["board", "publicTask", "receipt", "feed", "deployment"].includes(route))
45193
- throw new TaskOperationError(
45194
- "not_signed_in",
45195
- `${verb} needs sign-in. ${options.signInHint}`
45196
- );
45197
- throw new TaskOperationError(
45198
- error61.serverCode ?? (error61.status ? `http_${error61.status}` : error61.code),
45199
- error61.message
45200
- );
45201
- }
45202
- throw error61;
45203
- }
45204
- }
45205
- async function resolveTaskBearer(args) {
45206
- const link2 = args.wallets.entry(args.wallet)?.link;
45207
- if (!link2) return void 0;
45208
- if (new URL(link2.apiBase).origin !== new URL(args.baseUrl).origin)
45209
- throw new TaskOperationError(
45210
- "not_signed_in",
45211
- `The acting wallet is linked to a different server. ${args.signInHint}`
45212
- );
45213
- try {
45214
- const token = await agentAccessToken({
45215
- secrets: args.secrets,
45216
- wallets: args.wallets,
45217
- wallet: args.wallet,
45218
- ...args.fetchImpl ? { fetchImpl: args.fetchImpl } : {},
45219
- ...args.now ? { now: args.now } : {}
45220
- });
45221
- const current = args.wallets.entry(args.wallet)?.link;
45222
- if (current?.clientId !== link2.clientId || current.apiBase !== link2.apiBase)
45223
- throw new TaskOperationError(
45224
- "not_signed_in",
45225
- "The acting wallet's sign-in changed. Retry with its current server."
45226
- );
45227
- return token;
45228
- } catch (error61) {
45229
- if (error61 instanceof AgentLinkError && error61.code === "not_linked") return void 0;
45230
- throw error61;
45231
- }
45232
- }
45233
- var TASK_LIMITS = {
45234
- postDeadlineMinMs: 6e5,
45235
- proposalDurationMinMs: 6e5,
45236
- proposalDurationMaxMs: 7776e6,
45237
- proposalDurationUnitMs: 1e3,
45238
- proposalNoteMin: 1,
45239
- proposalNoteMax: 8e3,
45240
- titleMin: 3,
45241
- titleMax: 120,
45242
- briefMin: 10,
45243
- briefMax: 8e3,
45244
- maxAwardsMin: 1,
45245
- maxAwardsMax: 50,
45246
- deliveryFilesMin: 1,
45247
- deliveryFilesMax: 20,
45248
- deliveryNoteMax: 32e3,
45249
- messageMin: 1,
45250
- messageMax: 1e4,
45251
- searchTabs: ["trending", "new", "closing", "paid"],
45252
- disputeEvidenceHash: /^0x[0-9a-fA-F]{64}$/u,
45253
- uploadBytesMin: 1,
45254
- uploadBytesMax: 50 * 1024 * 1024,
45255
- watchIntervalMinMs: 1e3
45256
- };
45257
- function parseTaskDuration(text, now) {
45258
- const match = /^(\d+)(s|m|h|d)$/u.exec(text);
45259
- const units = { s: 1e3, m: 6e4, h: 36e5, d: 864e5 };
45260
- let milliseconds;
45261
- if (match) milliseconds = Number(match[1]) * units[match[2]];
45262
- else if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/u.test(text)) {
45263
- const datePart = text.slice(0, 10), day = /* @__PURE__ */ new Date(`${datePart}T00:00:00Z`);
45264
- if (!Number.isFinite(day.getTime()) || day.toISOString().slice(0, 10) !== datePart)
45265
- throw new TaskInputError("Expected a valid ISO-8601 timestamp.");
45266
- milliseconds = Date.parse(text) - now.getTime();
45267
- } else
45268
- throw new TaskInputError(
45269
- "Expected a duration such as 10m, 48h or 7d, or an ISO-8601 timestamp."
45270
- );
45271
- if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0 || !Number.isFinite(now.getTime()) || !Number.isFinite(new Date(now.getTime() + milliseconds).getTime()))
45272
- throw new TaskInputError(
45273
- "The duration or timestamp must be in the future and within the supported date range."
45298
+
45299
+ // src/tasks/chain-verification.ts
45300
+ var TasksPartiesNotBoundError = class extends TasksValidationError {
45301
+ constructor() {
45302
+ super(
45303
+ "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."
45274
45304
  );
45275
- return milliseconds;
45276
- }
45277
- async function readTaskFile(path) {
45278
- let details;
45279
- try {
45280
- details = await stat4(path);
45281
- } catch {
45282
- throw new TaskInputError(`Task file ${JSON.stringify(path)} could not be read.`);
45305
+ this.name = "TasksPartiesNotBoundError";
45283
45306
  }
45284
- if (!details.isFile())
45285
- throw new TaskInputError(
45286
- `Task file ${JSON.stringify(path)} must be a regular file, not a directory.`
45307
+ };
45308
+ async function verifyDeployment(ready, rpc, overrides) {
45309
+ const factory = getTrustedTasksFactory(ready.chainId, overrides);
45310
+ if (!factory)
45311
+ throw new TasksChainError(
45312
+ `No trusted Tasks escrow factory is configured for chain ${ready.chainId}. Set VAPI_TASKS_ESCROW_FACTORY_${ready.chainId}.`,
45313
+ false,
45314
+ { authorizationExposed: false }
45315
+ );
45316
+ if (!isAddressEqual(factory, ready.escrowContract))
45317
+ throw new TasksValidationError(
45318
+ "The Tasks readiness factory does not match the trusted factory."
45319
+ );
45320
+ if (await rpc.getChainId() !== ready.chainId)
45321
+ throw new TasksValidationError("The RPC chain ID does not match the task deployment.");
45322
+ const token = await rpc.readContract({
45323
+ address: factory,
45324
+ abi: TASKS_READ_ABI,
45325
+ functionName: "paymentToken"
45326
+ });
45327
+ if (!isAddressEqual(token, ready.usdc))
45328
+ throw new TasksValidationError(
45329
+ "The Tasks readiness token does not match the trusted factory payment token."
45330
+ );
45331
+ const [name, version5] = await Promise.all([
45332
+ rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "name" }),
45333
+ rpc.readContract({ address: token, abi: TASKS_READ_ABI, functionName: "version" })
45334
+ ]);
45335
+ const domain2 = { name, version: version5, chainId: ready.chainId, verifyingContract: getAddress(token) };
45336
+ if (ready.eip3009Domain && (ready.eip3009Domain.name !== name || ready.eip3009Domain.version !== version5 || ready.eip3009Domain.chainId !== ready.chainId || !isAddressEqual(ready.eip3009Domain.verifyingContract, token)))
45337
+ throw new TasksValidationError(
45338
+ "The funding authorization domain does not match the onchain token domain."
45287
45339
  );
45288
- const types = {
45289
- ".png": "image/png",
45290
- ".jpg": "image/jpeg",
45291
- ".jpeg": "image/jpeg",
45292
- ".webp": "image/webp",
45293
- ".gif": "image/gif",
45294
- ".pdf": "application/pdf",
45295
- ".zip": "application/zip",
45296
- ".txt": "text/plain",
45297
- ".md": "text/markdown",
45298
- ".json": "application/json",
45299
- ".csv": "text/csv"
45300
- };
45301
- const contentType = types[extname(path).toLowerCase()];
45302
- if (!contentType)
45303
- throw new TaskInputError("Task files must be images, PDF, ZIP, text, Markdown, JSON or CSV.");
45304
- const bytes = await readFile6(path);
45305
- if (bytes.length < TASK_LIMITS.uploadBytesMin || bytes.length > TASK_LIMITS.uploadBytesMax)
45306
- throw new TaskInputError("Task files must contain between 1 byte and 50 MiB.");
45307
45340
  return {
45308
- fileName: basename2(path),
45309
- bytes: Uint8Array.from(bytes),
45310
- contentType,
45311
- purpose: "delivery"
45341
+ ...ready,
45342
+ escrowContract: getAddress(factory),
45343
+ usdc: getAddress(token),
45344
+ eip3009Domain: domain2
45312
45345
  };
45313
45346
  }
45314
- function validTaskBrief(title, description) {
45315
- return title.trim().length >= TASK_LIMITS.titleMin && title.trim().length <= TASK_LIMITS.titleMax && description.trim().length >= TASK_LIMITS.briefMin && description.trim().length <= TASK_LIMITS.briefMax;
45316
- }
45317
- function proposalTerms(id, address9, deployment, terms) {
45318
- return {
45319
- version: "work-proposal-v1",
45320
- workOrderId: id,
45321
- // The server lowercases addresses before canonicalizing the signed payload.
45322
- providerAddress: address9.toLowerCase(),
45323
- pricingModel: "fixed",
45324
- milestones: [
45325
- {
45326
- version: "work-milestone-terms-v1",
45327
- title: terms.title,
45328
- description: terms.description,
45329
- acceptanceCriteria: ["Complete the task described in these terms."],
45330
- workDurationSeconds: terms.durationSeconds,
45331
- acceptanceWindowSeconds: 604800,
45332
- budget: {
45333
- network: deployment.network,
45334
- asset: `${deployment.network}/erc20:${deployment.usdc}`,
45335
- amountBaseUnits: terms.amount.toString()
45336
- },
45337
- escrow: { protocol: "escrow-v1", contract: deployment.escrowContract },
45338
- evidenceRules: { acceptedInputs: ["text", "private-file"], exactCommitRequired: false }
45339
- }
45340
- ]
45347
+ async function verifyScope(client, signer, selected, ready, verb, steps, options = {}) {
45348
+ const { scopes } = await client.getScopes(selected.workOrderId);
45349
+ const matches = scopes.filter(
45350
+ (scope2) => scope2.state === "accepted" && scope2.milestoneId === selected.id
45351
+ );
45352
+ if (matches.length !== 1)
45353
+ throw new TasksValidationError("The task milestone requires one accepted signed scope.");
45354
+ const scope = matches[0];
45355
+ const payload = scope.signingPayload;
45356
+ const frozen = freezeScopeTerms(scope.structuredTerms, scope.brief);
45357
+ 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)
45358
+ throw new TasksValidationError(
45359
+ "The accepted task scope does not match its locally verified terms hash and milestone."
45360
+ );
45361
+ if (!scope.counterpartyAddress || !scope.counterpartySignature || isAddressEqual(scope.proposerAddress, scope.counterpartyAddress) || !(isAddressEqual(signer, scope.proposerAddress) || isAddressEqual(signer, scope.counterpartyAddress)))
45362
+ throw new TasksValidationError(
45363
+ "The local signer is not one of the two accepted scope parties."
45364
+ );
45365
+ const message = canonicalJson(payload);
45366
+ const signatures = await Promise.all([
45367
+ verifyMessage({
45368
+ address: scope.proposerAddress,
45369
+ message,
45370
+ signature: scope.proposerSignature
45371
+ }),
45372
+ verifyMessage({
45373
+ address: scope.counterpartyAddress,
45374
+ message,
45375
+ signature: scope.counterpartySignature
45376
+ })
45377
+ ]);
45378
+ if (signatures.some((valid) => !valid))
45379
+ throw new TasksValidationError("Both accepted task scope signatures must verify.");
45380
+ const terms = frozen.structured;
45381
+ 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)
45382
+ throw new TasksValidationError(
45383
+ "The signed task scope asset, factory or amount does not match the deployment and milestone."
45384
+ );
45385
+ const identity = {
45386
+ orderId: selected.workOrderId,
45387
+ trancheOrdinal: selected.ordinal,
45388
+ scopeVersion: scope.version,
45389
+ termsHash: frozen.termsHash,
45390
+ self: getAddress(signer)
45341
45391
  };
45342
- }
45343
- function orderReceipts(order, baseUrl) {
45344
- if (order.version !== "work-order-view-v1") return [];
45345
- return order.milestones.filter(
45346
- (m) => ["released", "refunded"].includes(m.state) || m.escrowState === "resolved" && m.resolution !== null
45347
- ).map((m) => ({
45348
- receiptUrl: `${baseUrl.replace(/\/+$/u, "")}/receipts/${m.escrowContract}`,
45349
- receiptUrlSource: "escrow"
45350
- }));
45351
- }
45352
- var TASK_WATCH_STATES = [
45353
- "open",
45354
- "awarded",
45355
- "funded",
45356
- "delivered",
45357
- "paid",
45358
- "released",
45359
- "refunded",
45360
- "disputed",
45361
- "expired",
45362
- "closed",
45363
- "completed",
45364
- "cancelled",
45365
- "checkin",
45366
- "stalled",
45367
- "claimed",
45368
- "judging",
45369
- "milestone"
45370
- ];
45371
- function taskEventState(event) {
45372
- return typeof event.payload.state === "string" ? event.payload.state.toLowerCase() : event.type.split(".").at(-1)?.toLowerCase() ?? event.type.toLowerCase();
45373
- }
45374
- function taskStateMatches(until, state) {
45375
- return until === state || until === "paid" && state === "released";
45376
- }
45377
- function nextTaskEvents(page, cursor) {
45378
- if (!Number.isSafeInteger(page.nextAfter) || page.nextAfter < cursor)
45379
- throw new TaskOperationError(
45380
- "invalid_response",
45381
- "The task event cursor regressed or is malformed."
45392
+ const binding = await options.bindings?.get(identity);
45393
+ if (!binding) throw new TasksPartiesNotBoundError();
45394
+ if (options.counterparty && !isAddressEqual(binding.counterparty, options.counterparty))
45395
+ throw new TasksValidationError(
45396
+ "The confirmed counterparty differs from the locally bound parties."
45397
+ );
45398
+ 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(
45399
+ (address9) => isAddressEqual(address9, binding.self) || isAddressEqual(address9, binding.counterparty)
45400
+ ))
45401
+ throw new TasksValidationError(
45402
+ "The accepted scope parties do not match the locally bound parties."
45403
+ );
45404
+ const buyer = getAddress(binding.role === "client" ? binding.self : binding.counterparty);
45405
+ const seller = getAddress(binding.role === "provider" ? binding.self : binding.counterparty);
45406
+ if (verb === "createEscrow" && !isAddressEqual(signer, seller))
45407
+ throw new TasksValidationError("Task createEscrow requires the locally bound seller's wallet.");
45408
+ const workDurationSeconds = terms.workDurationSeconds ?? getTrustedTasksDurations(ready.chainId, options.trustedDurations).workDurationSeconds;
45409
+ if (workDurationSeconds === void 0)
45410
+ throw new TasksValidationError(
45411
+ "The signed task scope has no work duration and no trusted default is configured."
45382
45412
  );
45383
- for (const event of page.events)
45384
- if (!Number.isSafeInteger(event.sequence) || event.sequence < 0)
45385
- throw new TaskOperationError("invalid_response", "A task event sequence is malformed.");
45386
- const seen = /* @__PURE__ */ new Set();
45387
- const events = [...page.events].sort((a, b) => a.sequence - b.sequence).filter((event) => {
45388
- if (event.sequence <= cursor || seen.has(event.sequence)) return false;
45389
- seen.add(event.sequence);
45390
- return true;
45391
- });
45392
45413
  return {
45393
- events,
45394
- nextCursor: Math.max(cursor, page.nextAfter, ...page.events.map((e3) => e3.sequence))
45414
+ signer,
45415
+ buyer,
45416
+ seller,
45417
+ parties: [buyer, seller],
45418
+ workDurationSeconds,
45419
+ ...verb === "fund" ? { approveAmount: BigInt(terms.budget.amountBaseUnits) } : {},
45420
+ reviewWindowSeconds: terms.acceptanceWindowSeconds,
45421
+ nowSeconds: BigInt(Math.floor((options.now ?? (() => /* @__PURE__ */ new Date()))().getTime() / 1e3)),
45422
+ verb,
45423
+ deployment: ready,
45424
+ milestone: {
45425
+ ...selected,
45426
+ terms,
45427
+ termsHash: frozen.termsHash,
45428
+ amountBaseUnits: terms.budget.amountBaseUnits
45429
+ },
45430
+ steps
45395
45431
  };
45396
45432
  }
45397
- async function taskPolicyForWallet(args) {
45398
- let invalid = false;
45399
- const profiles = await listAgentProfiles(args.directory, {
45400
- schema: args.schema,
45401
- ...args.warn ? { warn: args.warn } : {},
45402
- onInvalid: () => {
45403
- invalid = true;
45404
- }
45433
+ async function verifyClone(rpc, expected, checkState) {
45434
+ if (expected.verb === "createEscrow") return;
45435
+ const clone2 = expected.milestone.escrowContract;
45436
+ const registered = await rpc.readContract({
45437
+ address: expected.deployment.escrowContract,
45438
+ abi: TASKS_READ_ABI,
45439
+ functionName: "isEscrow",
45440
+ args: [clone2]
45441
+ });
45442
+ if (!registered)
45443
+ throw new TasksValidationError(
45444
+ "The task escrow clone is not registered by the trusted factory."
45445
+ );
45446
+ const predicted = await rpc.readContract({
45447
+ address: expected.deployment.escrowContract,
45448
+ abi: TASKS_READ_ABI,
45449
+ functionName: "predictEscrow",
45450
+ args: [expected.seller, keccak256(stringToHex(expected.milestone.id))]
45405
45451
  });
45406
- if (invalid) throw new TaskInputError("An invalid agent profile prevents task policy selection.");
45407
- const matches = profiles.filter((profile2) => profile2.wallet === args.wallet);
45408
- if (matches.length > 1)
45409
- throw new TaskInputError(
45410
- `More than one agent profile uses wallet ${args.wallet}; task policy is ambiguous.`
45452
+ if (!isAddressEqual(predicted, clone2))
45453
+ throw new TasksValidationError(
45454
+ "The escrow clone does not match the signed milestone salt and bound seller."
45411
45455
  );
45412
- const profile = matches[0];
45413
- return profile ? {
45414
- maxPerTaskUsd: profile.maxPerTaskUsd,
45415
- approveAboveUsd: profile.approveAboveUsd,
45416
- autoReleaseBelowUsd: profile.autoReleaseBelowUsd,
45417
- source: "agent-profile"
45418
- } : {
45419
- maxPerTaskUsd: DEFAULT_MAX_PER_TASK_USD,
45420
- approveAboveUsd: agentProfileSchema.shape.approveAboveUsd.parse(void 0),
45421
- autoReleaseBelowUsd: DEFAULT_AUTO_RELEASE_BELOW_USD,
45422
- source: "defaults"
45456
+ const read = (functionName) => rpc.readContract({ address: clone2, abi: TASKS_READ_ABI, functionName });
45457
+ const [
45458
+ buyer,
45459
+ seller,
45460
+ token,
45461
+ amount4,
45462
+ termsHash,
45463
+ state,
45464
+ resolution,
45465
+ offerDeadline,
45466
+ workDeadline,
45467
+ reviewDeadline,
45468
+ disputedAt,
45469
+ counterEvidenceDeadline,
45470
+ slot0,
45471
+ slot6,
45472
+ slot7
45473
+ ] = await Promise.all([
45474
+ read("buyer"),
45475
+ read("seller"),
45476
+ read("token"),
45477
+ read("amount"),
45478
+ read("termsHash"),
45479
+ read("state"),
45480
+ read("resolution"),
45481
+ read("offerDeadline"),
45482
+ read("workDeadline"),
45483
+ read("reviewDeadline"),
45484
+ read("disputedAt"),
45485
+ read("counterEvidenceDeadline"),
45486
+ rpc.getStorageAt({ address: clone2, slot: "0x0" }),
45487
+ rpc.getStorageAt({ address: clone2, slot: "0x6" }),
45488
+ rpc.getStorageAt({ address: clone2, slot: "0x7" })
45489
+ ]);
45490
+ 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())
45491
+ throw new TasksValidationError(
45492
+ "The onchain escrow parties, token, amount or terms hash do not match the signed scope."
45493
+ );
45494
+ const s0 = storageWord(slot0);
45495
+ const s6 = storageWord(slot6);
45496
+ const s7 = storageWord(slot7);
45497
+ 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)
45498
+ throw new TasksValidationError("unsupported escrow layout");
45499
+ if (field(s7, 8, 8) !== BigInt(expected.workDurationSeconds) || field(s7, 16, 8) !== BigInt(expected.reviewWindowSeconds))
45500
+ throw new TasksValidationError(
45501
+ "The onchain escrow durations do not match the signed terms and trusted defaults."
45502
+ );
45503
+ const actor = expected.verb === "fund" || expected.verb === "release" ? buyer : expected.verb === "deliver" || expected.verb === "refund" ? seller : expected.signer;
45504
+ if (!isAddressEqual(actor, expected.signer))
45505
+ throw new TasksValidationError(
45506
+ `Task ${expected.verb} requires the onchain escrow party's local wallet.`
45507
+ );
45508
+ const states = {
45509
+ fund: [1],
45510
+ deliver: [2],
45511
+ release: [3],
45512
+ refund: [2, 3],
45513
+ dispute: [2, 3],
45514
+ "counter-evidence": [4],
45515
+ "resolve-unmatched": [4]
45423
45516
  };
45424
- }
45425
- async function taskMoneySnapshot(client, orderId, escrowId, options = { signInHint: "" }) {
45426
- const order = await taskRequest(
45427
- "task money",
45428
- "getOrder",
45429
- () => client.getOrder(orderId),
45430
- options
45431
- ), workOrder = order.workOrder;
45432
- if (workOrder.id !== orderId || workOrder.version !== "work-order-view-v1")
45433
- throw new TaskOperationError(
45434
- "invalid_response",
45435
- "A private task order matching the requested ID is required."
45517
+ if (checkState && !states[expected.verb]?.includes(state))
45518
+ throw new TasksValidationError(
45519
+ `The onchain escrow state is not eligible for task ${expected.verb}.`
45436
45520
  );
45437
- const matches = escrowId ? workOrder.milestones.filter((m) => m.id === escrowId) : workOrder.milestones;
45438
- if (matches.length !== 1)
45439
- throw new TaskOperationError("invalid_response", "Select one task milestone by escrow ID.");
45440
- const milestone = matches[0];
45441
- if (milestone.workOrderId !== orderId)
45442
- throw new TaskOperationError("invalid_response", "The milestone belongs to a different task.");
45443
- let readiness;
45444
- try {
45445
- readiness = { ok: true, value: await client.deployment() };
45446
- } catch (error61) {
45447
- readiness = { ok: false, error: error61 };
45521
+ if (["dispute", "counter-evidence"].includes(expected.verb)) {
45522
+ const fee = disputeFeeBaseUnits(amount4);
45523
+ if (await read("disputeFee") !== fee)
45524
+ throw new TasksValidationError(
45525
+ "The onchain dispute fee does not match the verified amount fee rule."
45526
+ );
45527
+ expected.disputeFee = fee;
45528
+ expected.approveAmount = fee;
45448
45529
  }
45449
- return {
45450
- order,
45451
- escrowId: milestone.id,
45452
- money: taskMoney(milestone.amountBaseUnits, readiness.ok ? parseFeeBp(readiness.value) : null),
45453
- readiness
45454
- };
45455
- }
45456
- function cachedMoneyClient(client, snapshot) {
45457
- return new Proxy(client, {
45458
- get(target, property) {
45459
- if (property === "getOrder")
45460
- return async (id) => {
45461
- if (id !== snapshot.order.workOrder.id)
45462
- throw new Error("The cached task order does not match the requested ID.");
45463
- return snapshot.order;
45464
- };
45465
- if (property === "deployment")
45466
- return async () => {
45467
- if (snapshot.readiness.ok) return snapshot.readiness.value;
45468
- throw snapshot.readiness.error;
45469
- };
45470
- const value = Reflect.get(target, property, target);
45471
- return typeof value === "function" ? value.bind(target) : value;
45472
- }
45473
- });
45474
- }
45475
- function fundingRefusalReason(error61) {
45476
- if (error61 instanceof Error && error61.name === "SpendCapExceededError") {
45477
- const fromCause = fundingRefusalReason(error61.cause);
45478
- if (fromCause) return fromCause;
45479
- return "cap" in error61 && error61.cap === "per_day" ? "policy.perDay" : void 0;
45530
+ if (checkState && ["counter-evidence", "resolve-unmatched"].includes(expected.verb)) {
45531
+ const slot8 = storageWord(await rpc.getStorageAt({ address: clone2, slot: "0x8" }));
45532
+ const opener = storageAddress(slot8, 0);
45533
+ const submitted = field(slot8, 20, 1);
45534
+ if (!isAddressEqual(opener, buyer) && !isAddressEqual(opener, seller) || submitted > 1n || field(slot8, 21, 11) !== 0n)
45535
+ throw new TasksValidationError("unsupported escrow layout");
45536
+ const now = expected.nowSeconds;
45537
+ if (now === void 0)
45538
+ throw new TasksValidationError("A trusted clock is required for dispute eligibility.");
45539
+ if (submitted === 1n)
45540
+ throw new TasksValidationError(
45541
+ "Counter-evidence has already been submitted for this dispute."
45542
+ );
45543
+ if (expected.verb === "counter-evidence") {
45544
+ if (isAddressEqual(opener, expected.signer))
45545
+ throw new TasksValidationError("Only the non-opener party can submit counter-evidence.");
45546
+ if (now >= counterEvidenceDeadline)
45547
+ throw new TasksValidationError("The counter-evidence deadline has passed.");
45548
+ } else if (now <= counterEvidenceDeadline)
45549
+ throw new TasksValidationError(
45550
+ "The counter-evidence deadline has not passed; unmatched resolution is unavailable."
45551
+ );
45480
45552
  }
45481
- if (!(error61 instanceof SpendCapError || error61 instanceof Error && error61.name === "SpendCapError"))
45482
- return void 0;
45483
- const code = "code" in error61 ? error61.code : void 0;
45484
- return code === "per_task_cap_exceeded" ? "policy.perTask" : code === "per_day_cap_exceeded" ? "policy.perDay" : void 0;
45553
+ expected.offerDeadline = offerDeadline;
45485
45554
  }
45486
- function taskEventLine(event) {
45487
- 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;
45488
- return `${event.sequence}: ${[label2, ...taskV2OutcomeLines(event.payload)].join(" \xB7 ")}`;
45555
+ function storageWord(value) {
45556
+ if (!value || !/^0x[0-9a-fA-F]{64}$/.test(value))
45557
+ throw new TasksValidationError("unsupported escrow layout");
45558
+ return BigInt(value);
45489
45559
  }
45490
- function requireTaskMethod(client, name) {
45491
- const method = client[name];
45492
- if (typeof method !== "function")
45493
- throw new TaskOperationError(
45494
- "not_supported",
45495
- `Task method ${name} is not supported by this SDK adapter.`
45496
- );
45497
- return method.bind(client);
45560
+ function field(word, offset, bytes) {
45561
+ return word >> BigInt(offset * 8) & (1n << BigInt(bytes * 8)) - 1n;
45562
+ }
45563
+ function storageAddress(word, offset) {
45564
+ return getAddress(`0x${field(word, offset, 20).toString(16).padStart(40, "0")}`);
45498
45565
  }
45499
45566
 
45500
45567
  // src/tasks/v2-trust.ts
@@ -45587,12 +45654,65 @@ function getTrustedTasksV2Deployment(chainId, options = {}) {
45587
45654
  return normalized2;
45588
45655
  }
45589
45656
 
45657
+ // src/tasks/v2-limits.ts
45658
+ var feeBpSchema = external_exports.union([external_exports.number(), external_exports.bigint()]).transform(Number).pipe(external_exports.number().int().min(0).max(2e3));
45659
+ var capSchema = external_exports.bigint().positive();
45660
+ async function readTaskV2Limits(input2) {
45661
+ const read = async () => {
45662
+ const pin = getTrustedTasksV2Deployment(input2.chainId, {
45663
+ ...input2.trustedV2Deployments ? { overrides: input2.trustedV2Deployments } : {},
45664
+ ...input2.env ? { env: input2.env } : {},
45665
+ // Display and pre-check only; the signing path prints the override notice.
45666
+ notice: input2.onV2UntrustedOverride ?? (() => {
45667
+ })
45668
+ });
45669
+ const rpc = input2.rpcFor(input2.chainId);
45670
+ if (await rpc.getChainId() !== input2.chainId) throw new Error("RPC chain mismatch");
45671
+ const pool = input2.shape === "pool";
45672
+ const address9 = pool ? pin.bountyPoolFactoryV1 : pin.escrowFactoryV2;
45673
+ const abi2 = pool ? bountyPoolFactoryV1Abi : escrowFactoryV2Abi;
45674
+ const [feeBp, cap] = await Promise.all([
45675
+ rpc.readContract({ address: address9, abi: abi2, functionName: "feeBp" }),
45676
+ rpc.readContract({
45677
+ address: address9,
45678
+ abi: abi2,
45679
+ functionName: pool ? "maxPoolBudget" : "maxEscrowAmount"
45680
+ })
45681
+ ]);
45682
+ return {
45683
+ chainId: input2.chainId,
45684
+ shape: input2.shape,
45685
+ feeBp: feeBpSchema.parse(feeBp),
45686
+ maxBaseUnits: capSchema.parse(cap)
45687
+ };
45688
+ };
45689
+ let timer;
45690
+ try {
45691
+ return await Promise.race([
45692
+ read(),
45693
+ new Promise((resolve) => {
45694
+ timer = setTimeout(() => resolve(void 0), input2.timeoutMs ?? 5e3);
45695
+ })
45696
+ ]);
45697
+ } catch {
45698
+ return void 0;
45699
+ } finally {
45700
+ if (timer) clearTimeout(timer);
45701
+ }
45702
+ }
45703
+ function assertWithinTaskV2Limit(totalBaseUnits, limits, untouched = "Nothing was signed and no money moved.") {
45704
+ if (totalBaseUnits <= limits.maxBaseUnits) return;
45705
+ throw new TaskInputError(
45706
+ `The total of $${formatBaseUnitsUsd(totalBaseUnits)} USDC is above the live limit of $${formatBaseUnitsUsd(limits.maxBaseUnits)} USDC per ${limits.shape} on ${taskNetworkName(limits.chainId)}. ${untouched}`
45707
+ );
45708
+ }
45709
+
45590
45710
  // src/tasks/v2-plan-guard.ts
45591
45711
  var address4 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).transform((v) => getAddress(v));
45592
45712
  var hash5 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u).transform((v) => v.toLowerCase());
45593
45713
  var uint2 = external_exports.union([external_exports.bigint(), external_exports.number().int().nonnegative(), external_exports.string().regex(/^\d+$/u)]).transform(BigInt);
45594
45714
  var small = (max) => external_exports.union([external_exports.number(), external_exports.bigint()]).transform(Number).pipe(external_exports.number().int().min(0).max(max));
45595
- var feeBpSchema = small(2e3);
45715
+ var feeBpSchema2 = small(2e3);
45596
45716
  var escrowTermsSchema = external_exports.object({
45597
45717
  shape: small(1),
45598
45718
  poster: address4,
@@ -45604,7 +45724,7 @@ var escrowTermsSchema = external_exports.object({
45604
45724
  bountyDeadline: uint2,
45605
45725
  objectionWindow: uint2,
45606
45726
  workerBondBp: small(2e3),
45607
- feeBp: feeBpSchema,
45727
+ feeBp: feeBpSchema2,
45608
45728
  winners: small(255),
45609
45729
  rewardPerWinner: uint2
45610
45730
  });
@@ -45868,7 +45988,7 @@ function verifyActor(action, signer, poster, worker, verifier) {
45868
45988
  );
45869
45989
  }
45870
45990
  async function creationPolicy(rpc, pin, pool) {
45871
- const feeBp = feeBpSchema.parse(
45991
+ const feeBp = feeBpSchema2.parse(
45872
45992
  await v2Read(
45873
45993
  rpc,
45874
45994
  pool ? pin.bountyPoolFactoryV1 : pin.escrowFactoryV2,
@@ -45887,10 +46007,13 @@ async function verifyFundingDeadlines(rpc, contract, deadlines, timestamp) {
45887
46007
  `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.`
45888
46008
  );
45889
46009
  }
45890
- async function verifyV2Target(options, current, view, action, knownTarget) {
46010
+ async function verifyV2Target(options, current, view, action, knownTarget, fundingMined = false) {
45891
46011
  const operation = taskV2OperationResponseSchema.safeParse(current);
45892
46012
  const intent = taskV2IntentSchema.safeParse(current);
45893
- 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;
46013
+ const plan = operation.success ? operation.data.operation.plan : null;
46014
+ if (operation.success && !plan)
46015
+ return v2GuardFailure("The hosted operation carries no plan to verify.");
46016
+ const chainId = plan ? plan.chainId : intent.success ? intent.data.typedData.domain.chainId : external_exports.object({ chainId: external_exports.number().int().positive() }).parse(current).chainId;
45894
46017
  const binding = await options.pending.v2Target?.(view.workOrder.id);
45895
46018
  if (action.action === "bump-consent-nonce" && !binding)
45896
46019
  return v2GuardFailure("Revocation requires a locally accepted consent target binding.");
@@ -45922,11 +46045,8 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
45922
46045
  let candidate = knownTarget ?? external_exports.object({ escrow: address4 }).safeParse(order.v2State).data?.escrow ?? (intent.success ? external_exports.object({ escrow: address4 }).safeParse(intent.data).data?.escrow : void 0);
45923
46046
  let creationArgs;
45924
46047
  let fresh;
45925
- if (action.action === "fund" && operation.success && same(operation.data.operation.plan.to, factory)) {
45926
- const decoded = decodeFunctionData({
45927
- abi: factoryAbi,
45928
- data: operation.data.operation.plan.data
45929
- });
46048
+ if (action.action === "fund" && plan && same(plan.to, factory)) {
46049
+ const decoded = decodeFunctionData({ abi: factoryAbi, data: plan.data });
45930
46050
  const names = pool ? ["createPool"] : ["createEscrow", "createAndFundWithAuthorization"];
45931
46051
  if (!names.includes(decoded.functionName))
45932
46052
  return v2GuardFailure("Unexpected V2 factory funding selector.");
@@ -45936,7 +46056,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
45936
46056
  verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
45937
46057
  candidate = await predict(creationArgs);
45938
46058
  }
45939
- if (action.action === "fund" && operation.success && operation.data.operation.plan.step === "v2-approve-usdc" && (!candidate || !await isRegistered(candidate))) {
46059
+ if (action.action === "fund" && plan?.step === "v2-approve-usdc" && (!candidate || !await isRegistered(candidate))) {
45940
46060
  fresh = await creationPolicy(rpc, pin, pool);
45941
46061
  creationArgs = acceptedCreationArgs(options, view, pin, chainId, fresh);
45942
46062
  verifyAcceptedCreation(options, view, pin, creationArgs, pool, chainId, fresh);
@@ -45952,7 +46072,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
45952
46072
  "The V2 target cannot be independently verified from this response. A registered target or verifiable funding creation terms are required."
45953
46073
  );
45954
46074
  if (!await isRegistered(candidate)) {
45955
- if (action.action !== "fund" || !operation.success || !creationArgs || !fresh)
46075
+ if (action.action !== "fund" || !plan || !creationArgs || !fresh)
45956
46076
  return v2GuardFailure("The V2 target is not registered by the locally pinned factory.");
45957
46077
  const expectedCreation = acceptedCreationArgs(options, view, pin, chainId, fresh);
45958
46078
  if (canon(creationArgs) !== canon(expectedCreation))
@@ -46004,7 +46124,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
46004
46124
  poster = address4.parse(await read("poster"));
46005
46125
  verifier = address4.parse(await read("verifier"));
46006
46126
  total = uint2.parse(await read("budget"));
46007
- feeBp = feeBpSchema.parse(await read("feeBp"));
46127
+ feeBp = feeBpSchema2.parse(await read("feeBp"));
46008
46128
  termsHash = hash5.parse(await read("termsHash"));
46009
46129
  creationArgs = [
46010
46130
  poster,
@@ -46068,7 +46188,7 @@ async function verifyV2Target(options, current, view, action, knownTarget) {
46068
46188
  "The V2 target differs from the pinned factory's prediction for the requested order."
46069
46189
  );
46070
46190
  verifyBinding(candidate, termsHash);
46071
- if (action.action === "fund" && !pool && !bounty)
46191
+ if (action.action === "fund" && !pool && !bounty && !fundingMined)
46072
46192
  await verifyFundingDeadlines(
46073
46193
  rpc,
46074
46194
  candidate,
@@ -46172,6 +46292,7 @@ function acceptedV2WorkerBond(target, view) {
46172
46292
  }
46173
46293
  async function verifyV2Plan(target, op, action, pays, fundingAuthorization) {
46174
46294
  const plan = op.plan;
46295
+ if (!plan) return v2GuardFailure("The hosted operation carries no plan to verify.");
46175
46296
  if (plan.value !== "0" || plan.chainId !== target.chainId)
46176
46297
  return v2GuardFailure("V2 plan value or chain mismatch.");
46177
46298
  const authorizationArgs = fundingAuthorization ? [
@@ -46438,7 +46559,8 @@ function isTaskV2SecretAction(action) {
46438
46559
  return action.action === "commit-vote" || action.action === "reveal-vote";
46439
46560
  }
46440
46561
  function publicTaskV2Operation(op, secret = false) {
46441
- const reveal = secret || op.step === "v2-reveal-vote" || op.plan.step === "v2-reveal-vote" || op.plan.data.toLowerCase().startsWith(REVEAL_SELECTOR);
46562
+ const plan = op.plan;
46563
+ const reveal = secret || op.step === "v2-reveal-vote" || plan?.step === "v2-reveal-vote" || plan?.data.toLowerCase().startsWith(REVEAL_SELECTOR) === true;
46442
46564
  return {
46443
46565
  id: op.id,
46444
46566
  kind: op.kind,
@@ -46446,16 +46568,17 @@ function publicTaskV2Operation(op, secret = false) {
46446
46568
  step: op.step,
46447
46569
  expectedActor: op.expectedActor,
46448
46570
  transactionHash: op.transactionHash,
46449
- plan: {
46450
- version: op.plan.version,
46451
- operationId: op.plan.operationId,
46452
- step: op.plan.step,
46453
- chainId: op.plan.chainId,
46454
- network: op.plan.network,
46455
- from: op.plan.from,
46456
- to: op.plan.to,
46457
- data: reveal ? TASK_V2_REDACTED_CALLDATA : op.plan.data,
46458
- value: op.plan.value
46571
+ // Null once the transaction is submitted or confirmed: the API no longer returns the plan.
46572
+ plan: plan && {
46573
+ version: plan.version,
46574
+ operationId: plan.operationId,
46575
+ step: plan.step,
46576
+ chainId: plan.chainId,
46577
+ network: plan.network,
46578
+ from: plan.from,
46579
+ to: plan.to,
46580
+ data: reveal ? TASK_V2_REDACTED_CALLDATA : plan.data,
46581
+ value: plan.value
46459
46582
  }
46460
46583
  };
46461
46584
  }
@@ -46476,7 +46599,7 @@ var shownOperationSchema = external_exports.object({
46476
46599
  to: external_exports.string(),
46477
46600
  data: external_exports.string(),
46478
46601
  value: external_exports.literal("0")
46479
- })
46602
+ }).nullable()
46480
46603
  });
46481
46604
  function publicTaskV2OperationOf(value, secret = false) {
46482
46605
  const parsed = shownOperationSchema.safeParse(value);
@@ -46696,6 +46819,9 @@ function bufferedV2Gas(estimate) {
46696
46819
  var fail = (message) => {
46697
46820
  throw new TaskOperationError("invalid_response", message);
46698
46821
  };
46822
+ var balanceAbi = parseAbi(["function balanceOf(address account) view returns (uint256)"]);
46823
+ var PAID_NOW_ACTIONS = ["fund", "raise-dispute", "counter-evidence"];
46824
+ var RESERVING_ACTIONS = [...PAID_NOW_ACTIONS, "approve-bond"];
46699
46825
  async function taskUsesV2(context, id) {
46700
46826
  if (!context.client.prepareV2) return false;
46701
46827
  const { workOrder } = await context.client.getOrder(id);
@@ -46723,6 +46849,7 @@ async function executeTaskV2(context, input2) {
46723
46849
  }
46724
46850
  const saved = journal.preparedV2;
46725
46851
  if (saved) return saved;
46852
+ requireTasksAvailable(action.action, await readTasksReadiness(context.client));
46726
46853
  const result = await (input2.consent ? context.client.signV2(input2.id, input2.consent, journal) : context.client.prepareV2(input2.id, input2.write, journal));
46727
46854
  await context.pending?.bindPreparedV2?.(input2.id, verb, result);
46728
46855
  return result;
@@ -46756,17 +46883,76 @@ function createTaskV2Executor(options) {
46756
46883
  journal = { idempotencyKey: input2.preparationKey ?? randomUUID(), inputs: action };
46757
46884
  await pending.putPreparation(input2.id, verb, journal);
46758
46885
  }
46759
- let current = taskV2PreparedSchema.parse(
46760
- input2.prepared ?? journal.preparedV2 ?? await (input2.consent ? sign(input2.id, input2.consent, journal) : prepare(input2.id, input2.write, journal))
46761
- );
46762
46886
  if (!pending.bindPreparedV2) fail("Durable V2 preparation storage is unavailable.");
46763
- await pending.bindPreparedV2(input2.id, verb, current);
46887
+ const supplied = input2.prepared ?? journal.preparedV2;
46888
+ let current = supplied === void 0 ? void 0 : taskV2PreparedSchema.parse(supplied);
46889
+ if (current) await pending.bindPreparedV2(input2.id, verb, current);
46890
+ const finalStep = action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`;
46891
+ 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];
46892
+ const reservedForTask = (excludeReservationId) => taskReservedAtomic({
46893
+ ledgerPath: input2.ledgerPath,
46894
+ wallet: input2.wallet,
46895
+ taskKey: input2.id,
46896
+ now: now(),
46897
+ ...excludeReservationId === void 0 ? {} : { excludeReservationId }
46898
+ });
46899
+ const savedOperation = journal.operationId;
46900
+ const savedTransaction = savedOperation !== void 0 && (await Promise.all(allowedSteps.map((step2) => pending.get(savedOperation, step2)))).some(
46901
+ (entry) => entry !== void 0
46902
+ );
46903
+ const signedBefore = journal.signed === true;
46904
+ const started = savedTransaction || RESERVING_ACTIONS.includes(action.action) && (signedBefore || await reservedForTask() !== await reservedForTask(journal.idempotencyKey));
46905
+ const savedFinal = savedOperation === void 0 ? void 0 : await pending.get(savedOperation, finalStep);
46906
+ const mined = savedFinal && isAddressEqual(savedFinal.signer, account.address) && (await Promise.resolve().then(
46907
+ () => rpcFor(savedFinal.chainId).getTransactionReceipt({ hash: savedFinal.txHash })
46908
+ ).catch(() => void 0))?.status === "success" ? savedFinal : void 0;
46909
+ if (current && !started && action.action === "fund" && "kind" in current && current.kind === "eip712") {
46910
+ const end = external_exports.object({ validBefore: uint3 }).safeParse(taskV2IntentSchema.parse(current).typedData.message);
46911
+ if (end.success && BigInt(end.data.validBefore) * 1000n <= BigInt(now().getTime())) {
46912
+ await pending.completePreparation(input2.id, verb);
46913
+ journal = { idempotencyKey: randomUUID(), inputs: action };
46914
+ await pending.putPreparation(input2.id, verb, journal);
46915
+ current = void 0;
46916
+ }
46917
+ }
46918
+ const readiness = await readTasksReadiness(client);
46919
+ if (!started)
46920
+ requireTasksAvailable(
46921
+ action.action,
46922
+ readiness,
46923
+ 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
46924
+ );
46925
+ if (!current) {
46926
+ current = taskV2PreparedSchema.parse(
46927
+ await (input2.consent ? sign(input2.id, input2.consent, journal) : prepare(input2.id, input2.write, journal))
46928
+ );
46929
+ await pending.bindPreparedV2(input2.id, verb, current);
46930
+ }
46764
46931
  const view = await client.getOrder(input2.id);
46765
46932
  if (view.workOrder.id !== input2.id) fail("The money view belongs to another task.");
46766
46933
  const terms = view.workOrder.terms;
46767
46934
  const state = stateSchema.safeParse(view.workOrder.v2State);
46768
- const deployment = await client.deployment();
46769
- const target = await verifyV2Target(options, current, view, action);
46935
+ const resumed = taskV2OperationResponseSchema.safeParse(current);
46936
+ let resumedChainId;
46937
+ if (resumed.success && !resumed.data.operation.plan) {
46938
+ resumedChainId = (await pending.v2Target?.(input2.id))?.chainId ?? readiness?.chainId;
46939
+ if (resumedChainId === void 0)
46940
+ fail("The hosted operation carries no plan and its chain cannot be read.");
46941
+ }
46942
+ const target = await verifyV2Target(
46943
+ options,
46944
+ resumedChainId === void 0 ? current : { chainId: resumedChainId },
46945
+ view,
46946
+ action,
46947
+ void 0,
46948
+ mined !== void 0
46949
+ );
46950
+ if (mined && mined.chainId !== target.chainId)
46951
+ fail("The saved transaction is for another chain than the verified task.");
46952
+ if (readiness && target.chainId !== readiness.chainId)
46953
+ fail(
46954
+ `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."}`
46955
+ );
46770
46956
  if (state.success && (BigInt(state.data.totalBaseUnits) !== target.total || state.data.feeBp !== target.feeBp))
46771
46957
  v2GuardFailure("Hosted money snapshot differs from the verified V2 target.");
46772
46958
  let gross = 0n, pays = 0n;
@@ -46810,8 +46996,7 @@ function createTaskV2Executor(options) {
46810
46996
  else gross = total ?? 0n;
46811
46997
  feeBp = 0;
46812
46998
  } else if (action.action === "raise-dispute" || action.action === "counter-evidence") {
46813
- if (!state.success || !deployment.configured)
46814
- fail("Hosted dispute binding is unavailable.");
46999
+ if (!state.success) fail("Hosted dispute binding is unavailable.");
46815
47000
  pays = gross = await target.rpc.readContract({
46816
47001
  address: target.escrow,
46817
47002
  abi: escrowV2Abi,
@@ -46869,6 +47054,44 @@ function createTaskV2Executor(options) {
46869
47054
  }
46870
47055
  };
46871
47056
  await input2.onMoney?.(money);
47057
+ if (action.action === "fund" && !started) {
47058
+ const cap = await v2Read(
47059
+ target.rpc,
47060
+ target.factory,
47061
+ target.pool ? bountyPoolFactoryV1Abi : escrowFactoryV2Abi,
47062
+ target.pool ? "maxPoolBudget" : "maxEscrowAmount"
47063
+ ).catch(() => void 0);
47064
+ if (typeof cap === "bigint" && cap > 0n)
47065
+ assertWithinTaskV2Limit(gross, {
47066
+ chainId: target.chainId,
47067
+ shape: target.pool ? "pool" : target.bounty ? "bounty" : "task",
47068
+ feeBp: target.feeBp,
47069
+ maxBaseUnits: cap
47070
+ });
47071
+ }
47072
+ if (pays > 0n && PAID_NOW_ACTIONS.includes(action.action) && !started) {
47073
+ const balance = await target.rpc.readContract({
47074
+ address: target.pin.usdc,
47075
+ abi: balanceAbi,
47076
+ functionName: "balanceOf",
47077
+ args: [account.address]
47078
+ }).catch(() => void 0);
47079
+ if (typeof balance === "bigint" && balance < pays)
47080
+ throw new TaskOperationError(
47081
+ "insufficient_usdc",
47082
+ `This step pays $${formatBaseUnitsUsd(pays)} USDC, but the wallet holds $${formatBaseUnitsUsd(balance)} on ${taskNetworkName(target.chainId)}. Nothing was signed and no money moved.`,
47083
+ void 0,
47084
+ progress
47085
+ );
47086
+ const gas = await Promise.resolve().then(() => target.rpc.getBalance({ address: account.address })).catch(() => void 0);
47087
+ if (gas === 0n)
47088
+ throw new TaskOperationError(
47089
+ "insufficient_gas",
47090
+ `The wallet holds no ETH on ${taskNetworkName(target.chainId)} to pay for the transaction. Nothing was signed and no money moved.`,
47091
+ void 0,
47092
+ progress
47093
+ );
47094
+ }
46872
47095
  const reservationKey = journal.idempotencyKey;
46873
47096
  const remaining = pays > 0n ? await escrowFundingDayRemainingAtomic({
46874
47097
  caps: input2.caps,
@@ -46884,11 +47107,11 @@ function createTaskV2Executor(options) {
46884
47107
  now: now(),
46885
47108
  excludeReservationId: reservationKey
46886
47109
  }) : 0n;
46887
- if (pays + alreadyReserved > taskPolicyAtomic(input2.policy.maxPerTaskUsd))
47110
+ if (!mined && pays + alreadyReserved > taskPolicyAtomic(input2.policy.maxPerTaskUsd))
46888
47111
  return { ok: false, reason: "policy.perTask", money, ...progress };
46889
- if (pays > remaining)
47112
+ if (!mined && pays > remaining)
46890
47113
  return { ok: false, reason: "policy.perDay", money, ...progress };
46891
- if (pays > taskPolicyAtomic(input2.policy.approveAboveUsd)) {
47114
+ if (!mined && pays > taskPolicyAtomic(input2.policy.approveAboveUsd)) {
46892
47115
  if (input2.approval && "ask" in input2.approval) {
46893
47116
  if (!await input2.approval.ask({
46894
47117
  money: taskMoney(pays, 0),
@@ -46924,13 +47147,24 @@ function createTaskV2Executor(options) {
46924
47147
  };
46925
47148
  let fundingAuthorization;
46926
47149
  try {
47150
+ if (mined && "kind" in current)
47151
+ current = taskV2OperationResponseSchema.parse(
47152
+ await operationCall(savedOperation, "recover", { step: finalStep }, key2())
47153
+ );
46927
47154
  if ("kind" in current && current.kind === "eip712") {
46928
47155
  const intent = taskV2IntentSchema.parse(current);
46929
47156
  const typed = intent.typedData;
47157
+ if (started && !savedTransaction && !signedBefore)
47158
+ requireTasksAvailable(
47159
+ action.action,
47160
+ readiness,
47161
+ "No new signature was made. An authorization signed earlier stays valid until it expires."
47162
+ );
46930
47163
  await verifyV2TypedData(target, intent, action, account.address, pays);
46931
47164
  await bindTarget();
46932
47165
  await beforeSign();
46933
47166
  const signature = await account.signTypedData(typed);
47167
+ await pending.markPreparationSigned?.(input2.id, verb);
46934
47168
  if (action.action === "fund")
46935
47169
  fundingAuthorization = { message: typed.message, signature };
46936
47170
  const response = await confirmSignature(input2.id, intent.operationId, signature, key2());
@@ -46956,8 +47190,6 @@ function createTaskV2Executor(options) {
46956
47190
  }
46957
47191
  let result = taskV2OperationResponseSchema.parse(current);
46958
47192
  const operationId = result.operation.id;
46959
- const finalStep = action.action === "approve-bond" ? "v2-approve-usdc" : `v2-${action.action}`;
46960
- 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];
46961
47193
  const validate7 = (value) => {
46962
47194
  if (value.orderId !== input2.id || value.operation.id !== operationId || !isAddressEqual(value.operation.expectedActor, account.address) || !allowedSteps.includes(value.operation.step))
46963
47195
  fail("Hosted operation does not match the requested task, wallet or action.");
@@ -46976,10 +47208,17 @@ function createTaskV2Executor(options) {
46976
47208
  fail("Hosted sequence moved backwards.");
46977
47209
  return { parsed, complete: !("scanComplete" in response) || response.scanComplete };
46978
47210
  };
47211
+ let waiting;
46979
47212
  for (let poll2 = 0; poll2 < 256; poll2++) {
46980
47213
  validate7(result);
46981
47214
  progress = { ...progress, operation: publicTaskV2Operation(result.operation, secret) };
46982
47215
  const op = result.operation;
47216
+ if (op.state !== "prepared" || waiting?.step !== op.step) waiting = void 0;
47217
+ if (op.state === "prepared" && op.plan) {
47218
+ const shown = canonicalJson(op.plan);
47219
+ if (waiting && waiting.plan !== shown) fail("Recovery changed the prepared plan.");
47220
+ waiting = { step: op.step, plan: shown };
47221
+ }
46983
47222
  if (op.state === "confirmed") {
46984
47223
  if (op.step !== finalStep)
46985
47224
  fail("An approval alone cannot complete the requested action.");
@@ -47009,14 +47248,26 @@ function createTaskV2Executor(options) {
47009
47248
  result = recovered.parsed;
47010
47249
  continue;
47011
47250
  }
47012
- if (canonicalJson(recovered.parsed.operation.plan) !== canonicalJson(op.plan))
47251
+ if (mined) {
47252
+ if (op.step !== finalStep)
47253
+ fail(
47254
+ "vAPI asks for an earlier step although the last step of this operation is mined. Nothing was signed."
47255
+ );
47256
+ result = (await call2("transaction", op.step, mined.txHash)).parsed;
47257
+ if (result.operation.state === "prepared") await sleep(1e3);
47258
+ continue;
47259
+ }
47260
+ const plan = recovered.parsed.operation.plan;
47261
+ if (!plan) return fail("The hosted operation is prepared but carries no plan to sign.");
47262
+ if (waiting && waiting.plan !== canonicalJson(plan))
47013
47263
  fail("Recovery changed the prepared plan.");
47014
- const plan = op.plan;
47015
- if (!deployment.configured || plan.chainId !== deployment.chainId)
47016
- fail("Hosted plan deployment mismatch.");
47264
+ waiting = void 0;
47265
+ const step2 = { ...op, plan };
47266
+ if (plan.chainId !== target.chainId)
47267
+ fail("The hosted plan names another chain than the verified task.");
47017
47268
  const refreshed = await verifyV2Target(
47018
47269
  options,
47019
- { orderId: input2.id, operation: op },
47270
+ { orderId: input2.id, operation: step2 },
47020
47271
  view,
47021
47272
  action,
47022
47273
  target.escrow
@@ -47024,7 +47275,7 @@ function createTaskV2Executor(options) {
47024
47275
  if (!isAddressEqual(refreshed.escrow, target.escrow))
47025
47276
  v2GuardFailure("The continuation changed the verified V2 target.");
47026
47277
  try {
47027
- await verifyV2Plan(refreshed, op, action, pays, fundingAuthorization);
47278
+ await verifyV2Plan(refreshed, step2, action, pays, fundingAuthorization);
47028
47279
  } catch (error61) {
47029
47280
  if (error61 instanceof TaskOperationError) throw error61;
47030
47281
  v2GuardFailure("Unknown V2 selector or malformed ABI arguments.");
@@ -47033,7 +47284,6 @@ function createTaskV2Executor(options) {
47033
47284
  if (await rpc.getChainId() !== plan.chainId) fail("Transaction chain mismatch.");
47034
47285
  await input2.beforeSigning?.();
47035
47286
  await bindTarget();
47036
- await beforeSign();
47037
47287
  const saved = await pending.withStepLock(
47038
47288
  op.id,
47039
47289
  op.step,
@@ -47048,8 +47298,15 @@ function createTaskV2Executor(options) {
47048
47298
  account.address
47049
47299
  ))
47050
47300
  fail("Saved transaction differs from the hosted plan.");
47301
+ await beforeSign();
47051
47302
  return existing;
47052
47303
  }
47304
+ if (started)
47305
+ requireTasksAvailable(
47306
+ action.action,
47307
+ readiness,
47308
+ "This step was not signed. Anything this operation signed earlier stands."
47309
+ );
47053
47310
  const nonce = Math.max(
47054
47311
  await rpc.getTransactionCount({ address: account.address, blockTag: "pending" }),
47055
47312
  await pending.nextNonce(plan.chainId, account.address)
@@ -47064,6 +47321,7 @@ function createTaskV2Executor(options) {
47064
47321
  nonce
47065
47322
  });
47066
47323
  if (request.gas === void 0) fail("The V2 transaction has no gas estimate.");
47324
+ await beforeSign();
47067
47325
  const raw = await account.signTransaction({
47068
47326
  ...request,
47069
47327
  gas: bufferedV2Gas(request.gas)
@@ -47168,7 +47426,7 @@ import { randomBytes as nodeRandomBytes } from "node:crypto";
47168
47426
 
47169
47427
  // src/tasks/ballots.ts
47170
47428
  import { readdir as readdir3, readFile as readFile7 } from "node:fs/promises";
47171
- import { join as join6 } from "node:path";
47429
+ import { join as join7 } from "node:path";
47172
47430
  var address5 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u).transform((v) => v.toLowerCase());
47173
47431
  var hash6 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/u).transform((v) => v.toLowerCase());
47174
47432
  var TASK_V2_VOTE_OUTCOMES = ["worker", "poster", "split"];
@@ -47188,7 +47446,7 @@ var taskV2BallotSchema = external_exports.strictObject({
47188
47446
  createdAt: external_exports.iso.datetime()
47189
47447
  });
47190
47448
  function taskV2BallotDirectory(home, key2) {
47191
- return join6(
47449
+ return join7(
47192
47450
  home,
47193
47451
  "tasks",
47194
47452
  "ballots",
@@ -47198,7 +47456,7 @@ function taskV2BallotDirectory(home, key2) {
47198
47456
  );
47199
47457
  }
47200
47458
  function taskV2BallotPath(home, key2) {
47201
- return join6(taskV2BallotDirectory(home, key2), `${hash6.parse(key2.commitment)}.json`);
47459
+ return join7(taskV2BallotDirectory(home, key2), `${hash6.parse(key2.commitment)}.json`);
47202
47460
  }
47203
47461
  async function writeTaskV2Ballot(home, ballot) {
47204
47462
  const parsed = taskV2BallotSchema.parse(ballot);
@@ -47234,7 +47492,7 @@ async function listTaskV2Ballots(home, key2) {
47234
47492
  }
47235
47493
  const ballots = [];
47236
47494
  for (const name of names.filter((n) => /^0x[0-9a-f]{64}\.json$/u.test(n)).sort()) {
47237
- const ballot = await readBallotFile(join6(directory, name));
47495
+ const ballot = await readBallotFile(join7(directory, name));
47238
47496
  if (ballot && `${ballot.commitment}.json` === name) ballots.push(ballot);
47239
47497
  }
47240
47498
  return ballots.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -47301,13 +47559,16 @@ function createTaskV2Jury(options) {
47301
47559
  };
47302
47560
  async function voteCase(id, i2) {
47303
47561
  taskV2IndexSchema.parse(i2);
47304
- const deployment = await client.deployment();
47305
- if (!deployment.configured)
47306
- throw new TaskOperationError("v2_resolver_unavailable", "Hosted Tasks V2 is not configured.");
47562
+ const chainId = (await readTasksReadiness(client))?.chainId ?? (await options.pending.v2Target?.(id))?.chainId;
47563
+ if (chainId === void 0)
47564
+ throw new TaskOperationError(
47565
+ "v2_resolver_unavailable",
47566
+ "vAPI's Tasks status could not be read, so the chain of this dispute is unknown. Nothing was signed. Try again later."
47567
+ );
47307
47568
  const view = await client.getOrder(id);
47308
47569
  if (view.workOrder.id !== id)
47309
47570
  throw new TaskOperationError("invalid_response", "The order view belongs to another task.");
47310
- const target = await verifyV2Target(options, { chainId: deployment.chainId }, view, {
47571
+ const target = await verifyV2Target(options, { chainId }, view, {
47311
47572
  action: "open-jury",
47312
47573
  i: i2
47313
47574
  });
@@ -47718,7 +47979,9 @@ function createTasksChain(options) {
47718
47979
  });
47719
47980
  async function deployment() {
47720
47981
  const value = await client.deployment();
47721
- if (!value.configured || value.network !== `eip155:${value.chainId}`)
47982
+ if (!value.configured)
47983
+ throw new TasksValidationError(tasksUnavailableError(value.chainId).message);
47984
+ if (value.network !== `eip155:${value.chainId}`)
47722
47985
  throw new TasksValidationError("The Tasks chain deployment is unavailable.");
47723
47986
  if (!getTrustedTasksFactory(value.chainId, options.trustedFactories))
47724
47987
  throw new TasksChainError(
@@ -48673,7 +48936,7 @@ function createTasksRpcFor(config2, options = {}) {
48673
48936
 
48674
48937
  // src/tasks/pending-transactions.ts
48675
48938
  import { readFile as readFile8 } from "node:fs/promises";
48676
- import { join as join7 } from "node:path";
48939
+ import { join as join8 } from "node:path";
48677
48940
  var hex4 = external_exports.string().regex(/^0x(?:[0-9a-fA-F]{2})+$/).transform((v) => v);
48678
48941
  var hash8 = external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).transform((v) => v);
48679
48942
  var step = external_exports.union([
@@ -48738,7 +49001,8 @@ var stateSchema2 = external_exports.object({
48738
49001
  idempotencyKey: external_exports.uuid(),
48739
49002
  inputs: external_exports.unknown(),
48740
49003
  operationId: external_exports.uuid().optional(),
48741
- preparedV2: taskV2PreparedSchema.optional()
49004
+ preparedV2: taskV2PreparedSchema.optional(),
49005
+ signed: external_exports.boolean().optional()
48742
49006
  }).strict()
48743
49007
  ).default({})
48744
49008
  }).strict();
@@ -48762,7 +49026,7 @@ function validCheckpointStep(storedStep, response) {
48762
49026
  }[response.operation.kind];
48763
49027
  }
48764
49028
  function createPendingTransactions(home) {
48765
- const path = join7(home, "tasks", "pending.json");
49029
+ const path = join8(home, "tasks", "pending.json");
48766
49030
  const lockPath = `${path}.lock`;
48767
49031
  const read = async () => {
48768
49032
  try {
@@ -48849,7 +49113,7 @@ function createPendingTransactions(home) {
48849
49113
  },
48850
49114
  withStepLock(operationId, step2, fn) {
48851
49115
  return withFileLock(
48852
- join7(
49116
+ join8(
48853
49117
  home,
48854
49118
  "tasks",
48855
49119
  `step-${encodeURIComponent(operationId)}-${encodeURIComponent(step2)}.lock`
@@ -48861,13 +49125,13 @@ function createPendingTransactions(home) {
48861
49125
  external_exports.number().int().positive().parse(chainId);
48862
49126
  address7.parse(signer);
48863
49127
  return withFileLock(
48864
- join7(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
49128
+ join8(home, "tasks", `signer-${chainId}-${signer.toLowerCase()}.lock`),
48865
49129
  fn
48866
49130
  );
48867
49131
  },
48868
49132
  withFundingLock(milestoneId2, fn) {
48869
49133
  milestoneKey(milestoneId2);
48870
- return withFileLock(join7(home, "tasks", `fund-${milestoneId2}.lock`), fn);
49134
+ return withFileLock(join8(home, "tasks", `fund-${milestoneId2}.lock`), fn);
48871
49135
  },
48872
49136
  async nextNonce(chainId, signer) {
48873
49137
  external_exports.number().int().positive().parse(chainId);
@@ -48928,7 +49192,8 @@ function createPendingTransactions(home) {
48928
49192
  idempotencyKey: external_exports.uuid(),
48929
49193
  inputs: external_exports.unknown(),
48930
49194
  operationId: external_exports.uuid().optional(),
48931
- preparedV2: taskV2PreparedSchema.optional()
49195
+ preparedV2: taskV2PreparedSchema.optional(),
49196
+ signed: external_exports.boolean().optional()
48932
49197
  }).strict().parse(preparation);
48933
49198
  const existing = state.preparations[key2];
48934
49199
  if (existing && (existing.idempotencyKey !== parsed.idempotencyKey || canonicalJson(existing.inputs) !== canonicalJson(parsed.inputs)))
@@ -48970,6 +49235,14 @@ function createPendingTransactions(home) {
48970
49235
  }
48971
49236
  });
48972
49237
  },
49238
+ async markPreparationSigned(milestoneId2, verb) {
49239
+ await locked(async (state) => {
49240
+ const existing = state.preparations[preparationKey(milestoneId2, verb)];
49241
+ if (!existing || existing.signed) return;
49242
+ existing.signed = true;
49243
+ await save(state);
49244
+ });
49245
+ },
48973
49246
  async completePreparation(milestoneId2, verb) {
48974
49247
  await locked(async (state) => {
48975
49248
  const key2 = preparationKey(milestoneId2, verb);
@@ -49109,7 +49382,7 @@ function validateAmount(amountUsd) {
49109
49382
  // src/tasks/funding-attempts.ts
49110
49383
  import { createHash as createHash5 } from "node:crypto";
49111
49384
  import { readFile as readFile9, unlink as unlink5 } from "node:fs/promises";
49112
- import { dirname as dirname5, join as join8 } from "node:path";
49385
+ import { dirname as dirname5, join as join9 } from "node:path";
49113
49386
  var coordinates = external_exports.object({
49114
49387
  network: external_exports.string().regex(/^eip155:[1-9][0-9]*$/u),
49115
49388
  asset: external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/u),
@@ -49137,7 +49410,7 @@ var attemptSchema = external_exports.object({
49137
49410
  );
49138
49411
  async function withFundingAttempt(input2, operation) {
49139
49412
  const key2 = createHash5("sha256").update(`${input2.taskId}:${input2.milestoneId}`).digest("hex");
49140
- const path = join8(dirname5(input2.ledgerPath), "tasks", `funding-${key2}.json`);
49413
+ const path = join9(dirname5(input2.ledgerPath), "tasks", `funding-${key2}.json`);
49141
49414
  return withFileLock(
49142
49415
  `${path}.lock`,
49143
49416
  async () => {
@@ -49917,7 +50190,14 @@ async function postTask(context, input2) {
49917
50190
  "The Tasks deployment is unavailable, so the market network cannot be selected."
49918
50191
  );
49919
50192
  }
49920
- const feeBp = parseFeeBp(deployment);
50193
+ if (input2.fund)
50194
+ requireTasksAvailable("fund", deployment, "Nothing was posted or signed and no money moved.");
50195
+ const declared = input2.order;
50196
+ const shape = declared.shape ?? (input2.intake === "submissions" ? "bounty" : "task");
50197
+ const total = input2.amount * BigInt(shape === "bounty" ? declared.bounty?.winners ?? input2.maxAwards ?? 1 : 1);
50198
+ const limits = typeof deployment.chainId === "number" ? await context.limitsV2?.(deployment.chainId, shape).catch(() => void 0) : void 0;
50199
+ if (limits) assertWithinTaskV2Limit(total, limits, "Nothing was posted and no money moved.");
50200
+ const feeBp = limits?.feeBp ?? parseFeeBp(deployment);
49921
50201
  const feeUnavailable = feeBp === null;
49922
50202
  if (feeUnavailable) input2.onFeeUnavailable?.();
49923
50203
  const money = taskMoney(input2.amount, feeBp);
@@ -49996,7 +50276,11 @@ async function proposeTask(context, input2) {
49996
50276
  context
49997
50277
  );
49998
50278
  if (!deployment.configured)
49999
- throw new TaskOperationError("not_available", "Task escrow deployment is unavailable.");
50279
+ throw tasksUnavailableError(
50280
+ deployment.chainId,
50281
+ "No proposal was signed or sent.",
50282
+ "not_available"
50283
+ );
50000
50284
  const account = await input2.unlock();
50001
50285
  const terms = {
50002
50286
  title: workOrder.title,
@@ -50077,7 +50361,11 @@ async function submitTask(context, input2) {
50077
50361
  context
50078
50362
  );
50079
50363
  if (!deployment.configured)
50080
- throw new TaskOperationError("not_available", "Task escrow deployment is unavailable.");
50364
+ throw tasksUnavailableError(
50365
+ deployment.chainId,
50366
+ "No entry was signed or sent.",
50367
+ "not_available"
50368
+ );
50081
50369
  if (task.amount === null) {
50082
50370
  throw new TaskInputError("Task amount is unavailable.");
50083
50371
  }
@@ -50577,6 +50865,9 @@ async function resolveUnmatchedTaskOperation(context, input2) {
50577
50865
  }
50578
50866
 
50579
50867
  // src/tasks/post-options.ts
50868
+ var TASK_POST_DEADLINE_LEAD_MS = 3 * 36e5;
50869
+ var TASK_POST_DEADLINE_MARGIN_MS = 6e4;
50870
+ 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.";
50580
50871
  function positive(text, name) {
50581
50872
  if (text === void 0) throw new TaskInputError(`${name} is required.`);
50582
50873
  try {
@@ -50674,17 +50965,16 @@ function prepareTaskPost(input2, now) {
50674
50965
  "An open pool requires --open-check allowlist|invite (configure participants separately)."
50675
50966
  );
50676
50967
  } else {
50677
- if (!input2.milestones?.length && duration3 < 36e5)
50678
- throw new TaskInputError(
50679
- "Task deadlines must leave at least one hour for work before award."
50680
- );
50968
+ 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;
50969
+ if (!input2.milestones?.length && duration3 < lead)
50970
+ throw new TaskInputError(`Task deadlines ${TASK_DEADLINE_TOO_SOON}`);
50681
50971
  const sum = input2.milestones?.reduce((total, item) => total + BigInt(item.amountBaseUnits), 0n);
50682
50972
  amount4 = input2.amountUsd === void 0 && sum !== void 0 ? sum : positive(input2.amountUsd, "--amount");
50683
50973
  if (sum !== void 0 && sum !== amount4)
50684
50974
  throw new TaskInputError("Milestone amounts must sum to --amount.");
50685
- if (input2.milestones?.some((item) => Date.parse(item.deadlineAt) - now.getTime() < 36e5))
50975
+ if (input2.milestones?.some((item) => Date.parse(item.deadlineAt) - now.getTime() < lead))
50686
50976
  throw new TaskInputError(
50687
- "Milestone deadlines must leave at least one hour for work; creation and funding also check the verified MIN_WORK_TIME against the chain clock."
50977
+ `Milestone deadlines ${TASK_DEADLINE_TOO_SOON} Creation and funding also check the contract's MIN_WORK_TIME against the chain clock.`
50688
50978
  );
50689
50979
  }
50690
50980
  if (input2.amountUsd !== void 0 && positive(input2.amountUsd, "--amount") !== amount4)
@@ -57350,10 +57640,13 @@ export {
57350
57640
  TASKS_CLIENT_VERBS,
57351
57641
  TASKS_V2_EVENT_ABIS,
57352
57642
  TASK_LIMITS,
57643
+ TASK_POST_DEADLINE_LEAD_MS,
57644
+ TASK_POST_DEADLINE_MARGIN_MS,
57353
57645
  TASK_V2_CASE_STATES,
57354
57646
  TASK_V2_GAS_BUFFER_PERCENT,
57355
57647
  TASK_V2_JURY_RULES,
57356
57648
  TASK_V2_JURY_STEPS,
57649
+ TASK_V2_NEW_WORK_ACTIONS,
57357
57650
  TASK_V2_NO_VERDICT_SUMMARY,
57358
57651
  TASK_V2_REDACTED,
57359
57652
  TASK_V2_REDACTED_CALLDATA,
@@ -57372,6 +57665,7 @@ export {
57372
57665
  TasksScopeCreationError,
57373
57666
  V2_RESOLVER_ACTIONS,
57374
57667
  acceptedV2WorkerBond,
57668
+ assertWithinTaskV2Limit,
57375
57669
  autoReleaseDecision,
57376
57670
  awardTask,
57377
57671
  boardNumbersSchema,
@@ -57462,7 +57756,9 @@ export {
57462
57756
  publicTaskV2Recovery,
57463
57757
  readTaskFile,
57464
57758
  readTaskV2Ballot,
57759
+ readTaskV2Limits,
57465
57760
  readTaskV2ReviewerStatus,
57761
+ readTasksReadiness,
57466
57762
  recoverTaskV2,
57467
57763
  redactTaskV2Ballots,
57468
57764
  refundTask,
@@ -57470,6 +57766,7 @@ export {
57470
57766
  releaseTask,
57471
57767
  releaseTaskOperation,
57472
57768
  requireTaskMethod,
57769
+ requireTasksAvailable,
57473
57770
  resolveTaskBearer,
57474
57771
  resolveUnmatchedTask,
57475
57772
  resolveUnmatchedTaskOperation,
@@ -57493,6 +57790,7 @@ export {
57493
57790
  taskLifecycleSchema,
57494
57791
  taskMoney,
57495
57792
  taskMoneySnapshot,
57793
+ taskNetworkName,
57496
57794
  taskPolicyAtomic,
57497
57795
  taskPolicyForWallet,
57498
57796
  taskPostResponseSchema,
@@ -57531,6 +57829,7 @@ export {
57531
57829
  taskV2VoteHostedError,
57532
57830
  taskV2VoteInputSchema,
57533
57831
  taskViewFields,
57832
+ tasksUnavailableError,
57534
57833
  threadTask,
57535
57834
  validTaskBrief,
57536
57835
  verifiedV2Resolver,