402mob-runtime 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  }
@@ -64277,15 +64241,15 @@ var RuntimeCatalog = class {
64277
64241
  }
64278
64242
  };
64279
64243
 
64280
- // dist/runtime/core.js
64244
+ // src/runtime/core.ts
64281
64245
  import { randomUUID as randomUUID3 } from "node:crypto";
64282
64246
  var RuntimeCore = class {
64283
- store;
64284
- clock;
64285
64247
  constructor(store, clock = Date.now) {
64286
64248
  this.store = store;
64287
64249
  this.clock = clock;
64288
64250
  }
64251
+ store;
64252
+ clock;
64289
64253
  create(id, profile, owner, input2, state2) {
64290
64254
  return this.store.transaction(() => {
64291
64255
  const existing = this.get(id);
@@ -64300,8 +64264,7 @@ var RuntimeCore = class {
64300
64264
  }
64301
64265
  get(id) {
64302
64266
  const r = this.store.db.prepare("SELECT * FROM jobs WHERE id=?").get(id);
64303
- if (!r)
64304
- return void 0;
64267
+ if (!r) return void 0;
64305
64268
  return {
64306
64269
  id: String(r.id),
64307
64270
  profile: String(r.profile),
@@ -64348,12 +64311,10 @@ var RuntimeCore = class {
64348
64311
  const claimed = this.store.transaction(() => {
64349
64312
  const j2 = this.get(id);
64350
64313
  requireThat(j2 && j2.profile === profile.name, "job_profile_mismatch");
64351
- if (j2.status !== "active" || j2.nextAt > now)
64352
- return false;
64314
+ if (j2.status !== "active" || j2.nextAt > now) return false;
64353
64315
  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
64316
  });
64355
- if (!claimed)
64356
- return this.get(id);
64317
+ if (!claimed) return this.get(id);
64357
64318
  const assertLease = () => {
64358
64319
  const r = this.store.db.prepare("SELECT lease,lease_until FROM jobs WHERE id=?").get(id);
64359
64320
  requireThat(r?.lease === lease && Number(r.lease_until) > this.clock() + 2e4, "runtime_lease_lost");
@@ -64372,8 +64333,7 @@ var RuntimeCore = class {
64372
64333
  const prior = this.store.db.prepare("SELECT * FROM actions WHERE job=? AND key=?").get(id, key);
64373
64334
  if (prior) {
64374
64335
  requireThat(prior.input_hash === hash5 && prior.replay === replay, "action_terms_changed");
64375
- if (prior.status === "complete")
64376
- return JSON.parse(String(prior.result));
64336
+ if (prior.status === "complete") return JSON.parse(String(prior.result));
64377
64337
  requireThat(replay === "safe", "uncertain_nonreplayable_action");
64378
64338
  requireThat(Number(prior.attempts) < 4, "action_retry_limit");
64379
64339
  }
@@ -64403,7 +64363,7 @@ var RuntimeCore = class {
64403
64363
  }
64404
64364
  };
64405
64365
 
64406
- // dist/runtime/artifact.js
64366
+ // src/runtime/artifact.ts
64407
64367
  var artifactTask = external_exports.object({
64408
64368
  kind: external_exports.literal("prepared_artifact"),
64409
64369
  id: uuid3,
@@ -64424,11 +64384,6 @@ var state = external_exports.object({
64424
64384
  transaction: external_exports.string().regex(/^0x[0-9a-fA-F]{64}$/).optional()
64425
64385
  }).strict();
64426
64386
  var ArtifactRuntime = class {
64427
- wallet;
64428
- model;
64429
- core;
64430
- http;
64431
- catalog;
64432
64387
  constructor(wallet2, fetcher = fetch, model) {
64433
64388
  this.wallet = wallet2;
64434
64389
  this.model = model;
@@ -64436,6 +64391,11 @@ var ArtifactRuntime = class {
64436
64391
  this.http = new RuntimeHttp(wallet2.origin, fetcher);
64437
64392
  this.catalog = new RuntimeCatalog(wallet2, fetcher);
64438
64393
  }
64394
+ wallet;
64395
+ model;
64396
+ core;
64397
+ http;
64398
+ catalog;
64439
64399
  create(delegation, value) {
64440
64400
  const task = artifactTask.parse(value), old = this.core.get(task.id);
64441
64401
  if (old) {
@@ -64446,7 +64406,8 @@ var ArtifactRuntime = class {
64446
64406
  const p = this.wallet.assertActive(delegation);
64447
64407
  requireThat(!p.merchantId || p.merchantId === task.merchantId, "merchant_outside_delegation");
64448
64408
  requireThat(!p.capability || p.capability === "prepared-artifact-v1", "capability_outside_delegation");
64449
- requireThat(toAtomic(task.maxPriceUSDC) <= toAtomic(p.maxPerPaymentUSDC ?? p.maxTotalUSDC), "task_exceeds_delegation");
64409
+ const cap = p.maxPerPaymentUSDC ?? p.maxTotalUSDC;
64410
+ requireThat(!cap || toAtomic(task.maxPriceUSDC) <= toAtomic(cap), "task_exceeds_delegation");
64450
64411
  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
64412
  requireThat(Number(this.wallet.store.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status='active'").get()?.n) < 100, "wallet_task_capacity");
64452
64413
  this.core.create(task.id, "buyer-v1", delegation, { ...task, delegation, deadline: new Date(this.wallet.clock() + 864e5).toISOString() }, { stage: "create" });
@@ -64493,8 +64454,7 @@ var ArtifactRuntime = class {
64493
64454
  const p = this.wallet.assertActive(task.delegation), inspected = await this.catalog.inspect(task.merchantId, task.offerId), terms2 = inspected.terms;
64494
64455
  requireThat(inspected.termsHash === task.termsHash, "offer_terms_changed");
64495
64456
  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" };
64457
+ 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
64458
  return { state: { ...s, terms: terms2, stage: "pay" } };
64499
64459
  }
64500
64460
  requireThat(s.terms, "artifact_terms_missing");
@@ -64520,8 +64480,7 @@ var ArtifactRuntime = class {
64520
64480
  }
64521
64481
  const op = uuid3.parse(r.headers.get("X-402Mob-Operation"));
64522
64482
  requireThat(!s.operationId || s.operationId === op, "payment_operation_changed");
64523
- if (r.status === 202)
64524
- return { state: { ...s, operationId: op }, waitMs: 5e3 };
64483
+ if (r.status === 202) return { state: { ...s, operationId: op }, waitMs: 5e3 };
64525
64484
  const proof2 = digest.parse(r.headers.get("X-402Mob-Artifact-Proof"));
64526
64485
  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
64486
  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 +64509,15 @@ var ArtifactRuntime = class {
64550
64509
  });
64551
64510
  return { state: { ...s, stage: "done" }, status: "complete" };
64552
64511
  }
64553
- if (s.stage !== "done")
64554
- throw new RuntimeFault("artifact_stage_invalid");
64512
+ if (s.stage !== "done") throw new RuntimeFault("artifact_stage_invalid");
64555
64513
  return { state: s, status: "complete" };
64556
64514
  }
64557
64515
  };
64558
64516
 
64559
- // dist/runtime/buyer.js
64517
+ // src/runtime/buyer.ts
64560
64518
  import { randomUUID as randomUUID4 } from "node:crypto";
64561
64519
 
64562
- // dist/runtime/protocol.js
64520
+ // src/runtime/protocol.ts
64563
64521
  var challenge2 = external_exports.object({ challengeId: uuid3, message: external_exports.string().max(1e4), expiresAt: date5 });
64564
64522
  var proof = challenge2.extend({ signature });
64565
64523
  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 +64572,7 @@ function quoteHash(t) {
64614
64572
  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
64573
  }
64616
64574
 
64617
- // dist/runtime/buyer.js
64575
+ // src/runtime/buyer.ts
64618
64576
  var workBuyerTask = external_exports.object({
64619
64577
  id: uuid3,
64620
64578
  input: textInput,
@@ -64654,13 +64612,6 @@ var stateSchema = external_exports.object({
64654
64612
  verdict: external_exports.enum(["accepted", "disputed"]).optional()
64655
64613
  }).strict();
64656
64614
  var BuyerRuntime = class {
64657
- wallet;
64658
- model;
64659
- name = "buyer-v1";
64660
- core;
64661
- http;
64662
- artifacts;
64663
- catalog;
64664
64615
  constructor(wallet2, fetcher = fetch, model) {
64665
64616
  this.wallet = wallet2;
64666
64617
  this.model = model;
@@ -64669,10 +64620,16 @@ var BuyerRuntime = class {
64669
64620
  this.artifacts = new ArtifactRuntime(wallet2, fetcher, model);
64670
64621
  this.catalog = this.artifacts.catalog;
64671
64622
  }
64623
+ wallet;
64624
+ model;
64625
+ name = "buyer-v1";
64626
+ core;
64627
+ http;
64628
+ artifacts;
64629
+ catalog;
64672
64630
  create(delegation, input2) {
64673
64631
  const parsed = buyerTask.parse(input2);
64674
- if ("kind" in parsed)
64675
- return buyerView.parse(this.artifacts.create(delegation, parsed));
64632
+ if ("kind" in parsed) return buyerView.parse(this.artifacts.create(delegation, parsed));
64676
64633
  const task = parsed, old = this.core.get(task.id);
64677
64634
  if (old) {
64678
64635
  const { delegation: _delegation, deadline: _deadline, targetMerchantId: _target, ...saved } = taskInput.parse(old.input);
@@ -64684,7 +64641,8 @@ var BuyerRuntime = class {
64684
64641
  requireThat(targetMerchantId, "task_merchant_required");
64685
64642
  requireThat(!policy.merchantId || targetMerchantId === policy.merchantId, "merchant_outside_delegation");
64686
64643
  requireThat(!policy.capability || policy.capability === TEXT_CAPABILITY, "capability_outside_delegation");
64687
- requireThat(toAtomic(task.maxPriceUSDC) <= toAtomic(policy.maxPerPaymentUSDC ?? policy.maxTotalUSDC), "task_exceeds_delegation");
64644
+ const cap = policy.maxPerPaymentUSDC ?? policy.maxTotalUSDC;
64645
+ requireThat(!cap || toAtomic(task.maxPriceUSDC) <= toAtomic(cap), "task_exceeds_delegation");
64688
64646
  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
64647
  requireThat(Number(this.wallet.store.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status='active'").get()?.n) < 100, "wallet_task_capacity");
64690
64648
  this.core.create(task.id, this.name, delegation, { ...task, delegation, targetMerchantId, deadline: new Date(this.wallet.clock() + 864e5).toISOString() }, { stage: "create" });
@@ -64693,16 +64651,14 @@ var BuyerRuntime = class {
64693
64651
  view(id, delegation) {
64694
64652
  const j = this.core.get(id);
64695
64653
  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));
64654
+ 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
64655
  const s = stateSchema.parse(j.state);
64699
64656
  const target = taskInput.parse(j.input).targetMerchantId ?? this.wallet.policy(delegation).policy.merchantId;
64700
64657
  let result = null;
64701
- if (s.resultBase64)
64702
- try {
64703
- result = JSON.parse(Buffer.from(s.resultBase64, "base64").toString("utf8"));
64704
- } catch {
64705
- }
64658
+ if (s.resultBase64) try {
64659
+ result = JSON.parse(Buffer.from(s.resultBase64, "base64").toString("utf8"));
64660
+ } catch {
64661
+ }
64706
64662
  return buyerView.parse({
64707
64663
  id,
64708
64664
  merchantId: target,
@@ -64729,8 +64685,7 @@ var BuyerRuntime = class {
64729
64685
  return (name) => name + (s.proofRevision ? ":" + s.proofRevision : "");
64730
64686
  }
64731
64687
  renewProof(c, s, error62, code) {
64732
- if (!(error62 instanceof RemoteHttpFault) || error62.status !== 401 || error62.remoteCode !== code)
64733
- throw error62;
64688
+ if (!(error62 instanceof RemoteHttpFault) || error62.status !== 401 || error62.remoteCode !== code) throw error62;
64734
64689
  requireThat(s.proofRevision < 3, "proof_renewal_limit");
64735
64690
  c.record("renew_" + s.stage + "_proof");
64736
64691
  return { state: { ...s, proofRevision: s.proofRevision + 1 }, waitMs: 1e3 };
@@ -64738,26 +64693,20 @@ var BuyerRuntime = class {
64738
64693
  checkTicket(t, c, state2) {
64739
64694
  const task = taskInput.parse(c.job.input), p = this.wallet.policy(task.delegation).policy;
64740
64695
  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");
64696
+ if (t.quote) requireThat(quoteHash(t) === t.quote.termsHash, "quote_hash_mismatch");
64697
+ if (state2.accepted) requireThat(t.quote && canonical(t.quote) === canonical(quote.parse(state2.accepted.quote)), "quote_changed");
64698
+ if (state2.operationId) requireThat(t.payment.operationId === state2.operationId, "payment_operation_changed");
64747
64699
  }
64748
64700
  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);
64701
+ 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
64702
  const task = taskInput.parse(c.job.input), s = stateSchema.parse(c.job.state), policy = this.wallet.policy(task.delegation).policy;
64752
64703
  const merchantId = task.targetMerchantId ?? policy.merchantId;
64753
64704
  requireThat(merchantId, "task_merchant_required");
64754
- if (Date.parse(task.deadline) <= c.now)
64755
- throw new RuntimeFault("task_deadline_recovery_required");
64705
+ if (Date.parse(task.deadline) <= c.now) throw new RuntimeFault("task_deadline_recovery_required");
64756
64706
  const buyer = this.wallet.address.toLowerCase(), key = "runtime_grant_" + task.id;
64757
64707
  if (s.stage === "create") {
64758
64708
  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" };
64709
+ 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
64710
  const body = { buyer, merchantId, capability: TEXT_CAPABILITY, input: task.input, maxPriceUSDC: task.maxPriceUSDC, expiresInSeconds: 3600 };
64762
64711
  const action = await this.proofKey(c, s, "grant", body);
64763
64712
  const signed = await c.effect(action("grant-proof"), body, "safe", async () => {
@@ -64769,7 +64718,12 @@ var BuyerRuntime = class {
64769
64718
  });
64770
64719
  let created;
64771
64720
  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 }));
64721
+ created = await c.effect(action("create-ticket"), { body, signed }, "safe", () => this.http.json(
64722
+ "/v1/work-tickets",
64723
+ ticketResponse,
64724
+ { ...body, challengeId: signed.challengeId, signature: signed.signature },
64725
+ { "Idempotency-Key": key }
64726
+ ));
64773
64727
  } catch (error62) {
64774
64728
  return this.renewProof(c, s, error62, "invalid_work_ticket_challenge");
64775
64729
  }
@@ -64782,8 +64736,7 @@ var BuyerRuntime = class {
64782
64736
  const current = (await this.http.json(path, ticketResponse)).ticket;
64783
64737
  this.checkTicket(current, c, s);
64784
64738
  if (s.stage === "quote") {
64785
- if (current.state === "open" || current.state === "claimed")
64786
- return { state: s, waitMs: 5e3 };
64739
+ if (current.state === "open" || current.state === "claimed") return { state: s, waitMs: 5e3 };
64787
64740
  requireThat(current.state === "quoted" || current.state === "accepted", "quote_unavailable");
64788
64741
  this.wallet.assertActive(task.delegation);
64789
64742
  const terms = { ticketId: s.ticketId, grant: s.grant, quote: current.quote };
@@ -64849,19 +64802,15 @@ var BuyerRuntime = class {
64849
64802
  payment = await this.wallet.authorize(task.id, task.delegation, s.accepted.quote.termsHash, req, path + "/checkout");
64850
64803
  }
64851
64804
  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);
64805
+ if (![200, 202].includes(paid.status)) throw new RuntimeFault("payment_outcome_uncertain", true);
64854
64806
  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");
64807
+ if (op) uuid3.parse(op);
64808
+ if (s.operationId && op) requireThat(s.operationId === op, "payment_operation_changed");
64859
64809
  c.record(paid.status === 202 ? "payment_pending" : "payment_submitted");
64860
64810
  return { state: op ? { ...s, operationId: op } : s, waitMs: 5e3 };
64861
64811
  }
64862
64812
  if (s.stage === "result") {
64863
- if (current.state === "paid")
64864
- return { state: s, waitMs: 5e3 };
64813
+ if (current.state === "paid") return { state: s, waitMs: 5e3 };
64865
64814
  requireThat(current.result.sha256 && current.result.contentType === "application/json", "result_unavailable");
64866
64815
  const saved = await c.effect("read-result", { ticketId: s.ticketId, hash: current.result.sha256 }, "safe", async () => {
64867
64816
  const ch = await this.http.json(path + "/result-challenges", challenge2, { buyer });
@@ -64878,8 +64827,7 @@ var BuyerRuntime = class {
64878
64827
  ].join("\n");
64879
64828
  requireThat(ch.message === expected, "read_message_mismatch");
64880
64829
  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);
64830
+ if (r.status !== 200) throw new RuntimeFault("result_read_uncertain", true);
64883
64831
  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
64832
  return { base64: r.bytes.toString("base64"), hash: sha256(r.bytes), verdict: evaluateTextStatistics(task.input, r.bytes) ? "accepted" : "disputed" };
64885
64833
  });
@@ -64923,7 +64871,7 @@ function newBuyerTask(text3, maxPriceUSDC, merchantId) {
64923
64871
  return workBuyerTask.parse({ id: randomUUID4(), input: { text: text3 }, maxPriceUSDC, ...merchantId !== void 0 ? { merchantId } : {} });
64924
64872
  }
64925
64873
 
64926
- // dist/runtime/server.js
64874
+ // src/runtime/server.ts
64927
64875
  var import_express = __toESM(require_express2(), 1);
64928
64876
  function createWalletApp(source) {
64929
64877
  const current = () => typeof source === "function" ? source() : source;
@@ -65003,7 +64951,7 @@ function createWalletApp(source) {
65003
64951
  return app;
65004
64952
  }
65005
64953
 
65006
- // dist/runtime/seller.js
64954
+ // src/runtime/seller.ts
65007
64955
  var sellerSettings = external_exports.object({
65008
64956
  origin: external_exports.string(),
65009
64957
  name: external_exports.string().regex(/^[A-Za-z0-9][A-Za-z0-9._ -]{0,63}$/),
@@ -65036,8 +64984,7 @@ async function enrollSeller(store, discoverable, fetcher = fetch) {
65036
64984
  try {
65037
64985
  c = await http2.json("/v1/merchants/enrollment-challenges", schema, { wallet: account.address, name: config2.name });
65038
64986
  } catch (e) {
65039
- if (!(e instanceof RemoteHttpFault) || e.status !== 409 || e.remoteCode !== "merchant_wallet_registered")
65040
- throw e;
64987
+ if (!(e instanceof RemoteHttpFault) || e.status !== 409 || e.remoteCode !== "merchant_wallet_registered") throw e;
65041
64988
  rotate = true;
65042
64989
  c = await http2.json("/v1/merchants/credential-challenges", schema, { wallet: account.address });
65043
64990
  }
@@ -65056,7 +65003,11 @@ async function enrollSeller(store, discoverable, fetcher = fetch) {
65056
65003
  "This creates or replaces a merchant API key. It does not authorize a payment."
65057
65004
  ].join("\n");
65058
65005
  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 }) });
65006
+ const result = await http2.json(
65007
+ rotate ? "/v1/merchants/credentials/rotate" : "/v1/merchants/enrollments",
65008
+ external_exports.object({ apiKey: external_exports.string().min(16).max(128), merchant: external_exports.object({ id: uuid3, payoutAddress: address }) }),
65009
+ { wallet: account.address, ...rotate ? {} : { name: config2.name }, challengeId: c.challengeId, signature: await account.signMessage({ message: expected }) }
65010
+ );
65060
65011
  requireThat(result.merchant.payoutAddress.toLowerCase() === account.address.toLowerCase(), "merchant_identity_mismatch");
65061
65012
  config2.apiKey = result.apiKey;
65062
65013
  config2.merchantId = result.merchant.id;
@@ -65088,15 +65039,6 @@ async function enrollSeller(store, discoverable, fetcher = fetch) {
65088
65039
  return { merchantId: config2.merchantId, address: account.address, origin: http2.origin, capability: TEXT_CAPABILITY, priceUSDC: config2.priceUSDC, discoverable };
65089
65040
  }
65090
65041
  var SellerRuntime = class {
65091
- store;
65092
- chain;
65093
- clock;
65094
- model;
65095
- name = "seller-v1";
65096
- core;
65097
- http;
65098
- config;
65099
- address;
65100
65042
  constructor(store, chain, fetcher = fetch, clock = Date.now, model) {
65101
65043
  this.store = store;
65102
65044
  this.chain = chain;
@@ -65109,6 +65051,15 @@ var SellerRuntime = class {
65109
65051
  this.http = new RuntimeHttp(this.config.origin, fetcher, this.config.apiKey);
65110
65052
  this.address = privateKeyToAccount(this.config.privateKey).address;
65111
65053
  }
65054
+ store;
65055
+ chain;
65056
+ clock;
65057
+ model;
65058
+ name = "seller-v1";
65059
+ core;
65060
+ http;
65061
+ config;
65062
+ address;
65112
65063
  discoveryStatus() {
65113
65064
  return this.store.get("seller-feed-error") ?? null;
65114
65065
  }
@@ -65123,27 +65074,23 @@ var SellerRuntime = class {
65123
65074
  last = e.sequence;
65124
65075
  }
65125
65076
  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 });
65077
+ for (const e of page.items) this.core.create(e.ticketId, this.name, this.config.merchantId, { ticketId: e.ticketId }, { stage: "inspect", ownsClaim: false });
65128
65078
  this.store.transaction(() => {
65129
65079
  const current = external_exports.number().parse(this.store.require("seller-event-cursor"));
65130
65080
  this.store.put("seller-event-cursor", Math.max(current, page.nextCursor));
65131
65081
  });
65132
- if (!page.hasMore)
65133
- break;
65082
+ if (!page.hasMore) break;
65134
65083
  }
65135
65084
  }
65136
65085
  async releaseExpiredSlots() {
65137
65086
  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
65087
  for (const row of rows) {
65139
65088
  const id = String(row.id), key = "seller-slot-check:" + id;
65140
- if ((this.store.get(key) ?? 0) > this.clock())
65141
- continue;
65089
+ if ((this.store.get(key) ?? 0) > this.clock()) continue;
65142
65090
  this.store.put(key, this.clock() + 6e4);
65143
65091
  try {
65144
65092
  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;
65093
+ if (t.id !== id || t.merchantId !== this.config.merchantId || t.state !== "expired" || t.payment.operationId) continue;
65147
65094
  this.store.transaction(() => {
65148
65095
  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
65096
  if (changed.changes) {
@@ -65170,48 +65117,37 @@ var SellerRuntime = class {
65170
65117
  this.store.put("seller-feed-error", { error: faultCode(error62), nextAt: this.clock() + 6e4 });
65171
65118
  }
65172
65119
  }
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));
65120
+ for (const job of this.core.active(this.name)) if (!visited.has(job.id)) results.push(await this.core.tick(job.id, this));
65176
65121
  return results.map((j) => ({ id: j.id, status: j.status, error: j.error, stage: sellerState.parse(j.state).stage }));
65177
65122
  }
65178
65123
  async step(c) {
65179
65124
  const s = sellerState.parse(c.job.state), id = uuid3.parse(c.job.id), path = `/v1/agent/work-tickets/${id}`;
65180
65125
  const t = (await this.http.json(path, detail)).ticket;
65181
65126
  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" };
65127
+ if (t.state === "expired") return { state: { ...s, stage: "done" }, status: "rejected" };
65184
65128
  if (["delivered", "accepted_by_buyer", "disputed"].includes(t.state)) {
65185
65129
  requireThat(s.outputHash && t.result.sha256 === s.outputHash, "unrecognized_delivery");
65186
65130
  return { state: { ...s, stage: "done" }, status: "complete" };
65187
65131
  }
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" };
65132
+ 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
65133
  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");
65134
+ 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
65135
  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" };
65136
+ 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
65137
  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 };
65138
+ if (t.state === "claimed" && !attempted && Date.parse(t.claimExpiresAt ?? "") > this.clock()) return { state: s, waitMs: 5e3 };
65199
65139
  requireThat(t.state === "open" || t.state === "claimed", "unrecognized_work_commitment");
65200
65140
  const slot = this.store.transaction(() => {
65201
65141
  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;
65142
+ if (this.store.db.prepare("SELECT job FROM seller_slots WHERE job=?").get(id)) return true;
65143
+ if (Number(this.store.db.prepare("SELECT COUNT(*) n FROM seller_slots").get()?.n) >= this.config.capacity) return false;
65206
65144
  this.store.db.prepare("INSERT INTO seller_slots VALUES(?)").run(id);
65207
65145
  return true;
65208
65146
  });
65209
- if (!slot)
65210
- return { state: s, waitMs: 5e3 };
65147
+ if (!slot) return { state: s, waitMs: 5e3 };
65211
65148
  await c.effect("claim", { id }, "safe", async () => {
65212
65149
  const fresh = (await this.http.json(path, detail)).ticket;
65213
- if (fresh.state === "claimed" && Date.parse(fresh.claimExpiresAt ?? "") > this.clock())
65214
- return { ticket: fresh };
65150
+ if (fresh.state === "claimed" && Date.parse(fresh.claimExpiresAt ?? "") > this.clock()) return { ticket: fresh };
65215
65151
  return this.http.json(path + "/claims", detail, { leaseSeconds: 600 });
65216
65152
  });
65217
65153
  return { state: { ...s, ownsClaim: true, stage: "quote" } };
@@ -65236,8 +65172,7 @@ var SellerRuntime = class {
65236
65172
  }
65237
65173
  if (s.stage === "funding") {
65238
65174
  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" };
65175
+ if (t.state !== "paying" && t.quote && Date.parse(t.quote.expiresAt) <= this.clock()) return { state: { ...s, ownsClaim: false }, status: "rejected" };
65241
65176
  return { state: s, waitMs: 5e3 };
65242
65177
  }
65243
65178
  requireThat(t.quote && t.payment.operationId && t.payment.transaction, "funding_reference_missing");
@@ -65258,7 +65193,7 @@ var SellerRuntime = class {
65258
65193
  }
65259
65194
  };
65260
65195
 
65261
- // dist/runtime/model.js
65196
+ // src/runtime/model.ts
65262
65197
  var admission = external_exports.object({ decision: external_exports.enum(["proceed", "reject"]), reason: external_exports.enum(["in_scope", "out_of_scope", "insufficient_context"]) }).strict();
65263
65198
  var modelSettings = external_exports.object({
65264
65199
  model: external_exports.string().regex(/^[A-Za-z0-9_.:/-]{1,120}$/),
@@ -65267,10 +65202,6 @@ var modelSettings = external_exports.object({
65267
65202
  maxReservedTokens: external_exports.number().int().min(4096).max(1e6)
65268
65203
  }).strict();
65269
65204
  var OpenRouterModel = class {
65270
- model;
65271
- key;
65272
- fetcher;
65273
- id;
65274
65205
  constructor(model, key, fetcher = fetch) {
65275
65206
  this.model = model;
65276
65207
  this.key = key;
@@ -65278,6 +65209,10 @@ var OpenRouterModel = class {
65278
65209
  this.id = "openrouter:" + model;
65279
65210
  requireThat(key.length >= 16 && key.length < 512 && !/\s/.test(key), "invalid_model_key");
65280
65211
  }
65212
+ model;
65213
+ key;
65214
+ fetcher;
65215
+ id;
65281
65216
  async propose(context, repair) {
65282
65217
  let response;
65283
65218
  try {
@@ -65307,20 +65242,18 @@ var OpenRouterModel = class {
65307
65242
  }
65308
65243
  const reader = response.body?.getReader(), parts = [];
65309
65244
  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
- });
65245
+ if (reader) try {
65246
+ for (; ; ) {
65247
+ const next = await reader.read();
65248
+ if (next.done) break;
65249
+ size5 += next.value.length;
65250
+ requireThat(size5 <= 32768, "model_response_too_large");
65251
+ parts.push(next.value);
65323
65252
  }
65253
+ } finally {
65254
+ await reader.cancel().catch(() => {
65255
+ });
65256
+ }
65324
65257
  try {
65325
65258
  const parsed = external_exports.object({
65326
65259
  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 +65266,15 @@ var OpenRouterModel = class {
65333
65266
  }
65334
65267
  };
65335
65268
  var ModelGate = class {
65336
- store;
65337
- adapter;
65338
- limits;
65339
65269
  constructor(store, adapter, limits) {
65340
65270
  this.store = store;
65341
65271
  this.adapter = adapter;
65342
65272
  this.limits = limits;
65343
65273
  external_exports.object({ maxCalls: external_exports.number().int().positive(), maxReservedTokens: external_exports.number().int().positive() }).strict().parse(limits);
65344
65274
  }
65275
+ store;
65276
+ adapter;
65277
+ limits;
65345
65278
  async admit(c, context) {
65346
65279
  const input2 = { adapter: this.adapter.id, context }, encoded = canonical(input2);
65347
65280
  requireThat(Buffer.byteLength(encoded) <= 2e4, "model_context_too_large");
@@ -65395,28 +65328,37 @@ var ModelGate = class {
65395
65328
  return decision.decision === "proceed";
65396
65329
  }
65397
65330
  };
65398
- function loadModelGate(store, file2) {
65331
+ function loadModelGate(store, file2, fetcher = fetch) {
65399
65332
  const prior = store.get("model-configuration");
65400
65333
  if (!file2) {
65401
65334
  requireThat(!prior, "model_configuration_required");
65402
65335
  return void 0;
65403
65336
  }
65404
65337
  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
- }
65338
+ if (prior) requireThat(binding === prior, "model_configuration_changed");
65411
65339
  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);
65340
+ const gate = new ModelGate(
65341
+ store,
65342
+ new OpenRouterModel(settings.model, secret2.apiKey, fetcher),
65343
+ { maxCalls: settings.maxCalls, maxReservedTokens: settings.maxReservedTokens }
65344
+ );
65345
+ store.transaction(() => {
65346
+ const current = store.get("model-configuration");
65347
+ if (current) requireThat(binding === current, "model_configuration_changed");
65348
+ else {
65349
+ requireThat(Number(store.db.prepare("SELECT COUNT(*) n FROM jobs").get()?.n) === 0, "model_configuration_requires_new_runtime");
65350
+ store.put("model-configuration", binding);
65351
+ }
65352
+ });
65353
+ return gate;
65413
65354
  }
65414
65355
 
65415
- // dist/runtime/web-launch.js
65356
+ // src/runtime/web-launch.ts
65416
65357
  import { createInterface } from "node:readline";
65417
65358
 
65418
- // dist/runtime/web-contract.js
65359
+ // src/runtime/web-contract.ts
65419
65360
  var WEB_WALLET_ORIGIN = "https://wallet.evidence.contact";
65361
+ var WALLET_CONSOLE_PROTOCOL = "402mob.wallet-console.v2";
65420
65362
  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
65363
  var emptyWebInput = external_exports.object({}).strict();
65422
65364
  var walletCreateInput = external_exports.object({ maxTotalUSDC: amount.nullable().optional() }).strict();
@@ -65430,7 +65372,7 @@ var webCredential = external_exports.object({
65430
65372
  policy: delegationPolicy,
65431
65373
  gateway: external_exports.string().url()
65432
65374
  }).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();
65375
+ 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
65376
  var webActivity = buyerView.omit({ result: true, resultBase64: true }).extend({ delegationId: uuid3 }).strict();
65435
65377
  var webState = external_exports.object({
65436
65378
  initialized: external_exports.boolean(),
@@ -65442,19 +65384,12 @@ var webState = external_exports.object({
65442
65384
  activity: external_exports.array(webActivity).max(50)
65443
65385
  }).strict();
65444
65386
  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();
65387
+ 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
65388
  var webMerchant = external_exports.object({ id: uuid3, name: external_exports.string(), payoutAddress: address }).strict();
65447
65389
  var webError = external_exports.object({ error: external_exports.string() }).strict();
65448
65390
 
65449
- // dist/runtime/web-service.js
65391
+ // src/runtime/web-service.ts
65450
65392
  var WalletWebService = class {
65451
- store;
65452
- chain;
65453
- fetcher;
65454
- clock;
65455
- runtime;
65456
- serviceOrigin;
65457
- agentGateway;
65458
65393
  constructor(store, chain, settings, fetcher = fetch, clock = Date.now) {
65459
65394
  this.store = store;
65460
65395
  this.chain = chain;
@@ -65465,14 +65400,21 @@ var WalletWebService = class {
65465
65400
  this.agentGateway = origin(settings.agentGateway);
65466
65401
  const gateway = new URL(this.agentGateway);
65467
65402
  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();
65403
+ this.model = loadModelGate(store, settings.modelConfig, fetcher);
65404
+ if (store.get("wallet")) this.open();
65471
65405
  }
65406
+ store;
65407
+ chain;
65408
+ fetcher;
65409
+ clock;
65410
+ runtime;
65411
+ serviceOrigin;
65412
+ agentGateway;
65413
+ model;
65472
65414
  open() {
65473
65415
  const wallet2 = new DelegatedWallet(this.store, this.chain, this.clock);
65474
65416
  requireThat(wallet2.origin === this.serviceOrigin, "wallet_service_origin_changed");
65475
- this.runtime = new BuyerRuntime(wallet2, this.fetcher);
65417
+ this.runtime = new BuyerRuntime(wallet2, this.fetcher, this.model);
65476
65418
  }
65477
65419
  ready() {
65478
65420
  requireThat(this.runtime, "wallet_not_created");
@@ -65480,8 +65422,7 @@ var WalletWebService = class {
65480
65422
  }
65481
65423
  create(input2) {
65482
65424
  const settings = walletCreateInput.parse(input2);
65483
- if (this.runtime)
65484
- requireThat(this.runtime.wallet.limitUSDC === (settings.maxTotalUSDC ?? null), "wallet_already_exists");
65425
+ if (this.runtime) requireThat(this.runtime.wallet.limitUSDC === (settings.maxTotalUSDC ?? null), "wallet_already_exists");
65485
65426
  else {
65486
65427
  DelegatedWallet.initialize(this.store, { origin: this.serviceOrigin, maxTotalUSDC: settings.maxTotalUSDC ?? null });
65487
65428
  this.open();
@@ -65537,13 +65478,11 @@ var WalletWebService = class {
65537
65478
  return webMerchant.parse({ id: response.merchant.id, name: response.merchant.name, payoutAddress: response.merchant.payoutAddress });
65538
65479
  }
65539
65480
  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);
65481
+ if (this.runtime) for (const job of this.runtime.core.active(this.runtime.name)) await this.runtime.tick(job.id);
65543
65482
  }
65544
65483
  };
65545
65484
 
65546
- // dist/runtime/web-server.js
65485
+ // src/runtime/web-server.ts
65547
65486
  var import_express2 = __toESM(require_express2(), 1);
65548
65487
  import { randomBytes as randomBytes4 } from "node:crypto";
65549
65488
  import { fileURLToPath } from "node:url";
@@ -65555,6 +65494,7 @@ var assets = /* @__PURE__ */ new Map([
65555
65494
  ["/style.css", ["style.css", "text/css"]],
65556
65495
  ["/favicon.svg", ["favicon.svg", "image/svg+xml"]]
65557
65496
  ]);
65497
+ var assetRoot = fileURLToPath(new URL("../../public/wallet/", import.meta.url));
65558
65498
  var secret = (prefix) => prefix + randomBytes4(32).toString("hex");
65559
65499
  var loopback = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
65560
65500
  function createWalletOwnerApp(service, settings = {}) {
@@ -65563,12 +65503,8 @@ function createWalletOwnerApp(service, settings = {}) {
65563
65503
  requireThat(publicUrl.protocol === "https:" || publicUrl.protocol === "http:" && ["127.0.0.1", "localhost"].includes(publicUrl.hostname), "invalid_wallet_web_origin");
65564
65504
  const pairs = /* @__PURE__ */ new Map(), sessions = /* @__PURE__ */ new Map();
65565
65505
  const cleanup = () => {
65566
- for (const [key, expiry] of pairs)
65567
- if (expiry <= clock())
65568
- pairs.delete(key);
65569
- for (const [key, session] of sessions)
65570
- if (session.expiresAt <= clock())
65571
- sessions.delete(key);
65506
+ for (const [key, expiry] of pairs) if (expiry <= clock()) pairs.delete(key);
65507
+ for (const [key, session] of sessions) if (session.expiresAt <= clock()) sessions.delete(key);
65572
65508
  };
65573
65509
  const issuePair = () => {
65574
65510
  cleanup();
@@ -65613,8 +65549,7 @@ function createWalletOwnerApp(service, settings = {}) {
65613
65549
  return;
65614
65550
  }
65615
65551
  res.set({ "Access-Control-Allow-Methods": "GET, POST", "Access-Control-Allow-Headers": "Authorization, Content-Type, X-402Mob-Wallet", "Access-Control-Max-Age": "0" });
65616
- if (req.get("Access-Control-Request-Private-Network") === "true")
65617
- res.set("Access-Control-Allow-Private-Network", "true");
65552
+ if (req.get("Access-Control-Request-Private-Network") === "true") res.set("Access-Control-Allow-Private-Network", "true");
65618
65553
  res.status(204).end();
65619
65554
  return;
65620
65555
  }
@@ -65626,8 +65561,7 @@ function createWalletOwnerApp(service, settings = {}) {
65626
65561
  res.status(400).json({ error: "unexpected_query" });
65627
65562
  return;
65628
65563
  }
65629
- if (bucket.until <= clock())
65630
- bucket = { count: 0, until: clock() + 6e4 };
65564
+ if (bucket.until <= clock()) bucket = { count: 0, until: clock() + 6e4 };
65631
65565
  if (++bucket.count > 240) {
65632
65566
  res.set("Retry-After", "60").status(429).json({ error: "wallet_rate_limited" });
65633
65567
  return;
@@ -65643,13 +65577,12 @@ function createWalletOwnerApp(service, settings = {}) {
65643
65577
  cleanup();
65644
65578
  next();
65645
65579
  });
65646
- for (const [path, [file2, type]] of assets)
65647
- app.get(path, (_req, res) => {
65648
- res.type(type).sendFile(fileURLToPath(new URL("../../public/wallet/" + file2, import.meta.url)));
65649
- });
65580
+ for (const [path, [file2, type]] of assets) app.get(path, (_req, res) => {
65581
+ res.type(type).sendFile(file2, { root: assetRoot, dotfiles: "deny" });
65582
+ });
65650
65583
  app.use(import_express2.default.json({ limit: "16kb", strict: true, inflate: false }));
65651
65584
  app.get("/api/healthz", (_req, res) => {
65652
- res.json({ protocol: "402mob.owner-wallet-web.v1", network: NETWORK, asset: USDC });
65585
+ res.json(webHealth.parse({ protocol: "402mob.owner-wallet-web.v1", consoleProtocol: WALLET_CONSOLE_PROTOCOL, network: NETWORK, asset: USDC }));
65653
65586
  });
65654
65587
  app.post("/api/session", (req, res) => {
65655
65588
  const { code } = webSessionInput.parse(req.body), key = sha256(code), expiry = pairs.get(key);
@@ -65734,13 +65667,13 @@ function createWalletOwnerApp(service, settings = {}) {
65734
65667
  } };
65735
65668
  }
65736
65669
 
65737
- // dist/runtime/listener.js
65670
+ // src/runtime/listener.ts
65738
65671
  var RuntimeListenFault = class extends RuntimeFault {
65739
- port;
65740
65672
  constructor(port, code) {
65741
65673
  super(code);
65742
65674
  this.port = port;
65743
65675
  }
65676
+ port;
65744
65677
  };
65745
65678
  function listenLoopback(app, port) {
65746
65679
  return new Promise((resolve3, reject) => {
@@ -65751,12 +65684,9 @@ function listenLoopback(app, port) {
65751
65684
  };
65752
65685
  const failed = (error62) => {
65753
65686
  server.off("listening", ready);
65754
- if (error62.code === "EADDRINUSE")
65755
- reject(new RuntimeListenFault(port, "local_port_in_use"));
65756
- else if (error62.code === "EACCES" || error62.code === "EPERM")
65757
- reject(new RuntimeListenFault(port, "local_port_permission_denied"));
65758
- else
65759
- reject(error62);
65687
+ if (error62.code === "EADDRINUSE") reject(new RuntimeListenFault(port, "local_port_in_use"));
65688
+ else if (error62.code === "EACCES" || error62.code === "EPERM") reject(new RuntimeListenFault(port, "local_port_permission_denied"));
65689
+ else reject(error62);
65760
65690
  };
65761
65691
  server.once("error", failed);
65762
65692
  server.once("listening", ready);
@@ -65770,11 +65700,15 @@ function listenerDiagnostic(error62) {
65770
65700
  };
65771
65701
  }
65772
65702
 
65773
- // dist/runtime/web-launch.js
65703
+ // src/runtime/web-launch.ts
65774
65704
  async function runWalletWeb(store, chain, settings) {
65775
65705
  requireThat(settings.port !== settings.webPort, "wallet_ports_must_differ");
65776
65706
  const agentGateway = `http://127.0.0.1:${settings.port}`, ownerGateway = `http://127.0.0.1:${settings.webPort}`;
65777
- const service = new WalletWebService(store, chain, { serviceOrigin: settings.serviceOrigin, agentGateway });
65707
+ const service = new WalletWebService(store, chain, {
65708
+ serviceOrigin: settings.serviceOrigin,
65709
+ agentGateway,
65710
+ ...settings.modelConfig ? { modelConfig: settings.modelConfig } : {}
65711
+ });
65778
65712
  const owner = createWalletOwnerApp(service, { webOrigin: settings.webOrigin });
65779
65713
  const agent = createWalletApp(() => service.runtime);
65780
65714
  const servers = [];
@@ -65822,24 +65756,27 @@ async function runWalletWeb(store, chain, settings) {
65822
65756
  }
65823
65757
  }
65824
65758
 
65825
- // dist/runtime/cli.js
65759
+ // src/runtime/cli.ts
65826
65760
  var usage = `402Mob local buyer/seller runtime (Base USDC)
65827
65761
 
65828
65762
  Owner commands:
65829
65763
  wallet init --dir DIR --origin https://evidence.contact [--max-usdc 1]
65830
65764
  wallet status --dir DIR
65831
- wallet grant --dir DIR --file policy.json --out credential.json
65765
+ wallet grant --dir DIR --name "Agent" [--max-usdc 1] [--out credential.json]
65766
+ Optional advanced policy: --file policy.json instead of --name.
65832
65767
  wallet limit --dir DIR --file limit-update.json
65833
65768
  wallet allocation --dir DIR --id DELEGATION_UUID --file allocation-update.json
65834
65769
  wallet revoke --dir DIR --id DELEGATION_UUID
65835
65770
  wallet retry --dir DIR --id JOB_UUID
65836
65771
  wallet serve --dir DIR [--port 4031] [--rpc https://mainnet.base.org]
65837
65772
  wallet web --dir DIR [--port 4031] [--web-port 4032]
65838
- [--web-origin https://wallet.evidence.contact] [--origin https://evidence.contact]
65773
+ [--web-origin https://wallet.evidence.contact] [--origin https://evidence.contact] [--model-config FILE]
65839
65774
  Starts the owner-controlled signer; open its one-use pairing link to create
65840
- a USDC wallet, inspect funding, grant spending and download agent credentials.
65775
+ a USDC wallet, inspect funding and copy the agent connection. Limits and file export are optional.
65841
65776
 
65842
- Agent commands (only a delegation credential, never the wallet directory):
65777
+ Agent commands (MOB_RUNTIME_TOKEN in the environment, or optional --credential FILE):
65778
+ buyer check
65779
+ buyer resources
65843
65780
  buyer check --credential credential.json
65844
65781
  buyer workers --credential credential.json [--query TEXT] [--limit 20] [--cursor 0]
65845
65782
  buyer resources --credential credential.json [--query TEXT] [--limit 20] [--cursor 0]
@@ -65849,7 +65786,9 @@ Agent commands (only a delegation credential, never the wallet directory):
65849
65786
  buyer submit --file request.json --credential credential.json [--gateway http://127.0.0.1:4031]
65850
65787
  buyer status --id JOB_UUID --credential credential.json [--gateway ...]
65851
65788
  buyer run --file request.json --credential credential.json [--gateway ...]
65852
- Gateway: explicit --gateway, then the downloaded credential, then localhost:4031.
65789
+ Connection: MOB_RUNTIME_TOKEN and optional MOB_RUNTIME_GATEWAY, or --credential FILE.
65790
+ Use --credential - to read a connection JSON from stdin. No config download is required.
65791
+ Gateway: explicit --gateway, then the selected connection, then localhost:4031.
65853
65792
  For prepared artifacts, --share-url PINNED_PAYMENT_LINK replaces --merchant-id and --offer-id.
65854
65793
  For text work, omit --merchant-id only when the delegation already fixes a seller.
65855
65794
 
@@ -65928,7 +65867,16 @@ async function main() {
65928
65867
  print({ id: task2.id, requestFile: resolve2(needed("out")) });
65929
65868
  return;
65930
65869
  }
65931
- 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")));
65870
+ const schema = external_exports.object({ id: uuid3.optional(), token: external_exports.string().regex(/^mobrt_[0-9a-f]{64}$/), gateway: external_exports.string().optional() });
65871
+ let credential;
65872
+ if (v.credential) {
65873
+ const input2 = v.credential === "-" ? readFileSync2(0, "utf8") : void 0;
65874
+ if (input2 !== void 0) requireThat(Buffer.byteLength(input2) <= 65536, "input_file_too_large");
65875
+ credential = schema.extend({ id: uuid3 }).parse(input2 === void 0 ? readPrivateJson(v.credential) : JSON.parse(input2));
65876
+ } else {
65877
+ requireThat(process.env.MOB_RUNTIME_TOKEN, "agent_connection_required");
65878
+ credential = schema.parse({ token: process.env.MOB_RUNTIME_TOKEN, gateway: process.env.MOB_RUNTIME_GATEWAY });
65879
+ }
65932
65880
  const gateway = origin(v.gateway ?? credential.gateway ?? "http://127.0.0.1:4031");
65933
65881
  if (!v.gateway) {
65934
65882
  const target = new URL(gateway);
@@ -65937,7 +65885,7 @@ async function main() {
65937
65885
  const client = new RuntimeHttp(gateway, fetch, credential.token);
65938
65886
  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();
65939
65887
  const status = await client.json("/v1/status", external_exports.object({ delegationId: uuid3 }));
65940
- requireThat(status.delegationId === credential.id, "credential_identity_mismatch");
65888
+ requireThat(!credential.id || status.delegationId === credential.id, "credential_identity_mismatch");
65941
65889
  if (command === "check") {
65942
65890
  print({ connected: true, gateway, capabilities: ["text-statistics-v1", "prepared-artifact-v1"], spending: await client.json("/v1/status", spendingStatus) });
65943
65891
  return;
@@ -65969,16 +65917,13 @@ async function main() {
65969
65917
  const task = buyerTask.parse(readPrivateJson(needed("file")));
65970
65918
  let result = await client.json("/v1/tasks", response, task);
65971
65919
  print(result);
65972
- if (command === "submit")
65973
- return;
65920
+ if (command === "submit") return;
65974
65921
  for (let i = 0; i < 180 && !stopped && result.status === "active"; i++) {
65975
65922
  await delay(5e3);
65976
65923
  result = await client.json("/v1/tasks/" + task.id, response);
65977
- if (result.status !== "active" || i % 12 === 0)
65978
- print(result);
65924
+ if (result.status !== "active" || i % 12 === 0) print(result);
65979
65925
  }
65980
- if (result.status === "active")
65981
- print({ id: task.id, next: "Keep the same request file. The wallet service retains and continues this job; use buyer status." });
65926
+ 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." });
65982
65927
  return;
65983
65928
  }
65984
65929
  requireThat(role === "wallet" || role === "seller", "unknown_role");
@@ -65988,7 +65933,6 @@ async function main() {
65988
65933
  try {
65989
65934
  const chain = new BaseUsdcReader(v.rpc);
65990
65935
  if (role === "wallet" && command === "web") {
65991
- requireThat(!v["model-config"], "web_model_configuration_unsupported");
65992
65936
  const port2 = external_exports.coerce.number().int().min(1).max(65535).parse(v.port ?? "4031");
65993
65937
  const webPort = external_exports.coerce.number().int().min(1).max(65535).parse(v["web-port"] ?? "4032");
65994
65938
  const existing = store.get("wallet");
@@ -65996,6 +65940,7 @@ async function main() {
65996
65940
  serviceOrigin: v.origin ?? existing?.origin ?? "https://evidence.contact",
65997
65941
  port: port2,
65998
65942
  webPort,
65943
+ ...v["model-config"] ? { modelConfig: v["model-config"] } : {},
65999
65944
  webOrigin: v["web-origin"] ?? WEB_WALLET_ORIGIN,
66000
65945
  stopped: () => stopped,
66001
65946
  print
@@ -66004,8 +65949,7 @@ async function main() {
66004
65949
  }
66005
65950
  if (role === "seller") {
66006
65951
  if (command === "init") {
66007
- if (!store.get("seller"))
66008
- initializeSeller(store, { origin: v.origin ?? "https://evidence.contact", name: needed("name"), priceUSDC: needed("price-usdc"), capacity: 1 });
65952
+ if (!store.get("seller")) initializeSeller(store, { origin: v.origin ?? "https://evidence.contact", name: needed("name"), priceUSDC: needed("price-usdc"), capacity: 1 });
66009
65953
  else {
66010
65954
  const saved = external_exports.object({ origin: external_exports.string(), name: external_exports.string(), priceUSDC: external_exports.string() }).parse(store.require("seller"));
66011
65955
  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");
@@ -66026,15 +65970,12 @@ async function main() {
66026
65970
  print(await seller.sync());
66027
65971
  failures = 0;
66028
65972
  const discovery = seller.discoveryStatus();
66029
- if (discovery)
66030
- print({ ...discovery, next: "retry_discovery_existing_jobs_continue" });
65973
+ if (discovery) print({ ...discovery, next: "retry_discovery_existing_jobs_continue" });
66031
65974
  } catch (e) {
66032
- if (command === "once" || !(e instanceof RuntimeFault) || !e.retryable || ++failures >= 4)
66033
- throw e;
65975
+ if (command === "once" || !(e instanceof RuntimeFault) || !e.retryable || ++failures >= 4) throw e;
66034
65976
  print({ error: e.code, next: "retry_feed", failures });
66035
65977
  }
66036
- if (command === "once")
66037
- break;
65978
+ if (command === "once") break;
66038
65979
  await delay(failures ? 6e4 : 5e3);
66039
65980
  } while (!stopped);
66040
65981
  return;
@@ -66057,16 +65998,19 @@ async function main() {
66057
65998
  return;
66058
65999
  }
66059
66000
  if (command === "grant") {
66060
- const file2 = needed("out");
66061
- requireThat(!existsSync2(file2), "credential_file_exists");
66062
- const grant = wallet2.grant(readJson(needed("file")));
66063
- try {
66064
- out(file2, grant);
66065
- } catch (e) {
66066
- wallet2.revoke(grant.id);
66067
- throw e;
66068
- }
66069
- print({ delegationId: grant.id, credentialFile: resolve2(file2), wallet: wallet2.address, policy: grant.policy });
66001
+ const file2 = v.out;
66002
+ if (file2) requireThat(!existsSync2(file2), "credential_file_exists");
66003
+ requireThat(!v.file || !v.name && !v["max-usdc"], "choose_policy_file_or_name");
66004
+ const grant = wallet2.grant(v.file ? readJson(v.file) : { name: needed("name"), ...v["max-usdc"] ? { maxTotalUSDC: v["max-usdc"] } : {} }, randomUUID5());
66005
+ if (file2) {
66006
+ try {
66007
+ out(file2, grant);
66008
+ } catch (e) {
66009
+ wallet2.revoke(grant.id);
66010
+ throw e;
66011
+ }
66012
+ print({ delegationId: grant.id, credentialFile: resolve2(file2), wallet: wallet2.address, policy: grant.policy });
66013
+ } else print({ ...grant, gateway: "http://127.0.0.1:4031" });
66070
66014
  return;
66071
66015
  }
66072
66016
  if (command === "revoke") {
@@ -66087,8 +66031,7 @@ async function main() {
66087
66031
  try {
66088
66032
  while (!stopped) {
66089
66033
  for (const job of buyer.core.active(buyer.name)) {
66090
- if (stopped)
66091
- break;
66034
+ if (stopped) break;
66092
66035
  await buyer.tick(job.id);
66093
66036
  }
66094
66037
  await delay(1e3);