402mob-runtime 0.2.2 → 0.3.1

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.
@@ -40247,7 +40247,7 @@ var require_express2 = __commonJS({
40247
40247
  }
40248
40248
  });
40249
40249
 
40250
- // dist/runtime/cli.js
40250
+ // src/runtime/cli.ts
40251
40251
  import { randomUUID as randomUUID5 } from "node:crypto";
40252
40252
  import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2 } from "node:fs";
40253
40253
  import { dirname, join as join3, resolve as resolve2 } from "node:path";
@@ -59970,13 +59970,13 @@ function date4(params) {
59970
59970
  return _coercedDate(ZodDate, params);
59971
59971
  }
59972
59972
 
59973
- // dist/runtime/store.js
59973
+ // src/runtime/store.ts
59974
59974
  import { DatabaseSync } from "node:sqlite";
59975
59975
  import { mkdirSync, lstatSync, openSync, closeSync, writeFileSync, readFileSync, fsyncSync, existsSync, renameSync } from "node:fs";
59976
59976
  import { resolve, join } from "node:path";
59977
59977
  import { createHash as createHash2, randomUUID } from "node:crypto";
59978
59978
 
59979
- // dist/crypto.js
59979
+ // src/crypto.ts
59980
59980
  import { createCipheriv, createDecipheriv, createHash, randomBytes, timingSafeEqual } from "node:crypto";
59981
59981
  function sha256(value) {
59982
59982
  return createHash("sha256").update(value).digest("hex");
@@ -59987,16 +59987,14 @@ function quoteSignatureText(value) {
59987
59987
  function canonical(value) {
59988
59988
  if (value === null || typeof value !== "object") {
59989
59989
  const encoded = JSON.stringify(value);
59990
- if (encoded === void 0)
59991
- throw new Error("Value is not JSON");
59990
+ if (encoded === void 0) throw new Error("Value is not JSON");
59992
59991
  return encoded;
59993
59992
  }
59994
- if (Array.isArray(value))
59995
- return `[${value.map(canonical).join(",")}]`;
59993
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
59996
59994
  return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
59997
59995
  }
59998
59996
 
59999
- // dist/runtime/common.js
59997
+ // src/runtime/common.ts
60000
59998
  var uuid3 = external_exports.string().uuid();
60001
59999
  var address = external_exports.string().regex(/^0x(?!0{40}$)[0-9a-fA-F]{40}$/);
60002
60000
  var atomic = external_exports.string().regex(/^[1-9][0-9]{0,11}$/);
@@ -60005,8 +60003,7 @@ var date5 = external_exports.string().datetime();
60005
60003
  var signature = external_exports.string().regex(/^0x[0-9a-fA-F]{130}$/);
60006
60004
  var amount = external_exports.string().regex(/^(?!0(?:\.0{1,6})?$)(0|[1-9][0-9]{0,5})(\.[0-9]{1,6})?$/);
60007
60005
  function toAtomic(value) {
60008
- if (!/^(0|[1-9][0-9]{0,5})(\.[0-9]{1,6})?$/.test(value))
60009
- throw new RuntimeFault("invalid_amount");
60006
+ if (!/^(0|[1-9][0-9]{0,5})(\.[0-9]{1,6})?$/.test(value)) throw new RuntimeFault("invalid_amount");
60010
60007
  const [whole = "0", fraction = ""] = value.split(".");
60011
60008
  return BigInt(whole) * 1000000n + BigInt(fraction.padEnd(6, "0"));
60012
60009
  }
@@ -60018,24 +60015,23 @@ function origin(value) {
60018
60015
  return u.origin;
60019
60016
  }
60020
60017
  var RuntimeFault = class extends Error {
60021
- code;
60022
- retryable;
60023
60018
  constructor(code, retryable = false) {
60024
60019
  super(code);
60025
60020
  this.code = code;
60026
60021
  this.retryable = retryable;
60027
60022
  this.name = "RuntimeFault";
60028
60023
  }
60024
+ code;
60025
+ retryable;
60029
60026
  };
60030
60027
  function requireThat(value, code) {
60031
- if (!value)
60032
- throw new RuntimeFault(code);
60028
+ if (!value) throw new RuntimeFault(code);
60033
60029
  }
60034
60030
  function faultCode(error62) {
60035
60031
  return error62 instanceof RuntimeFault ? error62.code : error62 instanceof external_exports.ZodError ? "schema_mismatch" : "adapter_failure";
60036
60032
  }
60037
60033
 
60038
- // dist/runtime/store.js
60034
+ // src/runtime/store.ts
60039
60035
  function privateFile(path) {
60040
60036
  const s = lstatSync(path);
60041
60037
  requireThat(s.isFile() && !s.isSymbolicLink() && s.uid === process.getuid?.() && (s.mode & 63) === 0, "unsafe_private_file");
@@ -60074,8 +60070,7 @@ var RuntimeStore = class {
60074
60070
  kind;
60075
60071
  constructor(directory, create2) {
60076
60072
  this.directory = resolve(directory);
60077
- if (create2)
60078
- mkdirSync(this.directory, { recursive: true, mode: 448 });
60073
+ if (create2) mkdirSync(this.directory, { recursive: true, mode: 448 });
60079
60074
  const info = lstatSync(this.directory);
60080
60075
  requireThat(info.isDirectory() && !info.isSymbolicLink() && info.uid === process.getuid?.() && (info.mode & 63) === 0, "unsafe_runtime_directory");
60081
60076
  const marker = join(this.directory, "identity.json"), file2 = join(this.directory, "runtime.sqlite");
@@ -60086,9 +60081,7 @@ var RuntimeStore = class {
60086
60081
  }
60087
60082
  const identity = bindingSchema.parse(readPrivateJson(marker));
60088
60083
  privateFile(file2);
60089
- for (const suffix of ["-wal", "-shm", "-journal"])
60090
- if (existsSync(file2 + suffix))
60091
- privateFile(file2 + suffix);
60084
+ for (const suffix of ["-wal", "-shm", "-journal"]) if (existsSync(file2 + suffix)) privateFile(file2 + suffix);
60092
60085
  this.id = identity.id;
60093
60086
  this.kind = identity.kind;
60094
60087
  this.db = new DatabaseSync(file2, { open: true });
@@ -60129,8 +60122,7 @@ var RuntimeStore = class {
60129
60122
  }
60130
60123
  get(key) {
60131
60124
  const row = this.db.prepare("SELECT value,digest FROM metadata WHERE key=?").get(key);
60132
- if (!row)
60133
- return void 0;
60125
+ if (!row) return void 0;
60134
60126
  const r = recordSchema.parse(row);
60135
60127
  requireThat(this.hash(r.value) === r.digest, "runtime_record_corrupt");
60136
60128
  return JSON.parse(r.value);
@@ -60144,13 +60136,12 @@ var RuntimeStore = class {
60144
60136
  }
60145
60137
  require(key) {
60146
60138
  const value = this.get(key);
60147
- if (value === void 0)
60148
- throw new RuntimeFault("runtime_record_missing");
60139
+ if (value === void 0) throw new RuntimeFault("runtime_record_missing");
60149
60140
  return value;
60150
60141
  }
60151
60142
  };
60152
60143
 
60153
- // dist/runtime/wallet.js
60144
+ // src/runtime/wallet.ts
60154
60145
  import { createHmac, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "node:crypto";
60155
60146
 
60156
60147
  // node_modules/viem/_esm/utils/signature/serializeSignature.js
@@ -63453,7 +63444,7 @@ var basePreconf = /* @__PURE__ */ defineChain({
63453
63444
  }
63454
63445
  });
63455
63446
 
63456
- // dist/payments.js
63447
+ // src/payments.ts
63457
63448
  var NETWORK = "eip155:8453";
63458
63449
  var USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
63459
63450
  var address2 = external_exports.string().regex(/^0x[0-9a-fA-F]{40}$/);
@@ -63517,10 +63508,10 @@ var enrollmentProofAbi = parseAbi([
63517
63508
  ]);
63518
63509
  var directTransferCallAbi = parseAbi(["function transfer(address to,uint256 value) returns (bool)"]);
63519
63510
 
63520
- // dist/runtime/wallet.js
63511
+ // src/runtime/wallet.ts
63521
63512
  import { join as join2 } from "node:path";
63522
63513
 
63523
- // dist/runtime/text-statistics.js
63514
+ // src/runtime/text-statistics.ts
63524
63515
  var TEXT_CAPABILITY = "text-statistics-v1";
63525
63516
  var TEXT_DELIVERABLE = "text-statistics-v1: SHA-256, UTF-8 bytes, Unicode code points, whitespace-delimited words and LF lines; no normalization";
63526
63517
  var textInput = external_exports.object({ text: external_exports.string().refine((v2) => Buffer.byteLength(v2, "utf8") <= 16e3 && !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(v2)) }).strict().refine((v2) => Buffer.byteLength(JSON.stringify(v2), "utf8") <= 3e4);
@@ -63551,14 +63542,14 @@ function evaluateTextStatistics(input2, bytes) {
63551
63542
  }
63552
63543
  }
63553
63544
 
63554
- // dist/runtime/wallet.js
63545
+ // src/runtime/wallet.ts
63555
63546
  var delegationPolicy = external_exports.object({
63556
63547
  name: external_exports.string().min(1).max(80),
63557
- maxTotalUSDC: amount.describe("Total USDC allocated to this delegation."),
63548
+ maxTotalUSDC: amount.optional().describe("Optional lifetime spending limit. Omit to use available wallet funds, including later deposits, subject to other configured limits."),
63558
63549
  merchantId: uuid3.optional().describe("Omit to let the agent choose a merchant for each task."),
63559
63550
  payee: address.optional().describe("Omit to permit any recipient of a supported purchase."),
63560
63551
  capability: external_exports.enum([TEXT_CAPABILITY, "prepared-artifact-v1"]).optional().describe("Omit to allow any installed runtime capability."),
63561
- maxPerPaymentUSDC: amount.optional().describe("Omit to allow a payment up to the remaining allocation."),
63552
+ maxPerPaymentUSDC: amount.optional().describe("Optional per-payment spending limit."),
63562
63553
  expiresAt: date5.optional().describe("Omit for no delegation expiry. Owner revocation still applies.")
63563
63554
  }).strict();
63564
63555
  var walletStatus = external_exports.object({
@@ -63571,10 +63562,10 @@ var walletStatus = external_exports.object({
63571
63562
  revoked: external_exports.boolean(),
63572
63563
  reservedAtomic: external_exports.string().regex(/^\d+$/),
63573
63564
  spentAtomic: external_exports.string().regex(/^\d+$/),
63574
- remainingAtomic: external_exports.string().regex(/^\d+$/).describe("Delegation allocation minus spent and reserved amounts; not a token balance. Owner-wide status uses the shared ceiling, or 0 when that ceiling is absent."),
63565
+ remainingAtomic: external_exports.string().regex(/^\d+$/).nullable().describe("Remaining delegation limit, or null when no delegation limit exists. Owner-wide status uses the shared ceiling. Not a token balance."),
63575
63566
  walletLimitUSDC: amount.nullable().describe("Optional lifetime shared ceiling; null means no extra wallet ceiling."),
63576
63567
  walletRemainingAtomic: external_exports.string().regex(/^\d+$/).nullable().describe("Shared ceiling minus spent and reserved amounts; null when no ceiling is configured."),
63577
- policyAvailableAtomic: external_exports.string().regex(/^\d+$/).describe("Delegation capacity after shared ceiling and per-payment cap; zero if expired or revoked. Does not measure funds."),
63568
+ policyAvailableAtomic: external_exports.string().regex(/^\d+$/).nullable().describe("Capacity after configured spending limits; null means no policy cap, zero if expired or revoked. Does not measure funds."),
63578
63569
  expired: external_exports.boolean(),
63579
63570
  funding: external_exports.string()
63580
63571
  }).strict();
@@ -63585,7 +63576,7 @@ var spendingStatus = walletStatus.extend({
63585
63576
  spendableAtomic: external_exports.string().regex(/^\d+$/).nullable().describe("Conservative estimate: policy capacity and observed balance minus all unresolved wallet reservations. Null means funds could not be observed; this is not a reservation.")
63586
63577
  }).strict();
63587
63578
  var walletLimitUpdate = external_exports.object({ requestId: uuid3, expectedLimitUSDC: amount.nullable(), maxTotalUSDC: amount.nullable() }).strict();
63588
- var allocationUpdate = external_exports.object({ requestId: uuid3, expectedMaxTotalUSDC: amount, maxTotalUSDC: amount }).strict();
63579
+ var allocationUpdate = external_exports.object({ requestId: uuid3, expectedMaxTotalUSDC: amount.nullable(), maxTotalUSDC: amount.nullable().describe("Null removes the agent limit. Existing spending and reservations remain recorded.") }).strict();
63589
63580
  var walletConfig = external_exports.object({ origin: external_exports.string(), maxTotalUSDC: amount.nullable(), privateKey: external_exports.string().regex(/^0x[0-9a-f]{64}$/i), address }).strict();
63590
63581
  var reservationSchema = external_exports.object({
63591
63582
  job: uuid3,
@@ -63618,15 +63609,6 @@ var reservationSchema = external_exports.object({
63618
63609
  transaction: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).nullable()
63619
63610
  }).strict();
63620
63611
  var DelegatedWallet = class {
63621
- store;
63622
- chain;
63623
- clock;
63624
- get config() {
63625
- return walletConfig.parse(this.store.require("wallet"));
63626
- }
63627
- account;
63628
- origin;
63629
- address;
63630
63612
  constructor(store, chain, clock = Date.now) {
63631
63613
  this.store = store;
63632
63614
  this.chain = chain;
@@ -63638,6 +63620,15 @@ var DelegatedWallet = class {
63638
63620
  requireThat(this.address === this.config.address, "wallet_identity_mismatch");
63639
63621
  store.transaction(() => this.assertAnchor());
63640
63622
  }
63623
+ store;
63624
+ chain;
63625
+ clock;
63626
+ get config() {
63627
+ return walletConfig.parse(this.store.require("wallet"));
63628
+ }
63629
+ account;
63630
+ origin;
63631
+ address;
63641
63632
  static initialize(store, settings) {
63642
63633
  requireThat(store.kind === "wallet" && !store.get("wallet"), "wallet_already_exists");
63643
63634
  const privateKey = generatePrivateKey();
@@ -63679,7 +63670,7 @@ var DelegatedWallet = class {
63679
63670
  requireThat(requestId !== void 0 && saved.token_hash === sha256(token) && original === canonical(policy), "delegation_request_conflict");
63680
63671
  requireThat(saved.revoked_at === null, "delegation_revoked");
63681
63672
  } else {
63682
- requireThat((!policy.maxPerPaymentUSDC || toAtomic(policy.maxPerPaymentUSDC) <= toAtomic(policy.maxTotalUSDC)) && (!this.config.maxTotalUSDC || toAtomic(policy.maxTotalUSDC) <= toAtomic(this.config.maxTotalUSDC)), "delegation_limit_invalid");
63673
+ requireThat(!policy.maxTotalUSDC || (!policy.maxPerPaymentUSDC || toAtomic(policy.maxPerPaymentUSDC) <= toAtomic(policy.maxTotalUSDC)) && (!this.config.maxTotalUSDC || toAtomic(policy.maxTotalUSDC) <= toAtomic(this.config.maxTotalUSDC)), "delegation_limit_invalid");
63683
63674
  requireThat(!policy.expiresAt || Date.parse(policy.expiresAt) > this.clock(), "delegation_expired");
63684
63675
  requireThat(Number(this.store.db.prepare("SELECT COUNT(*) n FROM delegations").get()?.n) < 1e3, "delegation_capacity");
63685
63676
  this.store.db.prepare("INSERT INTO delegations VALUES(?,?,?,NULL)").run(id, sha256(token), canonical(policy));
@@ -63721,11 +63712,12 @@ var DelegatedWallet = class {
63721
63712
  const change = allocationUpdate.parse(input2);
63722
63713
  this.updateBudget(change.requestId, "delegation:" + id, change, () => {
63723
63714
  const policy = this.assertActive(id);
63724
- requireThat(policy.maxTotalUSDC === change.expectedMaxTotalUSDC, "budget_revision_conflict");
63725
- requireThat(toAtomic(change.maxTotalUSDC) >= toAtomic(policy.maxTotalUSDC) && (!this.config.maxTotalUSDC || toAtomic(change.maxTotalUSDC) <= toAtomic(this.config.maxTotalUSDC)), "delegation_limit_invalid");
63726
- if (!this.store.get("grant-original:" + id))
63727
- this.store.put("grant-original:" + id, canonical(policy));
63728
- this.store.db.prepare("UPDATE delegations SET policy=? WHERE id=?").run(canonical({ ...policy, maxTotalUSDC: change.maxTotalUSDC }), id);
63715
+ requireThat((policy.maxTotalUSDC ?? null) === change.expectedMaxTotalUSDC, "budget_revision_conflict");
63716
+ const own2 = this.totals(id);
63717
+ requireThat(change.maxTotalUSDC === null || (!policy.maxTotalUSDC || toAtomic(change.maxTotalUSDC) >= toAtomic(policy.maxTotalUSDC)) && toAtomic(change.maxTotalUSDC) >= own2.held + own2.spent && (!policy.maxPerPaymentUSDC || toAtomic(change.maxTotalUSDC) >= toAtomic(policy.maxPerPaymentUSDC)) && (!this.config.maxTotalUSDC || toAtomic(change.maxTotalUSDC) <= toAtomic(this.config.maxTotalUSDC)), "delegation_limit_invalid");
63718
+ if (!this.store.get("grant-original:" + id)) this.store.put("grant-original:" + id, canonical(policy));
63719
+ const { maxTotalUSDC: _previous, ...rest } = policy;
63720
+ this.store.db.prepare("UPDATE delegations SET policy=? WHERE id=?").run(canonical({ ...rest, ...change.maxTotalUSDC === null ? {} : { maxTotalUSDC: change.maxTotalUSDC } }), id);
63729
63721
  });
63730
63722
  return this.status(id);
63731
63723
  }
@@ -63745,8 +63737,7 @@ var DelegatedWallet = class {
63745
63737
  return this.config.maxTotalUSDC;
63746
63738
  }
63747
63739
  authenticate(token) {
63748
- if (!/^mobrt_[0-9a-f]{64}$/.test(token))
63749
- return void 0;
63740
+ if (!/^mobrt_[0-9a-f]{64}$/.test(token)) return void 0;
63750
63741
  const row = this.store.db.prepare("SELECT id FROM delegations WHERE token_hash=?").get(sha256(token));
63751
63742
  return row ? String(row.id) : void 0;
63752
63743
  }
@@ -63769,12 +63760,10 @@ var DelegatedWallet = class {
63769
63760
  }
63770
63761
  reservation(job) {
63771
63762
  const r = this.store.db.prepare("SELECT data FROM reservations WHERE job=?").get(job);
63772
- if (!r)
63773
- return void 0;
63763
+ if (!r) return void 0;
63774
63764
  const saved = reservationSchema.parse(JSON.parse(String(r.data)));
63775
63765
  requireThat(saved.job === job && saved.authorization.from.toLowerCase() === this.address.toLowerCase() && saved.authorization.value === saved.amount, "reservation_corrupt");
63776
- if (saved.payment)
63777
- requireThat(canonical(saved.payment.payload.authorization) === canonical(saved.authorization) && saved.payment.resource.url === saved.resource && saved.payment.accepted.amount === saved.amount && saved.payment.accepted.payTo.toLowerCase() === saved.authorization.to.toLowerCase() && saved.payment.accepted.asset.toLowerCase() === USDC.toLowerCase(), "reservation_corrupt");
63766
+ if (saved.payment) requireThat(canonical(saved.payment.payload.authorization) === canonical(saved.authorization) && saved.payment.resource.url === saved.resource && saved.payment.accepted.amount === saved.amount && saved.payment.accepted.payTo.toLowerCase() === saved.authorization.to.toLowerCase() && saved.payment.accepted.asset.toLowerCase() === USDC.toLowerCase(), "reservation_corrupt");
63778
63767
  return saved;
63779
63768
  }
63780
63769
  save(r) {
@@ -63785,26 +63774,21 @@ var DelegatedWallet = class {
63785
63774
  const rows = delegation ? this.store.db.prepare("SELECT data FROM reservations WHERE delegation=?").all(delegation) : this.store.db.prepare("SELECT data FROM reservations").all();
63786
63775
  for (const row of rows) {
63787
63776
  const r = reservationSchema.parse(JSON.parse(String(row.data)));
63788
- if (r.status === "settled")
63789
- spent += BigInt(r.amount);
63790
- else
63791
- held += BigInt(r.amount);
63777
+ if (r.status === "settled") spent += BigInt(r.amount);
63778
+ else held += BigInt(r.amount);
63792
63779
  }
63793
63780
  return { held, spent };
63794
63781
  }
63795
63782
  status(id) {
63796
63783
  const sums = this.totals(id), grant = id ? this.policy(id) : void 0;
63797
- const total = this.totals(), limitValue = grant?.policy.maxTotalUSDC ?? this.config.maxTotalUSDC;
63798
- const remaining = limitValue ? toAtomic(limitValue) - sums.held - sums.spent : 0n;
63784
+ const total = this.totals(), limitValue = grant ? grant.policy.maxTotalUSDC : this.config.maxTotalUSDC;
63785
+ const remaining = limitValue ? toAtomic(limitValue) - sums.held - sums.spent : null;
63799
63786
  const walletRemaining = this.config.maxTotalUSDC ? toAtomic(this.config.maxTotalUSDC) - total.held - total.spent : null;
63800
63787
  const expired = Boolean(grant?.policy.expiresAt && Date.parse(grant.policy.expiresAt) <= this.clock());
63801
63788
  let available = remaining;
63802
- if (walletRemaining !== null && walletRemaining < available)
63803
- available = walletRemaining;
63804
- if (grant?.policy.maxPerPaymentUSDC && toAtomic(grant.policy.maxPerPaymentUSDC) < available)
63805
- available = toAtomic(grant.policy.maxPerPaymentUSDC);
63806
- if (grant?.revoked || expired)
63807
- available = 0n;
63789
+ if (walletRemaining !== null && (available === null || walletRemaining < available)) available = walletRemaining;
63790
+ if (grant?.policy.maxPerPaymentUSDC && (available === null || toAtomic(grant.policy.maxPerPaymentUSDC) < available)) available = toAtomic(grant.policy.maxPerPaymentUSDC);
63791
+ if (grant?.revoked || expired) available = 0n;
63808
63792
  return walletStatus.parse({
63809
63793
  address: this.address,
63810
63794
  network: NETWORK,
@@ -63815,12 +63799,12 @@ var DelegatedWallet = class {
63815
63799
  revoked: grant?.revoked ?? false,
63816
63800
  reservedAtomic: String(sums.held),
63817
63801
  spentAtomic: String(sums.spent),
63818
- remainingAtomic: String(remaining),
63802
+ remainingAtomic: remaining === null ? null : String(remaining),
63819
63803
  walletLimitUSDC: this.config.maxTotalUSDC,
63820
63804
  walletRemainingAtomic: walletRemaining === null ? null : String(walletRemaining),
63821
- policyAvailableAtomic: String(available),
63805
+ policyAvailableAtomic: available === null ? null : String(available),
63822
63806
  expired,
63823
- funding: "remainingAtomic is delegation allowance (zero for an uncapped owner view), not balance. Read spendableAtomic for a conservative new-payment estimate. Deposits do not change allocations or optional wallet limits."
63807
+ funding: "Null remainingAtomic or policyAvailableAtomic means no corresponding policy limit. Read spendableAtomic for available funds after reservations and configured limits. Uncapped agents can use later deposits. Deposits do not increase configured lifetime limits."
63824
63808
  });
63825
63809
  }
63826
63810
  async spendingStatus(id) {
@@ -63832,7 +63816,7 @@ var DelegatedWallet = class {
63832
63816
  return spendingStatus.parse({ ...this.status(id), balanceAtomic: null, balanceObservedAt: null, balanceError: "chain_unavailable", spendableAtomic: null });
63833
63817
  }
63834
63818
  const status = this.status(id), held = this.totals().held, free = balance > held ? balance - held : 0n;
63835
- const available = BigInt(status.policyAvailableAtomic);
63819
+ const available = status.policyAvailableAtomic === null ? free : BigInt(status.policyAvailableAtomic);
63836
63820
  return spendingStatus.parse({ ...status, balanceAtomic: String(balance), balanceObservedAt: new Date(this.clock()).toISOString(), balanceError: null, spendableAtomic: String(free < available ? free : available) });
63837
63821
  }
63838
63822
  /** Trusted profiles validate the complete purpose-bound message before calling this method. */
@@ -63849,8 +63833,7 @@ var DelegatedWallet = class {
63849
63833
  let previous = this.reservation(job);
63850
63834
  if (previous) {
63851
63835
  requireThat(previous.delegation === delegation && previous.termsHash === termsHash && previous.resource === this.origin + path && previous.amount === req.amount && previous.authorization.to.toLowerCase() === req.payTo.toLowerCase() && req.asset.toLowerCase() === USDC.toLowerCase(), "reservation_terms_changed");
63852
- if (previous.payment)
63853
- return previous.payment;
63836
+ if (previous.payment) return previous.payment;
63854
63837
  }
63855
63838
  this.assertActive(delegation);
63856
63839
  const balance = await this.chain.balance(this.address);
@@ -63858,13 +63841,11 @@ var DelegatedWallet = class {
63858
63841
  const p = this.assertActive(delegation), total = this.totals(), own2 = this.totals(delegation);
63859
63842
  requireThat((!p.payee || req.payTo.toLowerCase() === p.payee.toLowerCase()) && req.asset.toLowerCase() === USDC.toLowerCase() && (!p.maxPerPaymentUSDC || BigInt(req.amount) <= toAtomic(p.maxPerPaymentUSDC)), "payment_outside_delegation");
63860
63843
  previous = this.reservation(job);
63861
- if (previous)
63862
- requireThat(previous.delegation === delegation && previous.termsHash === termsHash && previous.resource === this.origin + path && previous.amount === req.amount && previous.authorization.to.toLowerCase() === req.payTo.toLowerCase(), "reservation_terms_changed");
63844
+ if (previous) requireThat(previous.delegation === delegation && previous.termsHash === termsHash && previous.resource === this.origin + path && previous.amount === req.amount && previous.authorization.to.toLowerCase() === req.payTo.toLowerCase(), "reservation_terms_changed");
63863
63845
  const add = previous ? 0n : BigInt(req.amount);
63864
- requireThat(own2.held + own2.spent + add <= toAtomic(p.maxTotalUSDC) && (!this.config.maxTotalUSDC || total.held + total.spent + add <= toAtomic(this.config.maxTotalUSDC)), "delegation_budget_exhausted");
63846
+ requireThat((!p.maxTotalUSDC || own2.held + own2.spent + add <= toAtomic(p.maxTotalUSDC)) && (!this.config.maxTotalUSDC || total.held + total.spent + add <= toAtomic(this.config.maxTotalUSDC)), "delegation_budget_exhausted");
63865
63847
  requireThat(balance >= total.held + add, "wallet_balance_insufficient");
63866
- if (previous)
63867
- return previous;
63848
+ if (previous) return previous;
63868
63849
  const now = Math.floor(this.clock() / 1e3);
63869
63850
  const saved = {
63870
63851
  job,
@@ -63894,8 +63875,7 @@ var DelegatedWallet = class {
63894
63875
  this.assertActive(delegation);
63895
63876
  const current = this.reservation(job);
63896
63877
  requireThat(canonical(current.authorization) === canonical(a), "authorization_changed");
63897
- if (!current.payment)
63898
- this.save({ ...current, status: "signed", payment });
63878
+ if (!current.payment) this.save({ ...current, status: "signed", payment });
63899
63879
  });
63900
63880
  return this.reservation(job).payment;
63901
63881
  }
@@ -63915,7 +63895,7 @@ var DelegatedWallet = class {
63915
63895
  }
63916
63896
  };
63917
63897
 
63918
- // dist/runtime/chain.js
63898
+ // src/runtime/chain.ts
63919
63899
  var abi2 = parseAbi(["function balanceOf(address) view returns (uint256)", "event Transfer(address indexed from,address indexed to,uint256 value)", "event AuthorizationUsed(address indexed authorizer,bytes32 indexed nonce)"]);
63920
63900
  var BaseUsdcReader = class {
63921
63901
  client;
@@ -63929,8 +63909,7 @@ var BaseUsdcReader = class {
63929
63909
  requireThat(await this.client.getChainId() === 8453, "wrong_rpc_chain");
63930
63910
  return await this.client.readContract({ address: USDC, abi: abi2, functionName: "balanceOf", args: [wallet2] });
63931
63911
  } catch (e) {
63932
- if (e instanceof RuntimeFault)
63933
- throw e;
63912
+ if (e instanceof RuntimeFault) throw e;
63934
63913
  throw new RuntimeFault("chain_unavailable", true);
63935
63914
  }
63936
63915
  }
@@ -63940,11 +63919,9 @@ var BaseUsdcReader = class {
63940
63919
  const r = await this.client.getTransactionReceipt({ hash: proof2.transaction });
63941
63920
  requireThat(r.status === "success", "transaction_reverted");
63942
63921
  const tip = await this.client.getBlockNumber();
63943
- if (tip < r.blockNumber + 2n)
63944
- throw new RuntimeFault("chain_confirming", true);
63922
+ if (tip < r.blockNumber + 2n) throw new RuntimeFault("chain_confirming", true);
63945
63923
  const matches = r.logs.filter((log) => {
63946
- if (log.address.toLowerCase() !== USDC.toLowerCase())
63947
- return false;
63924
+ if (log.address.toLowerCase() !== USDC.toLowerCase()) return false;
63948
63925
  try {
63949
63926
  const e = decodeEventLog({ abi: abi2, data: log.data, topics: log.topics });
63950
63927
  return e.eventName === "Transfer" && e.args.from.toLowerCase() === proof2.from.toLowerCase() && e.args.to.toLowerCase() === proof2.to.toLowerCase() && e.args.value === BigInt(proof2.amount);
@@ -63955,8 +63932,7 @@ var BaseUsdcReader = class {
63955
63932
  requireThat(matches.length === 1, "transfer_mismatch");
63956
63933
  if (proof2.nonce) {
63957
63934
  const used = r.logs.some((log) => {
63958
- if (log.address.toLowerCase() !== USDC.toLowerCase())
63959
- return false;
63935
+ if (log.address.toLowerCase() !== USDC.toLowerCase()) return false;
63960
63936
  try {
63961
63937
  const e = decodeEventLog({ abi: abi2, data: log.data, topics: log.topics });
63962
63938
  return e.eventName === "AuthorizationUsed" && e.args.authorizer.toLowerCase() === proof2.from.toLowerCase() && e.args.nonce.toLowerCase() === proof2.nonce.toLowerCase();
@@ -63967,20 +63943,19 @@ var BaseUsdcReader = class {
63967
63943
  requireThat(used, "authorization_nonce_not_confirmed");
63968
63944
  }
63969
63945
  } catch (e) {
63970
- if (e instanceof RuntimeFault)
63971
- throw e;
63946
+ if (e instanceof RuntimeFault) throw e;
63972
63947
  throw new RuntimeFault("chain_unavailable", true);
63973
63948
  }
63974
63949
  }
63975
63950
  };
63976
63951
 
63977
- // dist/text-schemas.js
63952
+ // src/text-schemas.ts
63978
63953
  var searchText = external_exports.string().trim().max(80).refine((value) => value.length <= 80, "Use at most 80 UTF-16 code units after trimming.").meta({
63979
63954
  description: "At most 80 UTF-16 code units after trimming; a non-BMP character such as an emoji counts as two.",
63980
63955
  "x-maxUtf16CodeUnits": 80
63981
63956
  });
63982
63957
 
63983
- // dist/worker-profiles.js
63958
+ // src/worker-profiles.ts
63984
63959
  var text = (limit) => external_exports.string().trim().min(1).refine((value) => Array.from(value).length <= limit, `Use at most ${limit} Unicode code points.`).meta({ maxLength: limit });
63985
63960
  var workerCapabilityId = external_exports.string().regex(/^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/);
63986
63961
  var workerContentType = external_exports.enum(["application/json", "text/plain; charset=utf-8"]);
@@ -64006,7 +63981,7 @@ var workerProfileViewSchema = external_exports.object({
64006
63981
  workTicket: external_exports.object({ method: external_exports.literal("POST"), challengePath: external_exports.literal("/v1/work-tickets/challenges"), merchantId: external_exports.string().uuid(), guide: external_exports.literal("/work-tickets.md"), paymentRequiredToCreate: external_exports.literal(false), quoteRequired: external_exports.literal(true) }).strict()
64007
63982
  }).strict().refine((value) => value.merchant.id === value.workerProfile.merchantId && value.merchant.id === value.workTicket.merchantId, "Worker routing must reference the same merchant.");
64008
63983
 
64009
- // dist/transaction-evidence/schema.js
63984
+ // src/transaction-evidence/schema.ts
64010
63985
  var EVIDENCE_PROTOCOL = "402mob.transaction-evidence.v1";
64011
63986
  var MAX_BUNDLE_BYTES = 256 * 1024;
64012
63987
  var EVIDENCE_ASSET = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
@@ -64045,21 +64020,19 @@ var transactionEvidenceContentSchema = external_exports.object({
64045
64020
  }).strict();
64046
64021
  var transactionEvidenceSchema = transactionEvidenceContentSchema.extend({ bundleHash: hash4 }).strict();
64047
64022
 
64048
- // dist/transaction-evidence/core.js
64023
+ // src/transaction-evidence/core.ts
64049
64024
  function evidenceCanonical(value) {
64050
64025
  if (value === null || typeof value !== "object") {
64051
64026
  const text3 = JSON.stringify(value);
64052
- if (text3 === void 0)
64053
- throw new Error("Non-JSON value");
64027
+ if (text3 === void 0) throw new Error("Non-JSON value");
64054
64028
  return text3;
64055
64029
  }
64056
- if (Array.isArray(value))
64057
- return "[" + value.map(evidenceCanonical).join(",") + "]";
64030
+ if (Array.isArray(value)) return "[" + value.map(evidenceCanonical).join(",") + "]";
64058
64031
  return "{" + Object.keys(value).sort().map((k) => JSON.stringify(k) + ":" + evidenceCanonical(value[k])).join(",") + "}";
64059
64032
  }
64060
64033
  var proposalDeadlineSchema = external_exports.string().datetime();
64061
64034
 
64062
- // dist/transaction-evidence/offer-schema.js
64035
+ // src/transaction-evidence/offer-schema.ts
64063
64036
  var text2 = (max) => external_exports.string().trim().min(1).refine((v2) => Array.from(v2).length <= max, `Use at most ${max} Unicode code points.`).meta({ maxLength: max });
64064
64037
  var https = external_exports.string().url().max(2048).refine((value) => {
64065
64038
  const u = new URL(value);
@@ -64070,10 +64043,8 @@ var purchaseDecisionSchema = external_exports.object({
64070
64043
  intendedUse: text2(500),
64071
64044
  resultSchema: external_exports.object({ uri: https, version: external_exports.string().regex(/^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/), sha256: external_exports.string().regex(/^[a-f0-9]{64}$/) }).strict().nullable(),
64072
64045
  coverage: external_exports.object({ asOf: external_exports.string().datetime(), from: external_exports.string().datetime().optional(), through: external_exports.string().datetime().optional() }).strict().superRefine((c, ctx) => {
64073
- if (c.from === void 0 !== (c.through === void 0))
64074
- ctx.addIssue({ code: "custom", message: "Provide both coverage from and through, or neither." });
64075
- if (c.from && c.through && Date.parse(c.from) > Date.parse(c.through))
64076
- ctx.addIssue({ code: "custom", path: ["through"], message: "Coverage through must not precede from." });
64046
+ if (c.from === void 0 !== (c.through === void 0)) ctx.addIssue({ code: "custom", message: "Provide both coverage from and through, or neither." });
64047
+ if (c.from && c.through && Date.parse(c.from) > Date.parse(c.through)) ctx.addIssue({ code: "custom", path: ["through"], message: "Coverage through must not precede from." });
64077
64048
  }),
64078
64049
  limitations: external_exports.array(text2(300)).min(1).max(8),
64079
64050
  reuseTerms: text2(3e3),
@@ -64097,28 +64068,27 @@ var evidenceOfferTermsSchema = external_exports.object({
64097
64068
  purchaseDecision: purchaseDecisionSchema
64098
64069
  }).strict();
64099
64070
 
64100
- // dist/runtime/http.js
64071
+ // src/runtime/http.ts
64101
64072
  var RemoteHttpFault = class extends RuntimeFault {
64102
- status;
64103
- remoteCode;
64104
64073
  constructor(status, remoteCode) {
64105
64074
  super("remote_http_" + status + (remoteCode ? "_" + remoteCode : ""), status === 429 || status >= 500);
64106
64075
  this.status = status;
64107
64076
  this.remoteCode = remoteCode;
64108
64077
  }
64078
+ status;
64079
+ remoteCode;
64109
64080
  };
64110
64081
  var RuntimeHttp = class {
64111
- fetcher;
64112
- apiKey;
64113
- origin;
64114
64082
  constructor(value, fetcher = fetch, apiKey) {
64115
64083
  this.fetcher = fetcher;
64116
64084
  this.apiKey = apiKey;
64117
64085
  this.origin = origin(value);
64118
64086
  }
64087
+ fetcher;
64088
+ apiKey;
64089
+ origin;
64119
64090
  async bytes(path, body, headers = {}) {
64120
- if (!path.startsWith("/") || path.startsWith("//"))
64121
- throw new RuntimeFault("invalid_api_path");
64091
+ if (!path.startsWith("/") || path.startsWith("//")) throw new RuntimeFault("invalid_api_path");
64122
64092
  try {
64123
64093
  const response = await this.fetcher(this.origin + path, {
64124
64094
  method: body === void 0 ? "GET" : "POST",
@@ -64134,25 +64104,21 @@ var RuntimeHttp = class {
64134
64104
  });
64135
64105
  const reader = response.body?.getReader(), chunks = [];
64136
64106
  let size5 = 0;
64137
- if (reader)
64138
- try {
64139
- for (; ; ) {
64140
- const item = await reader.read();
64141
- if (item.done)
64142
- break;
64143
- size5 += item.value.length;
64144
- if (size5 > 1024 * 1024)
64145
- throw new RuntimeFault("response_too_large");
64146
- chunks.push(item.value);
64147
- }
64148
- } finally {
64149
- await reader.cancel().catch(() => {
64150
- });
64107
+ if (reader) try {
64108
+ for (; ; ) {
64109
+ const item = await reader.read();
64110
+ if (item.done) break;
64111
+ size5 += item.value.length;
64112
+ if (size5 > 1024 * 1024) throw new RuntimeFault("response_too_large");
64113
+ chunks.push(item.value);
64151
64114
  }
64115
+ } finally {
64116
+ await reader.cancel().catch(() => {
64117
+ });
64118
+ }
64152
64119
  return { status: response.status, headers: response.headers, bytes: Buffer.concat(chunks) };
64153
64120
  } catch (e) {
64154
- if (e instanceof RuntimeFault)
64155
- throw e;
64121
+ if (e instanceof RuntimeFault) throw e;
64156
64122
  throw new RuntimeFault("transport_uncertain", true);
64157
64123
  }
64158
64124
  }
@@ -64162,8 +64128,7 @@ var RuntimeHttp = class {
64162
64128
  let code;
64163
64129
  try {
64164
64130
  const body2 = JSON.parse(result.bytes.toString("utf8"));
64165
- if (typeof body2?.error === "string" && /^[a-z][a-z0-9_]{0,79}$/.test(body2.error))
64166
- code = body2.error;
64131
+ if (typeof body2?.error === "string" && /^[a-z][a-z0-9_]{0,79}$/.test(body2.error)) code = body2.error;
64167
64132
  } catch {
64168
64133
  }
64169
64134
  throw new RemoteHttpFault(result.status, code);
@@ -64176,8 +64141,9 @@ var RuntimeHttp = class {
64176
64141
  }
64177
64142
  };
64178
64143
 
64179
- // dist/runtime/catalog.js
64144
+ // src/runtime/catalog.ts
64180
64145
  var catalogQuery = external_exports.object({ query: searchText.default(""), cursor: external_exports.coerce.number().int().min(0).max(1e8).default(0), limit: external_exports.coerce.number().int().min(1).max(50).default(20) }).strict();
64146
+ var WORKER_PAGE_MAX = 5;
64181
64147
  var resolveShareInput = external_exports.object({ url: external_exports.string().url().max(2048).describe("Pinned /s/{merchantId}/{offerId}/{shareId} URL on the configured service origin. No query, fragment or credentials; a changed share is rejected.") }).strict();
64182
64148
  var artifactMetadata = external_exports.object({ algorithm: external_exports.literal("sha256-private-proof-v1"), commitment: digest, sizeUpperBound: external_exports.number().int().min(1024).max(49152).multipleOf(1024) }).strict();
64183
64149
  var merchant = external_exports.object({ id: uuid3, name: external_exports.string(), payoutAddress: address });
@@ -64212,27 +64178,25 @@ var inspectedResource = external_exports.object({
64212
64178
  termsHash: digest.describe("SHA-256 of canonical normalized terms; copy this exact value into the prepared task. Distinct from offerTermsHash and artifact.commitment."),
64213
64179
  sourceShareId: digest.optional()
64214
64180
  }).strict();
64215
- var workerResults = external_exports.object({ items: external_exports.array(workerProfileViewSchema), nextCursor: external_exports.number().int().nonnegative().nullable() }).strict();
64181
+ var workerResults = external_exports.object({ items: external_exports.array(workerProfileViewSchema).max(WORKER_PAGE_MAX), nextCursor: external_exports.number().int().nonnegative().nullable() }).strict();
64216
64182
  var resourceResults = external_exports.object({ items: external_exports.array(external_exports.object({ merchant: merchant.omit({ payoutAddress: true }), offer })), nextCursor: external_exports.number().int().nonnegative().nullable() });
64217
64183
  var RuntimeCatalog = class {
64218
- wallet;
64219
- http;
64220
64184
  constructor(wallet2, fetcher = fetch) {
64221
64185
  this.wallet = wallet2;
64222
64186
  this.http = new RuntimeHttp(wallet2.origin, fetcher);
64223
64187
  }
64188
+ wallet;
64189
+ http;
64224
64190
  async workers(delegation, input2) {
64225
64191
  const p = this.wallet.policy(delegation).policy, q = catalogQuery.parse(input2);
64226
- if (p.capability && p.capability !== TEXT_CAPABILITY)
64227
- return workerResults.parse({ items: [], nextCursor: null });
64228
- const params = new URLSearchParams({ q: q.query, cursor: String(q.cursor), limit: String(q.limit), capability: TEXT_CAPABILITY, contentType: "application/json" });
64192
+ if (p.capability && p.capability !== TEXT_CAPABILITY) return workerResults.parse({ items: [], nextCursor: null });
64193
+ const params = new URLSearchParams({ q: q.query, cursor: String(q.cursor), limit: String(Math.min(q.limit, WORKER_PAGE_MAX)), capability: TEXT_CAPABILITY, contentType: "application/json" });
64229
64194
  const result = await this.http.json("/v1/worker-directory?" + params, workerResults);
64230
64195
  return workerResults.parse({ ...result, items: result.items.filter((item) => (!p.merchantId || p.merchantId === item.merchant.id) && (!p.payee || p.payee.toLowerCase() === item.merchant.payoutAddress.toLowerCase()) && item.workerProfile.availability === "accepting" && item.workerProfile.capabilities.some((c) => c.id === TEXT_CAPABILITY && c.resultContentTypes.includes("application/json") && (!c.settlementModes || c.settlementModes.includes("direct_prepayment")))) });
64231
64196
  }
64232
64197
  async resources(delegation, input2) {
64233
64198
  const p = this.wallet.policy(delegation).policy, q = catalogQuery.parse(input2);
64234
- if (p.capability && p.capability !== "prepared-artifact-v1")
64235
- return resourceResults.parse({ items: [], nextCursor: null });
64199
+ if (p.capability && p.capability !== "prepared-artifact-v1") return resourceResults.parse({ items: [], nextCursor: null });
64236
64200
  const result = await this.http.json("/v1/merchant-directory?" + new URLSearchParams({ q: q.query, cursor: String(q.cursor), limit: String(q.limit) }), resourceResults);
64237
64201
  return resourceResults.parse({ ...result, items: result.items.filter((item) => !p.merchantId || p.merchantId === item.merchant.id) });
64238
64202
  }
@@ -64242,50 +64206,38 @@ var RuntimeCatalog = class {
64242
64206
  const match = url2.pathname.match(/^\/s\/([^/]+)\/([^/]+)\/([a-f0-9]{64})$/);
64243
64207
  requireThat(match, "invalid_share_url");
64244
64208
  const merchantId = uuid3.parse(match[1]), offerId = uuid3.parse(match[2]);
64245
- const raw = await this.http.json(`/v1/merchants/${merchantId}/offers/${offerId}/share`, external_exports.object({ schema: external_exports.enum(["402mob.checkout-share.v3", "402mob.checkout-share.v4"]), origin: external_exports.string(), offer: external_exports.record(external_exports.string(), external_exports.unknown()), id: digest }).strict());
64246
- requireThat(raw.origin === this.http.origin && raw.id === match[3] && sha256(JSON.stringify({ schema: raw.schema, origin: raw.origin, offer: raw.offer })) === raw.id, "share_terms_changed");
64247
- const resource = await this.inspect(merchantId, offerId), terms = resourceTerms.parse(Object.fromEntries(Object.entries(raw.offer).filter(([key]) => !["amountUSDC", "resultSizeKnownBeforePayment", "checkout"].includes(key))));
64248
- requireThat(canonical(terms) === canonical(resource.terms) && raw.offer.checkout === `${this.http.origin}/v1/merchants/${merchantId}/offers/${offerId}/checkout`, "share_terms_changed");
64249
- return inspectedResource.parse({ ...resource, sourceShareId: raw.id });
64209
+ const { resource, shareId } = await this.readOffer(merchantId, offerId);
64210
+ requireThat(shareId === match[3], "share_terms_changed");
64211
+ return inspectedResource.parse({ ...resource, sourceShareId: shareId });
64250
64212
  }
64251
64213
  async inspect(merchantId, offerId) {
64214
+ return (await this.readOffer(merchantId, offerId)).resource;
64215
+ }
64216
+ async readOffer(merchantId, offerId) {
64252
64217
  uuid3.parse(merchantId);
64253
64218
  uuid3.parse(offerId);
64254
- const profile = await this.http.json("/v1/merchants/" + merchantId, external_exports.object({ merchant, offers: external_exports.array(offer) }));
64255
- const selected = profile.offers.find((o) => o.id === offerId);
64256
- requireThat(profile.merchant.id === merchantId && selected, "offer_unavailable");
64257
- const terms = resourceTerms.parse({
64258
- merchantId,
64259
- offerId,
64260
- version: selected.version,
64261
- title: selected.title,
64262
- description: selected.description,
64263
- payee: profile.merchant.payoutAddress.toLowerCase(),
64264
- network: NETWORK,
64265
- asset: USDC.toLowerCase(),
64266
- amountAtomic: selected.amountAtomic,
64267
- contentType: selected.contentType === "application/json" ? "application/json" : "text/plain",
64268
- artifact: selected.artifact,
64269
- ...selected.purchaseDecision ? { purchaseDecision: selected.purchaseDecision } : {},
64270
- ...selected.offerTermsHash ? { offerTermsHash: selected.offerTermsHash } : {}
64271
- });
64219
+ const raw = await this.http.json(`/v1/merchants/${merchantId}/offers/${offerId}/share`, external_exports.object({ schema: external_exports.enum(["402mob.checkout-share.v3", "402mob.checkout-share.v4"]), origin: external_exports.string(), offer: external_exports.record(external_exports.string(), external_exports.unknown()), id: digest }).strict());
64220
+ requireThat(raw.origin === this.http.origin && sha256(JSON.stringify({ schema: raw.schema, origin: raw.origin, offer: raw.offer })) === raw.id, "share_terms_changed");
64221
+ const terms = resourceTerms.extend({ version: offer.shape.version }).parse(Object.fromEntries(Object.entries(raw.offer).filter(([key]) => !["amountUSDC", "resultSizeKnownBeforePayment", "checkout"].includes(key))));
64222
+ requireThat(terms.merchantId === merchantId && terms.offerId === offerId && terms.asset.toLowerCase() === USDC.toLowerCase() && raw.offer.checkout === `${this.http.origin}/v1/merchants/${merchantId}/offers/${offerId}/checkout` && raw.offer.resultSizeKnownBeforePayment === false && raw.offer.amountUSDC === `${BigInt(terms.amountAtomic) / 1000000n}.${String(BigInt(terms.amountAtomic) % 1000000n).padStart(6, "0")}`, "offer_terms_mismatch");
64223
+ requireThat(raw.schema === "402mob.checkout-share.v4" ? Boolean(terms.purchaseDecision && terms.offerTermsHash) : !terms.purchaseDecision && !terms.offerTermsHash, "offer_terms_mismatch");
64272
64224
  if (terms.purchaseDecision || terms.offerTermsHash) {
64273
64225
  const { offerTermsHash, ...document2 } = terms;
64274
64226
  requireThat(terms.purchaseDecision && offerTermsHash === sha256(canonical({ schema: "402mob.offer-terms.v1", ...document2 })), "offer_terms_mismatch");
64275
64227
  }
64276
- return inspectedResource.parse({ terms, termsHash: sha256(canonical(terms)) });
64228
+ return { resource: inspectedResource.parse({ terms, termsHash: sha256(canonical(terms)) }), shareId: raw.id };
64277
64229
  }
64278
64230
  };
64279
64231
 
64280
- // dist/runtime/core.js
64232
+ // src/runtime/core.ts
64281
64233
  import { randomUUID as randomUUID3 } from "node:crypto";
64282
64234
  var RuntimeCore = class {
64283
- store;
64284
- clock;
64285
64235
  constructor(store, clock = Date.now) {
64286
64236
  this.store = store;
64287
64237
  this.clock = clock;
64288
64238
  }
64239
+ store;
64240
+ clock;
64289
64241
  create(id, profile, owner, input2, state2) {
64290
64242
  return this.store.transaction(() => {
64291
64243
  const existing = this.get(id);
@@ -64300,8 +64252,7 @@ var RuntimeCore = class {
64300
64252
  }
64301
64253
  get(id) {
64302
64254
  const r = this.store.db.prepare("SELECT * FROM jobs WHERE id=?").get(id);
64303
- if (!r)
64304
- return void 0;
64255
+ if (!r) return void 0;
64305
64256
  return {
64306
64257
  id: String(r.id),
64307
64258
  profile: String(r.profile),
@@ -64348,12 +64299,10 @@ var RuntimeCore = class {
64348
64299
  const claimed = this.store.transaction(() => {
64349
64300
  const j2 = this.get(id);
64350
64301
  requireThat(j2 && j2.profile === profile.name, "job_profile_mismatch");
64351
- if (j2.status !== "active" || j2.nextAt > now)
64352
- return false;
64302
+ if (j2.status !== "active" || j2.nextAt > now) return false;
64353
64303
  return this.store.db.prepare("UPDATE jobs SET lease=?,lease_until=? WHERE id=? AND lease_until<=?").run(lease, now + 12e4, id, now).changes === 1;
64354
64304
  });
64355
- if (!claimed)
64356
- return this.get(id);
64305
+ if (!claimed) return this.get(id);
64357
64306
  const assertLease = () => {
64358
64307
  const r = this.store.db.prepare("SELECT lease,lease_until FROM jobs WHERE id=?").get(id);
64359
64308
  requireThat(r?.lease === lease && Number(r.lease_until) > this.clock() + 2e4, "runtime_lease_lost");
@@ -64372,8 +64321,7 @@ var RuntimeCore = class {
64372
64321
  const prior = this.store.db.prepare("SELECT * FROM actions WHERE job=? AND key=?").get(id, key);
64373
64322
  if (prior) {
64374
64323
  requireThat(prior.input_hash === hash5 && prior.replay === replay, "action_terms_changed");
64375
- if (prior.status === "complete")
64376
- return JSON.parse(String(prior.result));
64324
+ if (prior.status === "complete") return JSON.parse(String(prior.result));
64377
64325
  requireThat(replay === "safe", "uncertain_nonreplayable_action");
64378
64326
  requireThat(Number(prior.attempts) < 4, "action_retry_limit");
64379
64327
  }
@@ -64403,7 +64351,7 @@ var RuntimeCore = class {
64403
64351
  }
64404
64352
  };
64405
64353
 
64406
- // dist/runtime/artifact.js
64354
+ // src/runtime/artifact.ts
64407
64355
  var artifactTask = external_exports.object({
64408
64356
  kind: external_exports.literal("prepared_artifact"),
64409
64357
  id: uuid3,
@@ -64424,11 +64372,6 @@ var state = external_exports.object({
64424
64372
  transaction: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).optional()
64425
64373
  }).strict();
64426
64374
  var ArtifactRuntime = class {
64427
- wallet;
64428
- model;
64429
- core;
64430
- http;
64431
- catalog;
64432
64375
  constructor(wallet2, fetcher = fetch, model) {
64433
64376
  this.wallet = wallet2;
64434
64377
  this.model = model;
@@ -64436,6 +64379,11 @@ var ArtifactRuntime = class {
64436
64379
  this.http = new RuntimeHttp(wallet2.origin, fetcher);
64437
64380
  this.catalog = new RuntimeCatalog(wallet2, fetcher);
64438
64381
  }
64382
+ wallet;
64383
+ model;
64384
+ core;
64385
+ http;
64386
+ catalog;
64439
64387
  create(delegation, value) {
64440
64388
  const task = artifactTask.parse(value), old = this.core.get(task.id);
64441
64389
  if (old) {
@@ -64446,7 +64394,8 @@ var ArtifactRuntime = class {
64446
64394
  const p = this.wallet.assertActive(delegation);
64447
64395
  requireThat(!p.merchantId || p.merchantId === task.merchantId, "merchant_outside_delegation");
64448
64396
  requireThat(!p.capability || p.capability === "prepared-artifact-v1", "capability_outside_delegation");
64449
- requireThat(toAtomic(task.maxPriceUSDC) <= toAtomic(p.maxPerPaymentUSDC ?? p.maxTotalUSDC), "task_exceeds_delegation");
64397
+ const cap = p.maxPerPaymentUSDC ?? p.maxTotalUSDC;
64398
+ requireThat(!cap || toAtomic(task.maxPriceUSDC) <= toAtomic(cap), "task_exceeds_delegation");
64450
64399
  requireThat(Number(this.wallet.store.db.prepare("SELECT COUNT(*) n FROM jobs WHERE owner=? AND status='active'").get(delegation)?.n) < 10, "agent_task_capacity");
64451
64400
  requireThat(Number(this.wallet.store.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status='active'").get()?.n) < 100, "wallet_task_capacity");
64452
64401
  this.core.create(task.id, "buyer-v1", delegation, { ...task, delegation, deadline: new Date(this.wallet.clock() + 864e5).toISOString() }, { stage: "create" });
@@ -64493,8 +64442,7 @@ var ArtifactRuntime = class {
64493
64442
  const p = this.wallet.assertActive(task.delegation), inspected = await this.catalog.inspect(task.merchantId, task.offerId), terms2 = inspected.terms;
64494
64443
  requireThat(inspected.termsHash === task.termsHash, "offer_terms_changed");
64495
64444
  requireThat(BigInt(terms2.amountAtomic) <= toAtomic(task.maxPriceUSDC) && (!p.payee || p.payee.toLowerCase() === terms2.payee.toLowerCase()), "offer_outside_delegation");
64496
- if (this.model && !await this.model.admit(c, { role: "buyer", capability: "prepared-artifact-v1", terms: terms2, maxPriceUSDC: task.maxPriceUSDC }))
64497
- return { state: s, status: "rejected" };
64445
+ if (this.model && !await this.model.admit(c, { role: "buyer", capability: "prepared-artifact-v1", terms: terms2, maxPriceUSDC: task.maxPriceUSDC })) return { state: s, status: "rejected" };
64498
64446
  return { state: { ...s, terms: terms2, stage: "pay" } };
64499
64447
  }
64500
64448
  requireThat(s.terms, "artifact_terms_missing");
@@ -64520,8 +64468,7 @@ var ArtifactRuntime = class {
64520
64468
  }
64521
64469
  const op = uuid3.parse(r.headers.get("X-402Mob-Operation"));
64522
64470
  requireThat(!s.operationId || s.operationId === op, "payment_operation_changed");
64523
- if (r.status === 202)
64524
- return { state: { ...s, operationId: op }, waitMs: 5e3 };
64471
+ if (r.status === 202) return { state: { ...s, operationId: op }, waitMs: 5e3 };
64525
64472
  const proof2 = digest.parse(r.headers.get("X-402Mob-Artifact-Proof"));
64526
64473
  requireThat(r.bytes.length <= terms.artifact.sizeUpperBound && sha256(Buffer.concat([Buffer.from("402mob.artifact-commitment.v1\n"), Buffer.from(proof2, "hex"), r.bytes])) === terms.artifact.commitment, "artifact_integrity_mismatch");
64527
64474
  requireThat(r.headers.get("content-type")?.split(";")[0] === terms.contentType && (!terms.offerTermsHash || r.headers.get("X-402Mob-Offer-Terms") === terms.offerTermsHash), "artifact_terms_mismatch");
@@ -64550,16 +64497,15 @@ var ArtifactRuntime = class {
64550
64497
  });
64551
64498
  return { state: { ...s, stage: "done" }, status: "complete" };
64552
64499
  }
64553
- if (s.stage !== "done")
64554
- throw new RuntimeFault("artifact_stage_invalid");
64500
+ if (s.stage !== "done") throw new RuntimeFault("artifact_stage_invalid");
64555
64501
  return { state: s, status: "complete" };
64556
64502
  }
64557
64503
  };
64558
64504
 
64559
- // dist/runtime/buyer.js
64505
+ // src/runtime/buyer.ts
64560
64506
  import { randomUUID as randomUUID4 } from "node:crypto";
64561
64507
 
64562
- // dist/runtime/protocol.js
64508
+ // src/runtime/protocol.ts
64563
64509
  var challenge2 = external_exports.object({ challengeId: uuid3, message: external_exports.string().max(1e4), expiresAt: date5 });
64564
64510
  var proof = challenge2.extend({ signature });
64565
64511
  var quote = external_exports.object({ id: uuid3, amountAtomic: atomic, deliverable: external_exports.string().max(300), contentType: external_exports.enum(["application/json", "text/plain; charset=utf-8"]), termsHash: digest, expiresAt: date5 });
@@ -64614,7 +64560,7 @@ function quoteHash(t) {
64614
64560
  return sha256(canonical({ ticketId: t.id, merchantId: t.merchantId, quoteId: q.id, amount: q.amountAtomic, deliverable: q.deliverable, contentType: q.contentType, expiresAt: q.expiresAt }));
64615
64561
  }
64616
64562
 
64617
- // dist/runtime/buyer.js
64563
+ // src/runtime/buyer.ts
64618
64564
  var workBuyerTask = external_exports.object({
64619
64565
  id: uuid3,
64620
64566
  input: textInput,
@@ -64654,13 +64600,6 @@ var stateSchema = external_exports.object({
64654
64600
  verdict: external_exports.enum(["accepted", "disputed"]).optional()
64655
64601
  }).strict();
64656
64602
  var BuyerRuntime = class {
64657
- wallet;
64658
- model;
64659
- name = "buyer-v1";
64660
- core;
64661
- http;
64662
- artifacts;
64663
- catalog;
64664
64603
  constructor(wallet2, fetcher = fetch, model) {
64665
64604
  this.wallet = wallet2;
64666
64605
  this.model = model;
@@ -64669,10 +64608,16 @@ var BuyerRuntime = class {
64669
64608
  this.artifacts = new ArtifactRuntime(wallet2, fetcher, model);
64670
64609
  this.catalog = this.artifacts.catalog;
64671
64610
  }
64611
+ wallet;
64612
+ model;
64613
+ name = "buyer-v1";
64614
+ core;
64615
+ http;
64616
+ artifacts;
64617
+ catalog;
64672
64618
  create(delegation, input2) {
64673
64619
  const parsed = buyerTask.parse(input2);
64674
- if ("kind" in parsed)
64675
- return buyerView.parse(this.artifacts.create(delegation, parsed));
64620
+ if ("kind" in parsed) return buyerView.parse(this.artifacts.create(delegation, parsed));
64676
64621
  const task = parsed, old = this.core.get(task.id);
64677
64622
  if (old) {
64678
64623
  const { delegation: _delegation, deadline: _deadline, targetMerchantId: _target, ...saved } = taskInput.parse(old.input);
@@ -64684,7 +64629,8 @@ var BuyerRuntime = class {
64684
64629
  requireThat(targetMerchantId, "task_merchant_required");
64685
64630
  requireThat(!policy.merchantId || targetMerchantId === policy.merchantId, "merchant_outside_delegation");
64686
64631
  requireThat(!policy.capability || policy.capability === TEXT_CAPABILITY, "capability_outside_delegation");
64687
- requireThat(toAtomic(task.maxPriceUSDC) <= toAtomic(policy.maxPerPaymentUSDC ?? policy.maxTotalUSDC), "task_exceeds_delegation");
64632
+ const cap = policy.maxPerPaymentUSDC ?? policy.maxTotalUSDC;
64633
+ requireThat(!cap || toAtomic(task.maxPriceUSDC) <= toAtomic(cap), "task_exceeds_delegation");
64688
64634
  requireThat(Number(this.wallet.store.db.prepare("SELECT COUNT(*) n FROM jobs WHERE profile=? AND owner=? AND status='active'").get(this.name, delegation)?.n) < 10, "agent_task_capacity");
64689
64635
  requireThat(Number(this.wallet.store.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status='active'").get()?.n) < 100, "wallet_task_capacity");
64690
64636
  this.core.create(task.id, this.name, delegation, { ...task, delegation, targetMerchantId, deadline: new Date(this.wallet.clock() + 864e5).toISOString() }, { stage: "create" });
@@ -64693,16 +64639,14 @@ var BuyerRuntime = class {
64693
64639
  view(id, delegation) {
64694
64640
  const j = this.core.get(id);
64695
64641
  requireThat(j && j.owner === delegation, "job_not_found");
64696
- if (artifactTask.safeParse(j.input && typeof j.input === "object" ? Object.fromEntries(Object.entries(j.input).filter(([key]) => !["delegation", "deadline"].includes(key))) : null).success)
64697
- return buyerView.parse(this.artifacts.view(id, delegation));
64642
+ if (artifactTask.safeParse(j.input && typeof j.input === "object" ? Object.fromEntries(Object.entries(j.input).filter(([key]) => !["delegation", "deadline"].includes(key))) : null).success) return buyerView.parse(this.artifacts.view(id, delegation));
64698
64643
  const s = stateSchema.parse(j.state);
64699
64644
  const target = taskInput.parse(j.input).targetMerchantId ?? this.wallet.policy(delegation).policy.merchantId;
64700
64645
  let result = null;
64701
- if (s.resultBase64)
64702
- try {
64703
- result = JSON.parse(Buffer.from(s.resultBase64, "base64").toString("utf8"));
64704
- } catch {
64705
- }
64646
+ if (s.resultBase64) try {
64647
+ result = JSON.parse(Buffer.from(s.resultBase64, "base64").toString("utf8"));
64648
+ } catch {
64649
+ }
64706
64650
  return buyerView.parse({
64707
64651
  id,
64708
64652
  merchantId: target,
@@ -64729,8 +64673,7 @@ var BuyerRuntime = class {
64729
64673
  return (name) => name + (s.proofRevision ? ":" + s.proofRevision : "");
64730
64674
  }
64731
64675
  renewProof(c, s, error62, code) {
64732
- if (!(error62 instanceof RemoteHttpFault) || error62.status !== 401 || error62.remoteCode !== code)
64733
- throw error62;
64676
+ if (!(error62 instanceof RemoteHttpFault) || error62.status !== 401 || error62.remoteCode !== code) throw error62;
64734
64677
  requireThat(s.proofRevision < 3, "proof_renewal_limit");
64735
64678
  c.record("renew_" + s.stage + "_proof");
64736
64679
  return { state: { ...s, proofRevision: s.proofRevision + 1 }, waitMs: 1e3 };
@@ -64738,26 +64681,20 @@ var BuyerRuntime = class {
64738
64681
  checkTicket(t, c, state2) {
64739
64682
  const task = taskInput.parse(c.job.input), p = this.wallet.policy(task.delegation).policy;
64740
64683
  requireThat(t.id === state2.ticketId && t.merchantId === (task.targetMerchantId ?? p.merchantId) && t.capability === TEXT_CAPABILITY && t.inputHash === sha256(canonical(task.input)) && t.maxPriceAtomic === toAtomic(task.maxPriceUSDC).toString(), "ticket_binding_mismatch");
64741
- if (t.quote)
64742
- requireThat(quoteHash(t) === t.quote.termsHash, "quote_hash_mismatch");
64743
- if (state2.accepted)
64744
- requireThat(t.quote && canonical(t.quote) === canonical(quote.parse(state2.accepted.quote)), "quote_changed");
64745
- if (state2.operationId)
64746
- requireThat(t.payment.operationId === state2.operationId, "payment_operation_changed");
64684
+ if (t.quote) requireThat(quoteHash(t) === t.quote.termsHash, "quote_hash_mismatch");
64685
+ if (state2.accepted) requireThat(t.quote && canonical(t.quote) === canonical(quote.parse(state2.accepted.quote)), "quote_changed");
64686
+ if (state2.operationId) requireThat(t.payment.operationId === state2.operationId, "payment_operation_changed");
64747
64687
  }
64748
64688
  async step(c) {
64749
- if (c.job.input && typeof c.job.input === "object" && "kind" in c.job.input && c.job.input.kind === "prepared_artifact")
64750
- return this.artifacts.step(c);
64689
+ if (c.job.input && typeof c.job.input === "object" && "kind" in c.job.input && c.job.input.kind === "prepared_artifact") return this.artifacts.step(c);
64751
64690
  const task = taskInput.parse(c.job.input), s = stateSchema.parse(c.job.state), policy = this.wallet.policy(task.delegation).policy;
64752
64691
  const merchantId = task.targetMerchantId ?? policy.merchantId;
64753
64692
  requireThat(merchantId, "task_merchant_required");
64754
- if (Date.parse(task.deadline) <= c.now)
64755
- throw new RuntimeFault("task_deadline_recovery_required");
64693
+ if (Date.parse(task.deadline) <= c.now) throw new RuntimeFault("task_deadline_recovery_required");
64756
64694
  const buyer = this.wallet.address.toLowerCase(), key = "runtime_grant_" + task.id;
64757
64695
  if (s.stage === "create") {
64758
64696
  this.wallet.assertActive(task.delegation);
64759
- if (this.model && !await this.model.admit(c, { role: "buyer", capability: TEXT_CAPABILITY, input: task.input, maxPriceUSDC: task.maxPriceUSDC }))
64760
- return { state: s, status: "rejected" };
64697
+ if (this.model && !await this.model.admit(c, { role: "buyer", capability: TEXT_CAPABILITY, input: task.input, maxPriceUSDC: task.maxPriceUSDC })) return { state: s, status: "rejected" };
64761
64698
  const body = { buyer, merchantId, capability: TEXT_CAPABILITY, input: task.input, maxPriceUSDC: task.maxPriceUSDC, expiresInSeconds: 3600 };
64762
64699
  const action = await this.proofKey(c, s, "grant", body);
64763
64700
  const signed = await c.effect(action("grant-proof"), body, "safe", async () => {
@@ -64769,7 +64706,12 @@ var BuyerRuntime = class {
64769
64706
  });
64770
64707
  let created;
64771
64708
  try {
64772
- created = await c.effect(action("create-ticket"), { body, signed }, "safe", () => this.http.json("/v1/work-tickets", ticketResponse, { ...body, challengeId: signed.challengeId, signature: signed.signature }, { "Idempotency-Key": key }));
64709
+ created = await c.effect(action("create-ticket"), { body, signed }, "safe", () => this.http.json(
64710
+ "/v1/work-tickets",
64711
+ ticketResponse,
64712
+ { ...body, challengeId: signed.challengeId, signature: signed.signature },
64713
+ { "Idempotency-Key": key }
64714
+ ));
64773
64715
  } catch (error62) {
64774
64716
  return this.renewProof(c, s, error62, "invalid_work_ticket_challenge");
64775
64717
  }
@@ -64782,8 +64724,7 @@ var BuyerRuntime = class {
64782
64724
  const current = (await this.http.json(path, ticketResponse)).ticket;
64783
64725
  this.checkTicket(current, c, s);
64784
64726
  if (s.stage === "quote") {
64785
- if (current.state === "open" || current.state === "claimed")
64786
- return { state: s, waitMs: 5e3 };
64727
+ if (current.state === "open" || current.state === "claimed") return { state: s, waitMs: 5e3 };
64787
64728
  requireThat(current.state === "quoted" || current.state === "accepted", "quote_unavailable");
64788
64729
  this.wallet.assertActive(task.delegation);
64789
64730
  const terms = { ticketId: s.ticketId, grant: s.grant, quote: current.quote };
@@ -64849,19 +64790,15 @@ var BuyerRuntime = class {
64849
64790
  payment = await this.wallet.authorize(task.id, task.delegation, s.accepted.quote.termsHash, req, path + "/checkout");
64850
64791
  }
64851
64792
  const paid = await this.http.bytes(path + "/checkout", {}, { "Idempotency-Key": paymentKey, "PAYMENT-SIGNATURE": Buffer.from(JSON.stringify(payment)).toString("base64") });
64852
- if (![200, 202].includes(paid.status))
64853
- throw new RuntimeFault("payment_outcome_uncertain", true);
64793
+ if (![200, 202].includes(paid.status)) throw new RuntimeFault("payment_outcome_uncertain", true);
64854
64794
  const op = paid.headers.get("X-402Mob-Operation");
64855
- if (op)
64856
- uuid3.parse(op);
64857
- if (s.operationId && op)
64858
- requireThat(s.operationId === op, "payment_operation_changed");
64795
+ if (op) uuid3.parse(op);
64796
+ if (s.operationId && op) requireThat(s.operationId === op, "payment_operation_changed");
64859
64797
  c.record(paid.status === 202 ? "payment_pending" : "payment_submitted");
64860
64798
  return { state: op ? { ...s, operationId: op } : s, waitMs: 5e3 };
64861
64799
  }
64862
64800
  if (s.stage === "result") {
64863
- if (current.state === "paid")
64864
- return { state: s, waitMs: 5e3 };
64801
+ if (current.state === "paid") return { state: s, waitMs: 5e3 };
64865
64802
  requireThat(current.result.sha256 && current.result.contentType === "application/json", "result_unavailable");
64866
64803
  const saved = await c.effect("read-result", { ticketId: s.ticketId, hash: current.result.sha256 }, "safe", async () => {
64867
64804
  const ch = await this.http.json(path + "/result-challenges", challenge2, { buyer });
@@ -64878,8 +64815,7 @@ var BuyerRuntime = class {
64878
64815
  ].join("\n");
64879
64816
  requireThat(ch.message === expected, "read_message_mismatch");
64880
64817
  const r = await this.http.bytes(path + "/result", void 0, { "X-402Mob-Challenge": ch.challengeId, "X-402Mob-Signature": await this.wallet.signMessage(expected) });
64881
- if (r.status !== 200)
64882
- throw new RuntimeFault("result_read_uncertain", true);
64818
+ if (r.status !== 200) throw new RuntimeFault("result_read_uncertain", true);
64883
64819
  requireThat(r.bytes.length <= 48 * 1024 && sha256(r.bytes) === current.result.sha256 && r.headers.get("X-402Mob-Result-SHA256") === current.result.sha256 && r.headers.get("X-402Mob-Work-Ticket") === s.ticketId, "result_integrity_mismatch");
64884
64820
  return { base64: r.bytes.toString("base64"), hash: sha256(r.bytes), verdict: evaluateTextStatistics(task.input, r.bytes) ? "accepted" : "disputed" };
64885
64821
  });
@@ -64923,7 +64859,7 @@ function newBuyerTask(text3, maxPriceUSDC, merchantId) {
64923
64859
  return workBuyerTask.parse({ id: randomUUID4(), input: { text: text3 }, maxPriceUSDC, ...merchantId !== void 0 ? { merchantId } : {} });
64924
64860
  }
64925
64861
 
64926
- // dist/runtime/server.js
64862
+ // src/runtime/server.ts
64927
64863
  var import_express = __toESM(require_express2(), 1);
64928
64864
  function createWalletApp(source) {
64929
64865
  const current = () => typeof source === "function" ? source() : source;
@@ -65003,7 +64939,7 @@ function createWalletApp(source) {
65003
64939
  return app;
65004
64940
  }
65005
64941
 
65006
- // dist/runtime/seller.js
64942
+ // src/runtime/seller.ts
65007
64943
  var sellerSettings = external_exports.object({
65008
64944
  origin: external_exports.string(),
65009
64945
  name: external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$/),
@@ -65036,8 +64972,7 @@ async function enrollSeller(store, discoverable, fetcher = fetch) {
65036
64972
  try {
65037
64973
  c = await http2.json("/v1/merchants/enrollment-challenges", schema, { wallet: account.address, name: config2.name });
65038
64974
  } catch (e) {
65039
- if (!(e instanceof RemoteHttpFault) || e.status !== 409 || e.remoteCode !== "merchant_wallet_registered")
65040
- throw e;
64975
+ if (!(e instanceof RemoteHttpFault) || e.status !== 409 || e.remoteCode !== "merchant_wallet_registered") throw e;
65041
64976
  rotate = true;
65042
64977
  c = await http2.json("/v1/merchants/credential-challenges", schema, { wallet: account.address });
65043
64978
  }
@@ -65056,7 +64991,11 @@ async function enrollSeller(store, discoverable, fetcher = fetch) {
65056
64991
  "This creates or replaces a merchant API key. It does not authorize a payment."
65057
64992
  ].join("\n");
65058
64993
  requireThat(c.message === expected, "enrollment_message_mismatch");
65059
- const result = await http2.json(rotate ? "/v1/merchants/credentials/rotate" : "/v1/merchants/enrollments", external_exports.object({ apiKey: external_exports.string().min(16).max(128), merchant: external_exports.object({ id: uuid3, payoutAddress: address }) }), { wallet: account.address, ...rotate ? {} : { name: config2.name }, challengeId: c.challengeId, signature: await account.signMessage({ message: expected }) });
64994
+ const result = await http2.json(
64995
+ rotate ? "/v1/merchants/credentials/rotate" : "/v1/merchants/enrollments",
64996
+ external_exports.object({ apiKey: external_exports.string().min(16).max(128), merchant: external_exports.object({ id: uuid3, payoutAddress: address }) }),
64997
+ { wallet: account.address, ...rotate ? {} : { name: config2.name }, challengeId: c.challengeId, signature: await account.signMessage({ message: expected }) }
64998
+ );
65060
64999
  requireThat(result.merchant.payoutAddress.toLowerCase() === account.address.toLowerCase(), "merchant_identity_mismatch");
65061
65000
  config2.apiKey = result.apiKey;
65062
65001
  config2.merchantId = result.merchant.id;
@@ -65088,15 +65027,6 @@ async function enrollSeller(store, discoverable, fetcher = fetch) {
65088
65027
  return { merchantId: config2.merchantId, address: account.address, origin: http2.origin, capability: TEXT_CAPABILITY, priceUSDC: config2.priceUSDC, discoverable };
65089
65028
  }
65090
65029
  var SellerRuntime = class {
65091
- store;
65092
- chain;
65093
- clock;
65094
- model;
65095
- name = "seller-v1";
65096
- core;
65097
- http;
65098
- config;
65099
- address;
65100
65030
  constructor(store, chain, fetcher = fetch, clock = Date.now, model) {
65101
65031
  this.store = store;
65102
65032
  this.chain = chain;
@@ -65109,6 +65039,15 @@ var SellerRuntime = class {
65109
65039
  this.http = new RuntimeHttp(this.config.origin, fetcher, this.config.apiKey);
65110
65040
  this.address = privateKeyToAccount(this.config.privateKey).address;
65111
65041
  }
65042
+ store;
65043
+ chain;
65044
+ clock;
65045
+ model;
65046
+ name = "seller-v1";
65047
+ core;
65048
+ http;
65049
+ config;
65050
+ address;
65112
65051
  discoveryStatus() {
65113
65052
  return this.store.get("seller-feed-error") ?? null;
65114
65053
  }
@@ -65123,27 +65062,23 @@ var SellerRuntime = class {
65123
65062
  last = e.sequence;
65124
65063
  }
65125
65064
  requireThat(page.nextCursor === last && (!page.hasMore || page.items.length > 0), "event_cursor_invalid");
65126
- for (const e of page.items)
65127
- this.core.create(e.ticketId, this.name, this.config.merchantId, { ticketId: e.ticketId }, { stage: "inspect", ownsClaim: false });
65065
+ for (const e of page.items) this.core.create(e.ticketId, this.name, this.config.merchantId, { ticketId: e.ticketId }, { stage: "inspect", ownsClaim: false });
65128
65066
  this.store.transaction(() => {
65129
65067
  const current = external_exports.number().parse(this.store.require("seller-event-cursor"));
65130
65068
  this.store.put("seller-event-cursor", Math.max(current, page.nextCursor));
65131
65069
  });
65132
- if (!page.hasMore)
65133
- break;
65070
+ if (!page.hasMore) break;
65134
65071
  }
65135
65072
  }
65136
65073
  async releaseExpiredSlots() {
65137
65074
  const rows = this.store.db.prepare("SELECT j.id,j.revision FROM seller_slots s JOIN jobs j ON j.id=s.job WHERE j.status='needs_attention' AND j.lease_until<=? LIMIT 10").all(this.clock());
65138
65075
  for (const row of rows) {
65139
65076
  const id = String(row.id), key = "seller-slot-check:" + id;
65140
- if ((this.store.get(key) ?? 0) > this.clock())
65141
- continue;
65077
+ if ((this.store.get(key) ?? 0) > this.clock()) continue;
65142
65078
  this.store.put(key, this.clock() + 6e4);
65143
65079
  try {
65144
65080
  const t = (await this.http.json(`/v1/agent/work-tickets/${id}`, detail)).ticket;
65145
- if (t.id !== id || t.merchantId !== this.config.merchantId || t.state !== "expired" || t.payment.operationId)
65146
- continue;
65081
+ if (t.id !== id || t.merchantId !== this.config.merchantId || t.state !== "expired" || t.payment.operationId) continue;
65147
65082
  this.store.transaction(() => {
65148
65083
  const changed = this.store.db.prepare("UPDATE jobs SET status='rejected',state=?,revision=revision+1,error=NULL WHERE id=? AND revision=? AND status='needs_attention' AND lease_until<=?").run(canonical({ stage: "done", ownsClaim: false }), id, row.revision, this.clock());
65149
65084
  if (changed.changes) {
@@ -65170,48 +65105,37 @@ var SellerRuntime = class {
65170
65105
  this.store.put("seller-feed-error", { error: faultCode(error62), nextAt: this.clock() + 6e4 });
65171
65106
  }
65172
65107
  }
65173
- for (const job of this.core.active(this.name))
65174
- if (!visited.has(job.id))
65175
- results.push(await this.core.tick(job.id, this));
65108
+ for (const job of this.core.active(this.name)) if (!visited.has(job.id)) results.push(await this.core.tick(job.id, this));
65176
65109
  return results.map((j) => ({ id: j.id, status: j.status, error: j.error, stage: sellerState.parse(j.state).stage }));
65177
65110
  }
65178
65111
  async step(c) {
65179
65112
  const s = sellerState.parse(c.job.state), id = uuid3.parse(c.job.id), path = `/v1/agent/work-tickets/${id}`;
65180
65113
  const t = (await this.http.json(path, detail)).ticket;
65181
65114
  requireThat(t.id === id && t.merchantId === this.config.merchantId, "ticket_identity_mismatch");
65182
- if (t.state === "expired")
65183
- return { state: { ...s, stage: "done" }, status: "rejected" };
65115
+ if (t.state === "expired") return { state: { ...s, stage: "done" }, status: "rejected" };
65184
65116
  if (["delivered", "accepted_by_buyer", "disputed"].includes(t.state)) {
65185
65117
  requireThat(s.outputHash && t.result.sha256 === s.outputHash, "unrecognized_delivery");
65186
65118
  return { state: { ...s, stage: "done" }, status: "complete" };
65187
65119
  }
65188
- if (t.capability !== TEXT_CAPABILITY || !textInput.safeParse(t.input).success || BigInt(t.maxPriceAtomic) < toAtomic(this.config.priceUSDC))
65189
- return { state: { ...s, stage: "done" }, status: "rejected" };
65120
+ if (t.capability !== TEXT_CAPABILITY || !textInput.safeParse(t.input).success || BigInt(t.maxPriceAtomic) < toAtomic(this.config.priceUSDC)) return { state: { ...s, stage: "done" }, status: "rejected" };
65190
65121
  requireThat(sha256(canonical(t.input)) === t.inputHash, "input_integrity_mismatch");
65191
- if (t.quote)
65192
- requireThat(quoteHash(t) === t.quote.termsHash && t.quote.amountAtomic === String(toAtomic(this.config.priceUSDC)) && t.quote.deliverable === TEXT_DELIVERABLE && t.quote.contentType === "application/json", "seller_quote_changed");
65122
+ if (t.quote) requireThat(quoteHash(t) === t.quote.termsHash && t.quote.amountAtomic === String(toAtomic(this.config.priceUSDC)) && t.quote.deliverable === TEXT_DELIVERABLE && t.quote.contentType === "application/json", "seller_quote_changed");
65193
65123
  if (s.stage === "inspect") {
65194
- if (this.model && !await this.model.admit(c, { role: "seller", capability: TEXT_CAPABILITY, input: t.input, priceUSDC: this.config.priceUSDC }))
65195
- return { state: s, status: "rejected" };
65124
+ if (this.model && !await this.model.admit(c, { role: "seller", capability: TEXT_CAPABILITY, input: t.input, priceUSDC: this.config.priceUSDC })) return { state: s, status: "rejected" };
65196
65125
  const attempted = this.store.db.prepare("SELECT key FROM actions WHERE job=? AND key='claim'").get(id);
65197
- if (t.state === "claimed" && !attempted && Date.parse(t.claimExpiresAt ?? "") > this.clock())
65198
- return { state: s, waitMs: 5e3 };
65126
+ if (t.state === "claimed" && !attempted && Date.parse(t.claimExpiresAt ?? "") > this.clock()) return { state: s, waitMs: 5e3 };
65199
65127
  requireThat(t.state === "open" || t.state === "claimed", "unrecognized_work_commitment");
65200
65128
  const slot = this.store.transaction(() => {
65201
65129
  this.store.db.prepare("DELETE FROM seller_slots WHERE job IN (SELECT id FROM jobs WHERE status IN ('complete','rejected'))").run();
65202
- if (this.store.db.prepare("SELECT job FROM seller_slots WHERE job=?").get(id))
65203
- return true;
65204
- if (Number(this.store.db.prepare("SELECT COUNT(*) n FROM seller_slots").get()?.n) >= this.config.capacity)
65205
- return false;
65130
+ if (this.store.db.prepare("SELECT job FROM seller_slots WHERE job=?").get(id)) return true;
65131
+ if (Number(this.store.db.prepare("SELECT COUNT(*) n FROM seller_slots").get()?.n) >= this.config.capacity) return false;
65206
65132
  this.store.db.prepare("INSERT INTO seller_slots VALUES(?)").run(id);
65207
65133
  return true;
65208
65134
  });
65209
- if (!slot)
65210
- return { state: s, waitMs: 5e3 };
65135
+ if (!slot) return { state: s, waitMs: 5e3 };
65211
65136
  await c.effect("claim", { id }, "safe", async () => {
65212
65137
  const fresh = (await this.http.json(path, detail)).ticket;
65213
- if (fresh.state === "claimed" && Date.parse(fresh.claimExpiresAt ?? "") > this.clock())
65214
- return { ticket: fresh };
65138
+ if (fresh.state === "claimed" && Date.parse(fresh.claimExpiresAt ?? "") > this.clock()) return { ticket: fresh };
65215
65139
  return this.http.json(path + "/claims", detail, { leaseSeconds: 600 });
65216
65140
  });
65217
65141
  return { state: { ...s, ownsClaim: true, stage: "quote" } };
@@ -65236,8 +65160,7 @@ var SellerRuntime = class {
65236
65160
  }
65237
65161
  if (s.stage === "funding") {
65238
65162
  if (t.state !== "paid") {
65239
- if (t.state !== "paying" && t.quote && Date.parse(t.quote.expiresAt) <= this.clock())
65240
- return { state: { ...s, ownsClaim: false }, status: "rejected" };
65163
+ if (t.state !== "paying" && t.quote && Date.parse(t.quote.expiresAt) <= this.clock()) return { state: { ...s, ownsClaim: false }, status: "rejected" };
65241
65164
  return { state: s, waitMs: 5e3 };
65242
65165
  }
65243
65166
  requireThat(t.quote && t.payment.operationId && t.payment.transaction, "funding_reference_missing");
@@ -65258,7 +65181,7 @@ var SellerRuntime = class {
65258
65181
  }
65259
65182
  };
65260
65183
 
65261
- // dist/runtime/model.js
65184
+ // src/runtime/model.ts
65262
65185
  var admission = external_exports.object({ decision: external_exports.enum(["proceed", "reject"]), reason: external_exports.enum(["in_scope", "out_of_scope", "insufficient_context"]) }).strict();
65263
65186
  var modelSettings = external_exports.object({
65264
65187
  model: external_exports.string().regex(/^[A-Za-z0-9_.:/-]{1,120}$/),
@@ -65267,10 +65190,6 @@ var modelSettings = external_exports.object({
65267
65190
  maxReservedTokens: external_exports.number().int().min(4096).max(1e6)
65268
65191
  }).strict();
65269
65192
  var OpenRouterModel = class {
65270
- model;
65271
- key;
65272
- fetcher;
65273
- id;
65274
65193
  constructor(model, key, fetcher = fetch) {
65275
65194
  this.model = model;
65276
65195
  this.key = key;
@@ -65278,6 +65197,10 @@ var OpenRouterModel = class {
65278
65197
  this.id = "openrouter:" + model;
65279
65198
  requireThat(key.length >= 16 && key.length < 512 && !/\s/.test(key), "invalid_model_key");
65280
65199
  }
65200
+ model;
65201
+ key;
65202
+ fetcher;
65203
+ id;
65281
65204
  async propose(context, repair) {
65282
65205
  let response;
65283
65206
  try {
@@ -65307,20 +65230,18 @@ var OpenRouterModel = class {
65307
65230
  }
65308
65231
  const reader = response.body?.getReader(), parts = [];
65309
65232
  let size5 = 0;
65310
- if (reader)
65311
- try {
65312
- for (; ; ) {
65313
- const next = await reader.read();
65314
- if (next.done)
65315
- break;
65316
- size5 += next.value.length;
65317
- requireThat(size5 <= 32768, "model_response_too_large");
65318
- parts.push(next.value);
65319
- }
65320
- } finally {
65321
- await reader.cancel().catch(() => {
65322
- });
65233
+ if (reader) try {
65234
+ for (; ; ) {
65235
+ const next = await reader.read();
65236
+ if (next.done) break;
65237
+ size5 += next.value.length;
65238
+ requireThat(size5 <= 32768, "model_response_too_large");
65239
+ parts.push(next.value);
65323
65240
  }
65241
+ } finally {
65242
+ await reader.cancel().catch(() => {
65243
+ });
65244
+ }
65324
65245
  try {
65325
65246
  const parsed = external_exports.object({
65326
65247
  choices: external_exports.array(external_exports.object({ finish_reason: external_exports.literal("stop"), message: external_exports.object({ content: external_exports.string().max(4096) }) })).min(1).max(1),
@@ -65333,15 +65254,15 @@ var OpenRouterModel = class {
65333
65254
  }
65334
65255
  };
65335
65256
  var ModelGate = class {
65336
- store;
65337
- adapter;
65338
- limits;
65339
65257
  constructor(store, adapter, limits) {
65340
65258
  this.store = store;
65341
65259
  this.adapter = adapter;
65342
65260
  this.limits = limits;
65343
65261
  external_exports.object({ maxCalls: external_exports.number().int().positive(), maxReservedTokens: external_exports.number().int().positive() }).strict().parse(limits);
65344
65262
  }
65263
+ store;
65264
+ adapter;
65265
+ limits;
65345
65266
  async admit(c, context) {
65346
65267
  const input2 = { adapter: this.adapter.id, context }, encoded = canonical(input2);
65347
65268
  requireThat(Buffer.byteLength(encoded) <= 2e4, "model_context_too_large");
@@ -65395,28 +65316,37 @@ var ModelGate = class {
65395
65316
  return decision.decision === "proceed";
65396
65317
  }
65397
65318
  };
65398
- function loadModelGate(store, file2) {
65319
+ function loadModelGate(store, file2, fetcher = fetch) {
65399
65320
  const prior = store.get("model-configuration");
65400
65321
  if (!file2) {
65401
65322
  requireThat(!prior, "model_configuration_required");
65402
65323
  return void 0;
65403
65324
  }
65404
65325
  const settings = modelSettings.parse(readPrivateJson(file2)), binding = sha256(canonical(settings));
65405
- if (prior)
65406
- requireThat(binding === prior, "model_configuration_changed");
65407
- else {
65408
- requireThat(Number(store.db.prepare("SELECT COUNT(*) n FROM jobs").get()?.n) === 0, "model_configuration_requires_new_runtime");
65409
- store.put("model-configuration", binding);
65410
- }
65326
+ if (prior) requireThat(binding === prior, "model_configuration_changed");
65411
65327
  const secret2 = external_exports.object({ apiKey: external_exports.string() }).strict().parse(readPrivateJson(settings.keyFile));
65412
- return new ModelGate(store, new OpenRouterModel(settings.model, secret2.apiKey), settings);
65328
+ const gate = new ModelGate(
65329
+ store,
65330
+ new OpenRouterModel(settings.model, secret2.apiKey, fetcher),
65331
+ { maxCalls: settings.maxCalls, maxReservedTokens: settings.maxReservedTokens }
65332
+ );
65333
+ store.transaction(() => {
65334
+ const current = store.get("model-configuration");
65335
+ if (current) requireThat(binding === current, "model_configuration_changed");
65336
+ else {
65337
+ requireThat(Number(store.db.prepare("SELECT COUNT(*) n FROM jobs").get()?.n) === 0, "model_configuration_requires_new_runtime");
65338
+ store.put("model-configuration", binding);
65339
+ }
65340
+ });
65341
+ return gate;
65413
65342
  }
65414
65343
 
65415
- // dist/runtime/web-launch.js
65344
+ // src/runtime/web-launch.ts
65416
65345
  import { createInterface } from "node:readline";
65417
65346
 
65418
- // dist/runtime/web-contract.js
65347
+ // src/runtime/web-contract.ts
65419
65348
  var WEB_WALLET_ORIGIN = "https://wallet.evidence.contact";
65349
+ var WALLET_CONSOLE_PROTOCOL = "402mob.wallet-console.v2";
65420
65350
  var walletWebCsp = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self' http://127.0.0.1:* http://localhost:*; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; object-src 'none'";
65421
65351
  var emptyWebInput = external_exports.object({}).strict();
65422
65352
  var walletCreateInput = external_exports.object({ maxTotalUSDC: amount.nullable().optional() }).strict();
@@ -65430,7 +65360,7 @@ var webCredential = external_exports.object({
65430
65360
  policy: delegationPolicy,
65431
65361
  gateway: external_exports.string().url()
65432
65362
  }).strict();
65433
- var webDelegation = walletStatus.extend({ id: uuid3, state: external_exports.enum(["active", "expired", "revoked"]), credentialRecoverable: external_exports.boolean().describe("True for a non-revoked web-issued credential. Recovery preserves expiry; an expired credential can only access existing jobs. CLI-issued or revoked credentials are not recoverable.") }).strict();
65363
+ var webDelegation = walletStatus.extend({ id: uuid3, state: external_exports.enum(["active", "expired", "revoked"]), credentialRecoverable: external_exports.boolean().describe("True for a non-revoked credential with owner recovery support. Recovery preserves expiry; an expired credential can only access existing jobs. Legacy random CLI credentials and revoked credentials are not recoverable.") }).strict();
65434
65364
  var webActivity = buyerView.omit({ result: true, resultBase64: true }).extend({ delegationId: uuid3 }).strict();
65435
65365
  var webState = external_exports.object({
65436
65366
  initialized: external_exports.boolean(),
@@ -65442,19 +65372,12 @@ var webState = external_exports.object({
65442
65372
  activity: external_exports.array(webActivity).max(50)
65443
65373
  }).strict();
65444
65374
  var webBalance = external_exports.object({ address, network: external_exports.literal(NETWORK), asset: external_exports.literal(USDC), balanceAtomic: external_exports.string().regex(/^\d+$/), observedAt: date5 }).strict();
65445
- var webHealth = external_exports.object({ protocol: external_exports.literal("402mob.owner-wallet-web.v1"), network: external_exports.literal(NETWORK), asset: external_exports.literal(USDC) }).strict();
65375
+ var webHealth = external_exports.object({ protocol: external_exports.literal("402mob.owner-wallet-web.v1"), consoleProtocol: external_exports.literal(WALLET_CONSOLE_PROTOCOL), network: external_exports.literal(NETWORK), asset: external_exports.literal(USDC) }).strict();
65446
65376
  var webMerchant = external_exports.object({ id: uuid3, name: external_exports.string(), payoutAddress: address }).strict();
65447
65377
  var webError = external_exports.object({ error: external_exports.string() }).strict();
65448
65378
 
65449
- // dist/runtime/web-service.js
65379
+ // src/runtime/web-service.ts
65450
65380
  var WalletWebService = class {
65451
- store;
65452
- chain;
65453
- fetcher;
65454
- clock;
65455
- runtime;
65456
- serviceOrigin;
65457
- agentGateway;
65458
65381
  constructor(store, chain, settings, fetcher = fetch, clock = Date.now) {
65459
65382
  this.store = store;
65460
65383
  this.chain = chain;
@@ -65465,14 +65388,21 @@ var WalletWebService = class {
65465
65388
  this.agentGateway = origin(settings.agentGateway);
65466
65389
  const gateway = new URL(this.agentGateway);
65467
65390
  requireThat(gateway.protocol === "http:" && ["127.0.0.1", "localhost"].includes(gateway.hostname), "local_gateway_required");
65468
- loadModelGate(store, void 0);
65469
- if (store.get("wallet"))
65470
- this.open();
65391
+ this.model = loadModelGate(store, settings.modelConfig, fetcher);
65392
+ if (store.get("wallet")) this.open();
65471
65393
  }
65394
+ store;
65395
+ chain;
65396
+ fetcher;
65397
+ clock;
65398
+ runtime;
65399
+ serviceOrigin;
65400
+ agentGateway;
65401
+ model;
65472
65402
  open() {
65473
65403
  const wallet2 = new DelegatedWallet(this.store, this.chain, this.clock);
65474
65404
  requireThat(wallet2.origin === this.serviceOrigin, "wallet_service_origin_changed");
65475
- this.runtime = new BuyerRuntime(wallet2, this.fetcher);
65405
+ this.runtime = new BuyerRuntime(wallet2, this.fetcher, this.model);
65476
65406
  }
65477
65407
  ready() {
65478
65408
  requireThat(this.runtime, "wallet_not_created");
@@ -65480,8 +65410,7 @@ var WalletWebService = class {
65480
65410
  }
65481
65411
  create(input2) {
65482
65412
  const settings = walletCreateInput.parse(input2);
65483
- if (this.runtime)
65484
- requireThat(this.runtime.wallet.limitUSDC === (settings.maxTotalUSDC ?? null), "wallet_already_exists");
65413
+ if (this.runtime) requireThat(this.runtime.wallet.limitUSDC === (settings.maxTotalUSDC ?? null), "wallet_already_exists");
65485
65414
  else {
65486
65415
  DelegatedWallet.initialize(this.store, { origin: this.serviceOrigin, maxTotalUSDC: settings.maxTotalUSDC ?? null });
65487
65416
  this.open();
@@ -65532,18 +65461,16 @@ var WalletWebService = class {
65532
65461
  return this.state();
65533
65462
  }
65534
65463
  async merchant(id) {
65535
- const response = await new RuntimeHttp(this.serviceOrigin, this.fetcher).json("/v1/merchants/" + uuid3.parse(id), external_exports.object({ merchant: webMerchant.passthrough() }));
65464
+ const response = await new RuntimeHttp(this.serviceOrigin, this.fetcher).json("/v1/merchants/" + uuid3.parse(id) + "?includeOffers=false", external_exports.object({ merchant: webMerchant.passthrough() }));
65536
65465
  requireThat(response.merchant.id === id, "merchant_identity_mismatch");
65537
65466
  return webMerchant.parse({ id: response.merchant.id, name: response.merchant.name, payoutAddress: response.merchant.payoutAddress });
65538
65467
  }
65539
65468
  async tick() {
65540
- if (this.runtime)
65541
- for (const job of this.runtime.core.active(this.runtime.name))
65542
- await this.runtime.tick(job.id);
65469
+ if (this.runtime) for (const job of this.runtime.core.active(this.runtime.name)) await this.runtime.tick(job.id);
65543
65470
  }
65544
65471
  };
65545
65472
 
65546
- // dist/runtime/web-server.js
65473
+ // src/runtime/web-server.ts
65547
65474
  var import_express2 = __toESM(require_express2(), 1);
65548
65475
  import { randomBytes as randomBytes4 } from "node:crypto";
65549
65476
  import { fileURLToPath } from "node:url";
@@ -65564,12 +65491,8 @@ function createWalletOwnerApp(service, settings = {}) {
65564
65491
  requireThat(publicUrl.protocol === "https:" || publicUrl.protocol === "http:" && ["127.0.0.1", "localhost"].includes(publicUrl.hostname), "invalid_wallet_web_origin");
65565
65492
  const pairs = /* @__PURE__ */ new Map(), sessions = /* @__PURE__ */ new Map();
65566
65493
  const cleanup = () => {
65567
- for (const [key, expiry] of pairs)
65568
- if (expiry <= clock())
65569
- pairs.delete(key);
65570
- for (const [key, session] of sessions)
65571
- if (session.expiresAt <= clock())
65572
- sessions.delete(key);
65494
+ for (const [key, expiry] of pairs) if (expiry <= clock()) pairs.delete(key);
65495
+ for (const [key, session] of sessions) if (session.expiresAt <= clock()) sessions.delete(key);
65573
65496
  };
65574
65497
  const issuePair = () => {
65575
65498
  cleanup();
@@ -65614,8 +65537,7 @@ function createWalletOwnerApp(service, settings = {}) {
65614
65537
  return;
65615
65538
  }
65616
65539
  res.set({ "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Headers": "Authorization, Content-Type, X-402Mob-Wallet", "Access-Control-Max-Age": "0" });
65617
- if (req.get("Access-Control-Request-Private-Network") === "true")
65618
- res.set("Access-Control-Allow-Private-Network", "true");
65540
+ if (req.get("Access-Control-Request-Private-Network") === "true") res.set("Access-Control-Allow-Private-Network", "true");
65619
65541
  res.status(204).end();
65620
65542
  return;
65621
65543
  }
@@ -65627,8 +65549,7 @@ function createWalletOwnerApp(service, settings = {}) {
65627
65549
  res.status(400).json({ error: "unexpected_query" });
65628
65550
  return;
65629
65551
  }
65630
- if (bucket.until <= clock())
65631
- bucket = { count: 0, until: clock() + 6e4 };
65552
+ if (bucket.until <= clock()) bucket = { count: 0, until: clock() + 6e4 };
65632
65553
  if (++bucket.count > 240) {
65633
65554
  res.set("Retry-After", "60").status(429).json({ error: "wallet_rate_limited" });
65634
65555
  return;
@@ -65644,13 +65565,12 @@ function createWalletOwnerApp(service, settings = {}) {
65644
65565
  cleanup();
65645
65566
  next();
65646
65567
  });
65647
- for (const [path, [file2, type]] of assets)
65648
- app.get(path, (_req, res) => {
65649
- res.type(type).sendFile(file2, { root: assetRoot, dotfiles: "deny" });
65650
- });
65568
+ for (const [path, [file2, type]] of assets) app.get(path, (_req, res) => {
65569
+ res.type(type).sendFile(file2, { root: assetRoot, dotfiles: "deny" });
65570
+ });
65651
65571
  app.use(import_express2.default.json({ limit: "16kb", strict: true, inflate: false }));
65652
65572
  app.get("/api/healthz", (_req, res) => {
65653
- res.json({ protocol: "402mob.owner-wallet-web.v1", network: NETWORK, asset: USDC });
65573
+ res.json(webHealth.parse({ protocol: "402mob.owner-wallet-web.v1", consoleProtocol: WALLET_CONSOLE_PROTOCOL, network: NETWORK, asset: USDC }));
65654
65574
  });
65655
65575
  app.post("/api/session", (req, res) => {
65656
65576
  const { code } = webSessionInput.parse(req.body), key = sha256(code), expiry = pairs.get(key);
@@ -65735,13 +65655,13 @@ function createWalletOwnerApp(service, settings = {}) {
65735
65655
  } };
65736
65656
  }
65737
65657
 
65738
- // dist/runtime/listener.js
65658
+ // src/runtime/listener.ts
65739
65659
  var RuntimeListenFault = class extends RuntimeFault {
65740
- port;
65741
65660
  constructor(port, code) {
65742
65661
  super(code);
65743
65662
  this.port = port;
65744
65663
  }
65664
+ port;
65745
65665
  };
65746
65666
  function listenLoopback(app, port) {
65747
65667
  return new Promise((resolve3, reject) => {
@@ -65752,12 +65672,9 @@ function listenLoopback(app, port) {
65752
65672
  };
65753
65673
  const failed = (error62) => {
65754
65674
  server.off("listening", ready);
65755
- if (error62.code === "EADDRINUSE")
65756
- reject(new RuntimeListenFault(port, "local_port_in_use"));
65757
- else if (error62.code === "EACCES" || error62.code === "EPERM")
65758
- reject(new RuntimeListenFault(port, "local_port_permission_denied"));
65759
- else
65760
- reject(error62);
65675
+ if (error62.code === "EADDRINUSE") reject(new RuntimeListenFault(port, "local_port_in_use"));
65676
+ else if (error62.code === "EACCES" || error62.code === "EPERM") reject(new RuntimeListenFault(port, "local_port_permission_denied"));
65677
+ else reject(error62);
65761
65678
  };
65762
65679
  server.once("error", failed);
65763
65680
  server.once("listening", ready);
@@ -65771,11 +65688,15 @@ function listenerDiagnostic(error62) {
65771
65688
  };
65772
65689
  }
65773
65690
 
65774
- // dist/runtime/web-launch.js
65691
+ // src/runtime/web-launch.ts
65775
65692
  async function runWalletWeb(store, chain, settings) {
65776
65693
  requireThat(settings.port !== settings.webPort, "wallet_ports_must_differ");
65777
65694
  const agentGateway = `http://127.0.0.1:${settings.port}`, ownerGateway = `http://127.0.0.1:${settings.webPort}`;
65778
- const service = new WalletWebService(store, chain, { serviceOrigin: settings.serviceOrigin, agentGateway });
65695
+ const service = new WalletWebService(store, chain, {
65696
+ serviceOrigin: settings.serviceOrigin,
65697
+ agentGateway,
65698
+ ...settings.modelConfig ? { modelConfig: settings.modelConfig } : {}
65699
+ });
65779
65700
  const owner = createWalletOwnerApp(service, { webOrigin: settings.webOrigin });
65780
65701
  const agent = createWalletApp(() => service.runtime);
65781
65702
  const servers = [];
@@ -65823,24 +65744,28 @@ async function runWalletWeb(store, chain, settings) {
65823
65744
  }
65824
65745
  }
65825
65746
 
65826
- // dist/runtime/cli.js
65747
+ // src/runtime/cli.ts
65827
65748
  var usage = `402Mob local buyer/seller runtime (Base USDC)
65828
65749
 
65829
65750
  Owner commands:
65830
65751
  wallet init --dir DIR --origin https://evidence.contact [--max-usdc 1]
65831
65752
  wallet status --dir DIR
65832
- wallet grant --dir DIR --file policy.json --out credential.json
65753
+ wallet grant --dir DIR --name "Agent" [--max-usdc 1] [--out credential.json]
65754
+ Optional advanced policy: --file policy.json instead of --name.
65755
+ --gateway URL sets the private connection destination (default http://127.0.0.1:4031).
65833
65756
  wallet limit --dir DIR --file limit-update.json
65834
65757
  wallet allocation --dir DIR --id DELEGATION_UUID --file allocation-update.json
65835
65758
  wallet revoke --dir DIR --id DELEGATION_UUID
65836
65759
  wallet retry --dir DIR --id JOB_UUID
65837
65760
  wallet serve --dir DIR [--port 4031] [--rpc https://mainnet.base.org]
65838
65761
  wallet web --dir DIR [--port 4031] [--web-port 4032]
65839
- [--web-origin https://wallet.evidence.contact] [--origin https://evidence.contact]
65762
+ [--web-origin https://wallet.evidence.contact] [--origin https://evidence.contact] [--model-config FILE]
65840
65763
  Starts the owner-controlled signer; open its one-use pairing link to create
65841
- a USDC wallet, inspect funding, grant spending and download agent credentials.
65764
+ a USDC wallet, inspect funding and copy the agent connection. Limits and file export are optional.
65842
65765
 
65843
- Agent commands (only a delegation credential, never the wallet directory):
65766
+ Agent commands (MOB_RUNTIME_TOKEN in the environment, or optional --credential FILE):
65767
+ buyer check
65768
+ buyer resources
65844
65769
  buyer check --credential credential.json
65845
65770
  buyer workers --credential credential.json [--query TEXT] [--limit 20] [--cursor 0]
65846
65771
  buyer resources --credential credential.json [--query TEXT] [--limit 20] [--cursor 0]
@@ -65850,7 +65775,9 @@ Agent commands (only a delegation credential, never the wallet directory):
65850
65775
  buyer submit --file request.json --credential credential.json [--gateway http://127.0.0.1:4031]
65851
65776
  buyer status --id JOB_UUID --credential credential.json [--gateway ...]
65852
65777
  buyer run --file request.json --credential credential.json [--gateway ...]
65853
- Gateway: explicit --gateway, then the downloaded credential, then localhost:4031.
65778
+ Connection: MOB_RUNTIME_TOKEN and optional MOB_RUNTIME_GATEWAY, or --credential FILE.
65779
+ Use --credential - to read a connection JSON from stdin. No config download is required.
65780
+ Gateway: explicit --gateway, then the selected connection, then localhost:4031.
65854
65781
  For prepared artifacts, --share-url PINNED_PAYMENT_LINK replaces --merchant-id and --offer-id.
65855
65782
  For text work, omit --merchant-id only when the delegation already fixes a seller.
65856
65783
 
@@ -65864,7 +65791,7 @@ Keep directories and credentials private. Funding is an owner transfer of native
65864
65791
  Base USDC to the generated address; creating a wallet or grant moves no money.
65865
65792
  The local wallet enforces policy in software. It is not an on-chain session wallet.
65866
65793
  Use the original request file and directories for retries. No command resets a ledger.
65867
- Optional model admission: add --model-config FILE to wallet serve or seller once/run.
65794
+ Optional model admission: add --model-config FILE to wallet serve/web or seller once/run.
65868
65795
  It sends task input to OpenRouter and incurs inference costs. Omit it for deterministic execution.
65869
65796
  `;
65870
65797
  var { positionals, values: v } = parseArgs({ allowPositionals: true, strict: true, options: {
@@ -65929,7 +65856,16 @@ async function main() {
65929
65856
  print({ id: task2.id, requestFile: resolve2(needed("out")) });
65930
65857
  return;
65931
65858
  }
65932
- const credential = external_exports.object({ id: uuid3, token: external_exports.string().regex(/^mobrt_[0-9a-f]{64}$/), gateway: external_exports.string().optional() }).parse(readPrivateJson(needed("credential")));
65859
+ const schema = external_exports.object({ id: uuid3.optional(), token: external_exports.string().regex(/^mobrt_[0-9a-f]{64}$/), gateway: external_exports.string().optional() });
65860
+ let credential;
65861
+ if (v.credential) {
65862
+ const input2 = v.credential === "-" ? readFileSync2(0, "utf8") : void 0;
65863
+ if (input2 !== void 0) requireThat(Buffer.byteLength(input2) <= 65536, "input_file_too_large");
65864
+ credential = schema.extend({ id: uuid3 }).parse(input2 === void 0 ? readPrivateJson(v.credential) : JSON.parse(input2));
65865
+ } else {
65866
+ requireThat(process.env.MOB_RUNTIME_TOKEN, "agent_connection_required");
65867
+ credential = schema.parse({ token: process.env.MOB_RUNTIME_TOKEN, gateway: process.env.MOB_RUNTIME_GATEWAY });
65868
+ }
65933
65869
  const gateway = origin(v.gateway ?? credential.gateway ?? "http://127.0.0.1:4031");
65934
65870
  if (!v.gateway) {
65935
65871
  const target = new URL(gateway);
@@ -65938,7 +65874,7 @@ async function main() {
65938
65874
  const client = new RuntimeHttp(gateway, fetch, credential.token);
65939
65875
  const response = external_exports.object({ id: uuid3, status: external_exports.enum(["active", "complete", "rejected", "needs_attention"]), stage: external_exports.string(), error: external_exports.string().nullable() }).passthrough();
65940
65876
  const status = await client.json("/v1/status", external_exports.object({ delegationId: uuid3 }));
65941
- requireThat(status.delegationId === credential.id, "credential_identity_mismatch");
65877
+ requireThat(!credential.id || status.delegationId === credential.id, "credential_identity_mismatch");
65942
65878
  if (command === "check") {
65943
65879
  print({ connected: true, gateway, capabilities: ["text-statistics-v1", "prepared-artifact-v1"], spending: await client.json("/v1/status", spendingStatus) });
65944
65880
  return;
@@ -65970,16 +65906,13 @@ async function main() {
65970
65906
  const task = buyerTask.parse(readPrivateJson(needed("file")));
65971
65907
  let result = await client.json("/v1/tasks", response, task);
65972
65908
  print(result);
65973
- if (command === "submit")
65974
- return;
65909
+ if (command === "submit") return;
65975
65910
  for (let i = 0; i < 180 && !stopped && result.status === "active"; i++) {
65976
65911
  await delay(5e3);
65977
65912
  result = await client.json("/v1/tasks/" + task.id, response);
65978
- if (result.status !== "active" || i % 12 === 0)
65979
- print(result);
65913
+ if (result.status !== "active" || i % 12 === 0) print(result);
65980
65914
  }
65981
- if (result.status === "active")
65982
- print({ id: task.id, next: "Keep the same request file. The wallet service retains and continues this job; use buyer status." });
65915
+ if (result.status === "active") print({ id: task.id, next: "Keep the same request file. The wallet service retains and continues this job; use buyer status." });
65983
65916
  return;
65984
65917
  }
65985
65918
  requireThat(role === "wallet" || role === "seller", "unknown_role");
@@ -65989,7 +65922,6 @@ async function main() {
65989
65922
  try {
65990
65923
  const chain = new BaseUsdcReader(v.rpc);
65991
65924
  if (role === "wallet" && command === "web") {
65992
- requireThat(!v["model-config"], "web_model_configuration_unsupported");
65993
65925
  const port2 = external_exports.coerce.number().int().min(1).max(65535).parse(v.port ?? "4031");
65994
65926
  const webPort = external_exports.coerce.number().int().min(1).max(65535).parse(v["web-port"] ?? "4032");
65995
65927
  const existing = store.get("wallet");
@@ -65997,6 +65929,7 @@ async function main() {
65997
65929
  serviceOrigin: v.origin ?? existing?.origin ?? "https://evidence.contact",
65998
65930
  port: port2,
65999
65931
  webPort,
65932
+ ...v["model-config"] ? { modelConfig: v["model-config"] } : {},
66000
65933
  webOrigin: v["web-origin"] ?? WEB_WALLET_ORIGIN,
66001
65934
  stopped: () => stopped,
66002
65935
  print
@@ -66005,8 +65938,7 @@ async function main() {
66005
65938
  }
66006
65939
  if (role === "seller") {
66007
65940
  if (command === "init") {
66008
- if (!store.get("seller"))
66009
- initializeSeller(store, { origin: v.origin ?? "https://evidence.contact", name: needed("name"), priceUSDC: needed("price-usdc"), capacity: 1 });
65941
+ if (!store.get("seller")) initializeSeller(store, { origin: v.origin ?? "https://evidence.contact", name: needed("name"), priceUSDC: needed("price-usdc"), capacity: 1 });
66010
65942
  else {
66011
65943
  const saved = external_exports.object({ origin: external_exports.string(), name: external_exports.string(), priceUSDC: external_exports.string() }).parse(store.require("seller"));
66012
65944
  requireThat((!v.origin || origin(v.origin) === saved.origin) && (!v.name || v.name === saved.name) && (!v["price-usdc"] || v["price-usdc"] === saved.priceUSDC), "seller_settings_changed");
@@ -66027,15 +65959,12 @@ async function main() {
66027
65959
  print(await seller.sync());
66028
65960
  failures = 0;
66029
65961
  const discovery = seller.discoveryStatus();
66030
- if (discovery)
66031
- print({ ...discovery, next: "retry_discovery_existing_jobs_continue" });
65962
+ if (discovery) print({ ...discovery, next: "retry_discovery_existing_jobs_continue" });
66032
65963
  } catch (e) {
66033
- if (command === "once" || !(e instanceof RuntimeFault) || !e.retryable || ++failures >= 4)
66034
- throw e;
65964
+ if (command === "once" || !(e instanceof RuntimeFault) || !e.retryable || ++failures >= 4) throw e;
66035
65965
  print({ error: e.code, next: "retry_feed", failures });
66036
65966
  }
66037
- if (command === "once")
66038
- break;
65967
+ if (command === "once") break;
66039
65968
  await delay(failures ? 6e4 : 5e3);
66040
65969
  } while (!stopped);
66041
65970
  return;
@@ -66058,16 +65987,21 @@ async function main() {
66058
65987
  return;
66059
65988
  }
66060
65989
  if (command === "grant") {
66061
- const file2 = needed("out");
66062
- requireThat(!existsSync2(file2), "credential_file_exists");
66063
- const grant = wallet2.grant(readJson(needed("file")));
66064
- try {
66065
- out(file2, grant);
66066
- } catch (e) {
66067
- wallet2.revoke(grant.id);
66068
- throw e;
66069
- }
66070
- print({ delegationId: grant.id, credentialFile: resolve2(file2), wallet: wallet2.address, policy: grant.policy });
65990
+ const file2 = v.out;
65991
+ if (file2) requireThat(!existsSync2(file2), "credential_file_exists");
65992
+ requireThat(!v.file || !v.name && !v["max-usdc"], "choose_policy_file_or_name");
65993
+ const gateway = origin(v.gateway ?? "http://127.0.0.1:4031");
65994
+ const grant = wallet2.grant(v.file ? readJson(v.file) : { name: needed("name"), ...v["max-usdc"] ? { maxTotalUSDC: v["max-usdc"] } : {} }, randomUUID5());
65995
+ const connection = { ...grant, gateway };
65996
+ if (file2) {
65997
+ try {
65998
+ out(file2, connection);
65999
+ } catch (e) {
66000
+ wallet2.revoke(grant.id);
66001
+ throw e;
66002
+ }
66003
+ print({ delegationId: grant.id, credentialFile: resolve2(file2), wallet: wallet2.address, policy: grant.policy });
66004
+ } else print(connection);
66071
66005
  return;
66072
66006
  }
66073
66007
  if (command === "revoke") {
@@ -66088,8 +66022,7 @@ async function main() {
66088
66022
  try {
66089
66023
  while (!stopped) {
66090
66024
  for (const job of buyer.core.active(buyer.name)) {
66091
- if (stopped)
66092
- break;
66025
+ if (stopped) break;
66093
66026
  await buyer.tick(job.id);
66094
66027
  }
66095
66028
  await delay(1e3);