402mob-merchant-sdk 0.5.0 → 0.7.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.
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { validPurchaseDecision, decisionCanonical } from "./purchase-decisions.js";
1
2
  function requireEip191Signature(signature) {
2
3
  if (!/^0x[0-9a-fA-F]{130}$/.test(signature)) {
3
4
  throw new TypeError("signature must be a 65-byte EIP-191 signature encoded as 0x-prefixed hex.");
@@ -20,10 +21,11 @@ export class MerchantApiError extends Error {
20
21
  this.name = "MerchantApiError";
21
22
  }
22
23
  }
23
- /**
24
- * Minimal, dependency-free HTTP client for 402Mob agent resource resolution and merchant management.
25
- * It never signs messages, submits wallet transactions, persists API keys, or retries requests.
26
- */
24
+ function validSession(v) {
25
+ if (!isRecord(v) || !freshExactKeys(v, ["id", "name", "scopes", "createdAt", "expiresAt", "revokedAt", "lastUsedAt"]) || !uuid(v.id) || !publicText(v.name, 64) || !Array.isArray(v.scopes) || v.scopes.length < 1 || v.scopes.length > 3 || new Set(v.scopes).size !== v.scopes.length || !v.scopes.every(s => ["merchant:manage", "merchant:sales:read", "merchant:work"].includes(String(s))))
26
+ return false;
27
+ return [v.createdAt, v.expiresAt].every(x => typeof x === "string" && Number.isFinite(Date.parse(x))) && [v.revokedAt, v.lastUsedAt].every(x => x === null || typeof x === "string" && Number.isFinite(Date.parse(x))) && Date.parse(String(v.expiresAt)) > Date.parse(String(v.createdAt));
28
+ }
27
29
  export class MerchantClient {
28
30
  baseUrl;
29
31
  #apiKey;
@@ -54,7 +56,7 @@ export class MerchantClient {
54
56
  }
55
57
  /** Full replacement, with separate worker-discovery opt-in. No artifact or wallet action. */
56
58
  setWorkerProfile(input) {
57
- if (!isWorkerProfileInput(input) || !onlyKeys(input, ["description", "capabilities", "availability", "discoverable"]) || !input.capabilities.every(cap => onlyKeys(cap, ["id", "title", "description", "inputDescription", "resultDescription", "resultContentTypes"])))
59
+ if (!isWorkerProfileInput(input) || !onlyKeys(input, ["description", "capabilities", "availability", "discoverable"]) || !input.capabilities.every(cap => onlyKeys(cap, ["id", "title", "description", "inputDescription", "resultDescription", "resultContentTypes", "settlementModes"])))
58
60
  throw new TypeError("Provide the worker profile PUT body: bounded descriptions, unique capability IDs/formats, availability and explicit discoverable. Unknown or read-only fields are not allowed.");
59
61
  const body = normalizedWorkerProfile(input);
60
62
  if (new TextEncoder().encode(JSON.stringify(body)).byteLength > 64 * 1024)
@@ -190,9 +192,35 @@ export class MerchantClient {
190
192
  }
191
193
  return payload;
192
194
  }
195
+ /** Read immutable public decision terms, including for an unpublished exact offer. Verifies the origin-backed SHA-256; not a seller signature. */
196
+ async getOfferTerms(merchantId, offerId) {
197
+ const v = await this.request("GET", `/v1/merchants/${checkedWorkTicketId(merchantId)}/offers/${checkedWorkTicketId(offerId)}/terms`);
198
+ if (!isRecord(v) || Object.keys(v).length !== 14 || !publicText(v.title, 120) || !publicText(v.description, 300) || typeof v.version !== "string" || !/^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/.test(v.version) || v.schema !== "402mob.offer-terms.v1" || v.merchantId !== merchantId || v.offerId !== offerId || !validPurchaseDecision(v.purchaseDecision) || !digest(v.hash) || !address(v.payee) || v.network !== "eip155:8453" || v.asset !== baseUsdc || !atomicAmount(v.amountAtomic) || !["application/json", "text/plain"].includes(v.contentType) || !isRecord(v.artifact) || v.artifact.algorithm !== "sha256-private-proof-v1" || !digest(v.artifact.commitment) || !Number.isSafeInteger(v.artifact.sizeUpperBound) || v.artifact.sizeUpperBound < 1024 || v.artifact.sizeUpperBound > 49152 || v.artifact.sizeUpperBound % 1024)
199
+ throw invalidPublicResponse();
200
+ const { hash, ...document } = v;
201
+ const nodeCryptoModule = "node:crypto";
202
+ const subtle = globalThis.crypto?.subtle ?? (await import(nodeCryptoModule)).webcrypto.subtle;
203
+ const bytes = await subtle.digest("SHA-256", new TextEncoder().encode(decisionCanonical(document)));
204
+ const expected = Array.from(new Uint8Array(bytes), x => x.toString(16).padStart(2, "0")).join("");
205
+ if (hash !== expected)
206
+ throw invalidPublicResponse();
207
+ return v;
208
+ }
193
209
  setDiscoverable(discoverable) {
194
210
  return this.request("PUT", "/v1/agent/merchant/discovery", { discoverable }, true);
195
211
  }
212
+ async createMerchantSession(input) {
213
+ if (!isRecord(input) || Object.keys(input).some(k => !["name", "scopes", "expiresInSeconds"].includes(k)) || !publicText(input.name, 64) || !Array.isArray(input.scopes) || input.scopes.length < 1 || input.scopes.length > 3 || new Set(input.scopes).size !== input.scopes.length || !input.scopes.every(s => ["merchant:manage", "merchant:sales:read", "merchant:work"].includes(s)) || !Number.isInteger(input.expiresInSeconds) || input.expiresInSeconds < 60 || input.expiresInSeconds > 86400)
214
+ throw new TypeError("Provide a name, distinct merchant scopes and expiry of 60–86400 seconds.");
215
+ const v = await this.request("POST", "/v1/agent/merchant/sessions", input, true);
216
+ if (!isRecord(v) || !validSession(v.session) || v.session.name !== input.name.trim() || [...v.session.scopes].sort().join() !== [...input.scopes].sort().join() || Date.parse(v.session.expiresAt) - Date.parse(v.session.createdAt) !== input.expiresInSeconds * 1000 || typeof v.token !== "string" || !/^402mob_session_[A-Za-z0-9_-]{43}$/.test(v.token))
217
+ throw invalidPublicResponse();
218
+ return v;
219
+ }
220
+ async listMerchantSessions() { const v = await this.request("GET", "/v1/agent/merchant/sessions", undefined, true); if (!isRecord(v) || !Array.isArray(v.items) || v.items.length > 1000 || !v.items.every(validSession) || new Set(v.items.map(x => x.id)).size !== v.items.length)
221
+ throw invalidPublicResponse(); return v; }
222
+ async revokeMerchantSession(sessionId) { const v = await this.request("DELETE", `/v1/agent/merchant/sessions/${checkedWorkTicketId(sessionId)}`, undefined, true); if (!validSession(v) || v.id !== sessionId || v.revokedAt === null)
223
+ throw invalidPublicResponse(); return v; }
196
224
  createOffer(input) {
197
225
  return this.request("POST", "/v1/agent/merchant/offers", input, true);
198
226
  }
@@ -249,7 +277,50 @@ export class MerchantClient {
249
277
  submitWorkTicketResult(ticketId, input) {
250
278
  return this.request("POST", `/v1/agent/work-tickets/${checkedWorkTicketId(ticketId)}/results`, input, true);
251
279
  }
280
+ /** New source API: opt-in linkage; selection still creates neither a ticket nor a payment. */
281
+ getWorkAgreementTemplate(requestId) { return this.request("GET", `/v1/work-requests/${checkedWorkTicketId(requestId)}/agreement-template`); }
282
+ createWorkExecutionReadChallenge(requestId, buyer) { return this.request("POST", `/v1/work-requests/${checkedWorkTicketId(requestId)}/execution-challenges`, { buyer }); }
283
+ readWorkExecution(requestId, proof) { return this.request("POST", `/v1/work-requests/${checkedWorkTicketId(requestId)}/execution`, { ...proof, signature: requireEip191Signature(proof.signature) }); }
284
+ readMerchantWorkExecution(requestId) { return this.request("GET", `/v1/agent/work-requests/${checkedWorkTicketId(requestId)}/execution`, undefined, true); }
285
+ async listWorkEvents(input = {}) {
286
+ const after = input.after ?? 0, limit = input.limit ?? 50;
287
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isInteger(limit) || limit < 1 || limit > 100)
288
+ throw new TypeError("after must be a nonnegative safe integer; limit must be 1–100.");
289
+ const page = await this.request("GET", `/v1/agent/work-events?after=${after}&limit=${limit}`, undefined, true);
290
+ if (!uuid(page.merchantId) || !Array.isArray(page.items) || page.items.length > limit || typeof page.hasMore !== "boolean")
291
+ throw invalidPublicResponse();
292
+ let cursor = after;
293
+ for (const event of page.items) {
294
+ if (!isRecord(event) || !Number.isSafeInteger(event.sequence) || event.sequence <= cursor || !uuid(event.ticketId) || !workTicketStates.includes(event.state) || !timestamp(event.occurredAt))
295
+ throw invalidPublicResponse();
296
+ cursor = event.sequence;
297
+ }
298
+ if (page.nextCursor !== cursor || page.hasMore && page.items.length === 0)
299
+ throw invalidPublicResponse();
300
+ return page;
301
+ }
252
302
  /** Free public demand. Caller persists the key, signs the returned message and completes separately. */
303
+ createWorkRequestChallenge(input, idempotencyKey) { return this.request("POST", "/v1/work-requests/challenges", input, false, { "Idempotency-Key": idempotencyKey }); }
304
+ completeWorkRequest(input, idempotencyKey) { return this.request("POST", "/v1/work-requests", input, false, { "Idempotency-Key": idempotencyKey }); }
305
+ listWorkRequests(input = {}) {
306
+ const q = new URLSearchParams();
307
+ if (input.query !== undefined)
308
+ q.set("q", input.query);
309
+ if (input.limit !== undefined)
310
+ q.set("limit", String(input.limit));
311
+ if (input.cursor !== undefined)
312
+ q.set("cursor", String(input.cursor));
313
+ return this.request("GET", "/v1/work-requests?" + q);
314
+ }
315
+ getWorkRequest(id) { return this.request("GET", `/v1/work-requests/${encodeURIComponent(id)}`); }
316
+ proposeWorkRequest(id, input) { return this.request("POST", `/v1/agent/work-requests/${encodeURIComponent(id)}/proposals`, input, true); }
317
+ declineWorkRequest(id, input) { return this.request("POST", `/v1/agent/work-requests/${encodeURIComponent(id)}/declines`, input, true); }
318
+ createWorkRequestWithdrawalChallenge(id, input) { return this.request("POST", `/v1/work-requests/${encodeURIComponent(id)}/withdrawal-challenges`, input); }
319
+ withdrawWorkRequest(id, input) { return this.request("POST", `/v1/work-requests/${encodeURIComponent(id)}/withdrawals`, input); }
320
+ reviseWorkRequestResponse(id, responseId, input) { return this.request("POST", `/v1/agent/work-requests/${encodeURIComponent(id)}/responses/${encodeURIComponent(responseId)}/revisions`, input, true); }
321
+ getWorkResponseHistory(id, responseId) { return this.request("GET", `/v1/work-requests/${encodeURIComponent(id)}/responses/${encodeURIComponent(responseId)}/history`); }
322
+ createWorkRequestSelectionChallenge(id, input) { return this.request("POST", `/v1/work-requests/${encodeURIComponent(id)}/selection-challenges`, input); }
323
+ selectWorkRequestProposal(id, input) { return this.request("POST", `/v1/work-requests/${encodeURIComponent(id)}/selections`, input); }
253
324
  createBuyerRequestChallenge(input, idempotencyKey) {
254
325
  return this.request("POST", "/v1/buyer-requests/challenges", input, false, { "Idempotency-Key": buyerRequestKey(idempotencyKey) });
255
326
  }
@@ -346,6 +417,16 @@ export class MerchantClient {
346
417
  if (method === "PUT" && JSON.stringify(normalizedWorkerProfile(payload.workerProfile)) !== JSON.stringify(body))
347
418
  throw invalidResponse();
348
419
  }
420
+ if (path.endsWith("/execution-challenges")) {
421
+ if (!isRecord(body) || !address(body.buyer))
422
+ throw invalidResponse();
423
+ const id = path.split("/")[3];
424
+ const expected = ["402Mob private work execution read", `Origin: ${new URL(this.baseUrl).origin}`, `Request: ${id}`, `Buyer: ${body.buyer.toLowerCase()}`, `Challenge: ${payload.challengeId}`, `Expires: ${payload.expiresAt}`, "Read the linked execution only. This authorizes no grant, payment or result acceptance."].join("\n");
425
+ if (payload.message !== expected)
426
+ throw invalidResponse();
427
+ }
428
+ if ((path.startsWith("/v1/work-requests") || path.startsWith("/v1/agent/work-requests/")) && !isFreshWorkResponse(method, path, payload, body))
429
+ throw invalidResponse();
349
430
  if ((path.startsWith("/v1/buyer-requests") || path.startsWith("/v1/agent/buyer-requests/")) && !isBuyerRequestResponse(method, path, payload, body))
350
431
  throw invalidResponse();
351
432
  if (path === "/v1/merchants/enrollment-challenges" || path === "/v1/merchants/credential-challenges") {
@@ -383,14 +464,14 @@ function validWorkerCapabilityId(value) { return typeof value === "string" && /^
383
464
  function onlyKeys(value, keys) { return Object.keys(value).every(key => keys.includes(key)); }
384
465
  function boundedWorkerText(value, max) { return typeof value === "string" && value.trim().length > 0 && Array.from(value.trim()).length <= max; }
385
466
  function normalizedWorkerProfile(value) {
386
- return { description: value.description.trim(), capabilities: value.capabilities.map(cap => ({ id: cap.id, title: cap.title.trim(), description: cap.description.trim(), inputDescription: cap.inputDescription.trim(), resultDescription: cap.resultDescription.trim(), resultContentTypes: [...cap.resultContentTypes] })), availability: value.availability, discoverable: value.discoverable };
467
+ return { description: value.description.trim(), capabilities: value.capabilities.map(cap => ({ id: cap.id, title: cap.title.trim(), description: cap.description.trim(), inputDescription: cap.inputDescription.trim(), resultDescription: cap.resultDescription.trim(), resultContentTypes: [...cap.resultContentTypes], ...(cap.settlementModes ? { settlementModes: [...cap.settlementModes] } : {}) })), availability: value.availability, discoverable: value.discoverable };
387
468
  }
388
469
  function isWorkerProfileInput(value) {
389
470
  if (!isRecord(value) || !boundedWorkerText(value.description, 1000) || (value.availability !== "accepting" && value.availability !== "paused") || typeof value.discoverable !== "boolean" || !Array.isArray(value.capabilities) || !value.capabilities.length || value.capabilities.length > 10)
390
471
  return false;
391
472
  if (new Set(value.capabilities.map(c => isRecord(c) ? c.id : null)).size !== value.capabilities.length)
392
473
  return false;
393
- return value.capabilities.every(c => isRecord(c) && validWorkerCapabilityId(c.id) && boundedWorkerText(c.title, 100) && boundedWorkerText(c.description, 1000) && boundedWorkerText(c.inputDescription, 1000) && boundedWorkerText(c.resultDescription, 1000) && Array.isArray(c.resultContentTypes) && c.resultContentTypes.length >= 1 && c.resultContentTypes.length <= 2 && new Set(c.resultContentTypes).size === c.resultContentTypes.length && c.resultContentTypes.every(artifactType));
474
+ return value.capabilities.every(c => isRecord(c) && validWorkerCapabilityId(c.id) && boundedWorkerText(c.title, 100) && boundedWorkerText(c.description, 1000) && boundedWorkerText(c.inputDescription, 1000) && boundedWorkerText(c.resultDescription, 1000) && Array.isArray(c.resultContentTypes) && c.resultContentTypes.length >= 1 && c.resultContentTypes.length <= 2 && new Set(c.resultContentTypes).size === c.resultContentTypes.length && c.resultContentTypes.every(artifactType) && (c.settlementModes === undefined || Array.isArray(c.settlementModes) && c.settlementModes.length >= 1 && c.settlementModes.length <= 2 && new Set(c.settlementModes).size === c.settlementModes.length && c.settlementModes.every(mode => mode === "direct_prepayment" || mode === "protected_inspection")));
394
475
  }
395
476
  function isWorkerProfileView(value) {
396
477
  if (!isRecord(value) || !isRecord(value.merchant) || !uuid(value.merchant.id) || !publicText(value.merchant.name, 100) || !address(value.merchant.payoutAddress) || !isWorkerProfileInput(value.workerProfile))
@@ -467,7 +548,8 @@ function isAgentResource(value) {
467
548
  return false;
468
549
  const amountAtomic = value.amountAtomic;
469
550
  const amountUSDC = value.amountUSDC;
470
- return (value.share === undefined || nonempty(value.share)) &&
551
+ return (value.purchaseDecision === undefined ? value.offerTermsHash === undefined && value.offerTermsPath === undefined : validPurchaseDecision(value.purchaseDecision) && digest(value.offerTermsHash) && typeof value.offerTermsPath === "string" && value.offerTermsPath.endsWith(`/offers/${value.id}/terms`)) &&
552
+ (value.share === undefined || nonempty(value.share)) &&
471
553
  (value.artifact === undefined || (isRecord(value.artifact) && value.artifact.algorithm === "sha256-private-proof-v1" &&
472
554
  typeof value.artifact.commitment === "string" && /^[a-f0-9]{64}$/.test(value.artifact.commitment) &&
473
555
  Number.isSafeInteger(value.artifact.sizeUpperBound) && Number(value.artifact.sizeUpperBound) >= 1024 &&
@@ -627,3 +709,134 @@ function isDisputeResponse(v, operationId, proof, origin) {
627
709
  return true;
628
710
  }
629
711
  export { ProtectedWorkClient, ProtectedWorkApiError } from "./protected-work.js";
712
+ function isFreshRequest(v) {
713
+ if (!isRecord(v) || Object.hasOwn(v, "buyer"))
714
+ return false;
715
+ if (v.supersedesRequestId !== undefined && (!uuid(v.supersedesRequestId) || v.supersedesRequestId === v.id))
716
+ return false;
717
+ if (v.state === "withdrawn" || v.state === "superseded") {
718
+ if (!timestamp(v.closedAt))
719
+ return false;
720
+ }
721
+ else if (v.closedAt !== undefined)
722
+ return false;
723
+ if (v.state === "superseded") {
724
+ if (!uuid(v.supersededByRequestId) || v.supersededByRequestId === v.id)
725
+ return false;
726
+ }
727
+ else if (v.supersededByRequestId !== undefined)
728
+ return false;
729
+ return uuid(v.id) && v.kind === "fresh" && publicText(v.title, 100) && publicText(v.description, 2000) && usdcAtomic(v.maxPriceUSDC) !== undefined && Number(usdcAtomic(v.maxPriceUSDC)) > 0 && artifactType(v.contentType) && Array.isArray(v.acceptanceCriteria) && v.acceptanceCriteria.length >= 1 && v.acceptanceCriteria.length <= 10 && v.acceptanceCriteria.every(x => publicText(x, 300)) && Number.isInteger(v.expiresInSeconds) && Number(v.expiresInSeconds) >= 60 && Number(v.expiresInSeconds) <= 86400 && timestamp(v.createdAt) && timestamp(v.expiresAt) && ["open", "selected", "expired", "withdrawn", "superseded"].includes(String(v.state)) && (v.state === "selected" ? uuid(v.selectedProposalId) : v.selectedProposalId === null);
730
+ }
731
+ function isInspectionPlan(v) {
732
+ if (!isRecord(v) || !freshExactKeys(v, ["version", "targetUrl", "method", "paymentRecipient", "maxTestAmountAtomic", "maxPaidAttempts"]) || v.version !== "buyer-probe-v1" || v.method !== "GET" || !address(v.paymentRecipient) || v.maxPaidAttempts !== 1 || typeof v.maxTestAmountAtomic !== "string" || !/^(?:0|[1-9][0-9]{0,5}|1000000)$/.test(v.maxTestAmountAtomic) || typeof v.targetUrl !== "string" || v.targetUrl.length > 2048)
733
+ return false;
734
+ try {
735
+ const u = new URL(v.targetUrl);
736
+ return u.protocol === "https:" && !u.username && !u.password && !u.hash && (!u.port || u.port === "443") && u.href === v.targetUrl;
737
+ }
738
+ catch {
739
+ return false;
740
+ }
741
+ }
742
+ function sameInspectionPlan(a, b) { return isInspectionPlan(a) && isInspectionPlan(b) && Object.entries(a).every(([key, value]) => value === b[key]); }
743
+ function isFreshProposal(v) {
744
+ if (!isRecord(v) || !uuid(v.id) || !uuid(v.requestId) || !uuid(v.merchantId) || !address(v.payoutAddress) || !digest(v.termsHash) || !timestamp(v.createdAt) || !isRecord(v.terms) || !publicText(v.terms.note, 300))
745
+ return false;
746
+ if (v.revision === undefined ? v.previousTermsHash !== undefined : !Number.isInteger(v.revision) || Number(v.revision) < 2 || Number(v.revision) > 20 || !digest(v.previousTermsHash) || v.previousTermsHash === v.termsHash)
747
+ return false;
748
+ const t = v.terms;
749
+ if (v.kind === "decline")
750
+ return ["endpoint_unavailable", "unsupported_payment", "scope_unsupported", "capacity_unavailable", "other"].includes(String(t.reason));
751
+ return v.kind === "proposal" && typeof t.capability === "string" && /^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/.test(t.capability) && publicText(t.deliverable, 300) && usdcAtomic(t.priceUSDC) !== undefined && Number(usdcAtomic(t.priceUSDC)) > 0 && timestamp(t.deliveryDeadline) && usdcAtomic(t.testPurchaseBudgetUSDC) !== undefined && (t.settlementMode === "protected_inspection" ? t.testPurchasePayer === "buyer" && isInspectionPlan(t.inspection) && t.inspection.maxTestAmountAtomic === usdcAtomic(t.testPurchaseBudgetUSDC) : (t.settlementMode === undefined || t.settlementMode === "direct_prepayment") && t.inspection === undefined && t.testPurchasePayer === "seller");
752
+ }
753
+ function freshExactKeys(value, keys) {
754
+ return Object.keys(value).length === keys.length && keys.every(k => Object.hasOwn(value, k));
755
+ }
756
+ function isFreshDetail(v, id) {
757
+ if (!isRecord(v) || !isFreshRequest(v.request) || id && v.request.id !== id || !Array.isArray(v.responses) || v.responses.length > 20 || !v.responses.every(isFreshProposal))
758
+ return false;
759
+ const r = v.request, responses = v.responses;
760
+ if (new Set(responses.map(p => p.merchantId)).size !== responses.length || new Set(responses.map(p => p.id)).size !== responses.length || responses.some(p => p.requestId !== r.id || p.kind === "proposal" && BigInt(usdcAtomic(p.terms.priceUSDC)) > BigInt(usdcAtomic(r.maxPriceUSDC))))
761
+ return false;
762
+ if (r.state !== "selected")
763
+ return v.workTicketHandoff === null && v.protectedWorkHandoff === null;
764
+ const p = responses.find(p => p.id === r.selectedProposalId), h = v.workTicketHandoff;
765
+ if (p?.kind === "proposal" && p.terms.settlementMode === "protected_inspection") {
766
+ const x = v.protectedWorkHandoff;
767
+ if (h !== null || !isRecord(x) || x.kind !== "protected_inspection" || x.path !== "/v1/protected-inspections/prepare" || !isRecord(x.task))
768
+ return false;
769
+ return r.contentType === "application/json" && x.seller === p.payoutAddress && x.amountAtomic === usdcAtomic(p.terms.priceUSDC) && x.deliveryDeadline === Math.floor(Date.parse(p.terms.deliveryDeadline) / 1000) && x.fundingRequired === true && x.buyerProbeRequired === true && x.paymentAuthorized === false && x.task.version === "funded-inspection-v1" && x.task.requestId === r.id && x.task.proposalId === p.id && x.task.proposalTermsHash === p.termsHash && sameInspectionPlan(x.task.plan, p.terms.inspection) && freshExactKeys(x, ["kind", "path", "task", "seller", "amountAtomic", "deliveryDeadline", "fundingRequired", "buyerProbeRequired", "paymentAuthorized"]) && freshExactKeys(x.task, ["version", "requestId", "proposalId", "proposalTermsHash", "plan"]);
770
+ }
771
+ if (v.protectedWorkHandoff !== null)
772
+ return false;
773
+ if (!p || p.kind !== "proposal" || !isRecord(h) || h.kind !== "work_ticket_grant" || h.method !== "POST" || h.path !== "/v1/work-tickets/challenges" || h.buyerWalletRequired !== true || h.grantSignatureRequired !== true || h.paymentAuthorized !== false || h.quoteAcceptanceRequired !== true || h.tracksTicketCreation !== false || !isRecord(h.body) || !isRecord(h.body.input))
774
+ return false;
775
+ const b = h.body, i = b.input;
776
+ if (!freshExactKeys(h, ["kind", "method", "path", "body", "buyerWalletRequired", "grantSignatureRequired", "paymentAuthorized", "quoteAcceptanceRequired", "tracksTicketCreation"]) || !freshExactKeys(b, ["merchantId", "capability", "input", "maxPriceUSDC", "expiresInSeconds"]) || !freshExactKeys(i, ["workRequestId", "proposalId", "proposalTermsHash", "title", "scope", "contentType", "acceptanceCriteria", "payoutAddress", "deliverable", "proposalNote", "deliveryDeadline", "testPurchaseBudgetUSDC", "testPurchasePayer"]))
777
+ return false;
778
+ return i.title === r.title && i.contentType === r.contentType && i.payoutAddress === p.payoutAddress && i.proposalNote === p.terms.note && b.merchantId === p.merchantId && b.capability === p.terms.capability && b.maxPriceUSDC === p.terms.priceUSDC && b.expiresInSeconds === 3600 && !Object.hasOwn(b, "buyer") && i.workRequestId === r.id && i.proposalId === p.id && i.proposalTermsHash === p.termsHash && i.scope === r.description && JSON.stringify(i.acceptanceCriteria) === JSON.stringify(r.acceptanceCriteria) && i.deliverable === p.terms.deliverable && i.deliveryDeadline === p.terms.deliveryDeadline && i.testPurchaseBudgetUSDC === p.terms.testPurchaseBudgetUSDC && i.testPurchasePayer === "seller";
779
+ }
780
+ function isFreshWorkResponse(method, path, v, body) {
781
+ const args = isRecord(body) ? body : {}, id = path.match(/^\/v1\/(?:agent\/)?work-requests\/([^/?]+)/)?.[1];
782
+ if (path.endsWith("/agreement-template"))
783
+ return validAgreementTemplate(v, id);
784
+ if (path.endsWith("/execution-challenges"))
785
+ return uuid(v.challengeId) && nonempty(v.message) && timestamp(v.expiresAt);
786
+ if (path.endsWith("/execution"))
787
+ return validWorkExecution(v, id);
788
+ const challenge = () => uuid(v.challengeId) && nonempty(v.message) && timestamp(v.expiresAt);
789
+ if (path === "/v1/work-requests/challenges")
790
+ return challenge() && timestamp(v.requestExpiresAt) && digest(v.policyHash) && Date.parse(String(v.expiresAt)) <= Date.parse(String(v.requestExpiresAt));
791
+ if (path === "/v1/work-requests" && method === "POST")
792
+ return isFreshDetail(v) && typeof v.replay === "boolean" && v.request.supersedesRequestId === args.supersedesRequestId && v.request.title === String(args.title).trim() && v.request.description === String(args.description).trim() && v.request.contentType === args.contentType && v.request.expiresInSeconds === args.expiresInSeconds && usdcAtomic(v.request.maxPriceUSDC) === usdcAtomic(args.maxPriceUSDC) && JSON.stringify(v.request.acceptanceCriteria) === JSON.stringify(args.acceptanceCriteria?.map(x => typeof x === 'string' ? x.trim() : x));
793
+ if (path.startsWith("/v1/work-requests?") || path === "/v1/work-requests" && method === "GET")
794
+ return Array.isArray(v.items) && v.items.length <= 50 && v.items.every(isFreshRequest) && (v.nextCursor === null || Number.isSafeInteger(v.nextCursor) && Number(v.nextCursor) >= 0);
795
+ if (path.endsWith("/withdrawal-challenges"))
796
+ return challenge();
797
+ if (path.endsWith("/withdrawals"))
798
+ return isFreshDetail(v, id) && v.request.state === "withdrawn" && typeof v.replay === "boolean";
799
+ const responseId = path.match(/\/responses\/([^/]+)\/(?:history|revisions)$/)?.[1];
800
+ if (path.endsWith("/history")) {
801
+ if (v.requestId !== id || v.responseId !== responseId || !Array.isArray(v.versions) || v.versions.length < 1 || v.versions.length > 20 || !v.versions.every(isFreshProposal))
802
+ return false;
803
+ const versions = v.versions;
804
+ return versions.every((p, i) => p.id === responseId && p.requestId === id && p.merchantId === versions[0].merchantId && (i === 0 ? p.revision === undefined && p.previousTermsHash === undefined : p.revision === i + 1 && p.previousTermsHash === versions[i - 1].termsHash));
805
+ }
806
+ if (path.endsWith("/revisions")) {
807
+ if (!isFreshProposal(v.response) || v.response.id !== responseId || v.response.requestId !== id || v.response.kind !== args.kind || v.response.previousTermsHash !== args.expectedTermsHash || !isRecord(args.terms) || typeof v.replay !== "boolean")
808
+ return false;
809
+ const terms = v.response.terms;
810
+ return Object.keys(terms).length === Object.keys(args.terms).length && Object.entries(args.terms).every(([k, x]) => k === "inspection" ? sameInspectionPlan(terms[k], x) : ["priceUSDC", "testPurchaseBudgetUSDC"].includes(k) ? usdcAtomic(terms[k]) === usdcAtomic(x) : JSON.stringify(terms[k]) === JSON.stringify(typeof x === 'string' ? x.trim() : x));
811
+ }
812
+ if (path.endsWith("/selection-challenges"))
813
+ return challenge() && isFreshProposal(v.proposal) && v.proposal.kind === "proposal" && v.proposal.requestId === id && v.proposal.id === args.proposalId;
814
+ if (path.endsWith("/proposals") || path.endsWith("/declines")) {
815
+ if (!isFreshProposal(v.response) || v.response.requestId !== id || v.response.kind !== (path.endsWith("/proposals") ? "proposal" : "decline") || typeof v.replay !== "boolean")
816
+ return false;
817
+ const terms = v.response.terms;
818
+ return Object.entries(args).every(([k, x]) => k === "inspection" ? sameInspectionPlan(terms[k], x) : ["priceUSDC", "testPurchaseBudgetUSDC"].includes(k) ? usdcAtomic(terms[k]) === usdcAtomic(x) : JSON.stringify(terms[k]) === JSON.stringify(typeof x === 'string' ? x.trim() : x));
819
+ }
820
+ return isFreshDetail(v, id) && (method === "GET" || v.request.state === "selected" && typeof v.replay === "boolean");
821
+ }
822
+ export { ProtectedInspectionClient, ProtectedInspectionApiError } from "./protected-inspection.js";
823
+ function validAgreementReference(v, id) {
824
+ return isRecord(v) && freshExactKeys(v, ["protocol", "requestId", "proposalId", "proposalTermsHash", "settlementMode"]) && v.protocol === "402mob.work-agreement.v1" && uuid(v.requestId) && (!id || v.requestId === id) && uuid(v.proposalId) && digest(v.proposalTermsHash) && v.settlementMode === "direct_prepayment";
825
+ }
826
+ function validAgreementTemplate(v, id) {
827
+ if (!validAgreementReference(v.agreement, id) || !isRecord(v.grant) || !isRecord(v.grant.input) || !validAgreementReference(v.grant.agreement, id) || stableJson(v.agreement) !== stableJson(v.grant.agreement))
828
+ return false;
829
+ const g = v.grant, i = g.input;
830
+ return freshExactKeys(v, ["agreement", "grant", "tracksTicketCreation", "paymentAuthorized", "grantSignatureRequired", "quoteAcceptanceRequired"]) && freshExactKeys(g, ["merchantId", "capability", "input", "maxPriceUSDC", "expiresInSeconds", "agreement"]) && uuid(g.merchantId) && typeof g.capability === "string" && /^[a-z0-9][a-z0-9-]{1,62}[a-z0-9]$/.test(g.capability) && usdcAtomic(g.maxPriceUSDC) !== undefined && BigInt(usdcAtomic(g.maxPriceUSDC)) > 0n && g.expiresInSeconds === 3600 && i.workRequestId === v.agreement.requestId && i.proposalId === v.agreement.proposalId && i.proposalTermsHash === v.agreement.proposalTermsHash && artifactType(i.contentType) && address(i.payoutAddress) && timestamp(i.deliveryDeadline) && publicText(i.deliverable, 300) && i.testPurchasePayer === "seller" && v.tracksTicketCreation === true && v.paymentAuthorized === false && v.grantSignatureRequired === true && v.quoteAcceptanceRequired === true;
831
+ }
832
+ function validWorkExecution(v, id) {
833
+ if (!freshExactKeys(v, ["agreement", "execution"]))
834
+ return false;
835
+ if (v.agreement === null)
836
+ return v.execution === null;
837
+ if (!isRecord(v.agreement) || !isRecord(v.execution))
838
+ return false;
839
+ const a = v.agreement, e = v.execution;
840
+ const reference = { protocol: a.protocol, requestId: a.requestId, proposalId: a.proposalId, proposalTermsHash: a.proposalTermsHash, settlementMode: a.settlementMode };
841
+ return validAgreementReference(reference, id) && uuid(a.ticketId) && uuid(a.merchantId) && address(a.buyer) && address(a.payTo) && atomicAmount(a.amountAtomic) && publicText(a.deliverable, 300) && artifactType(a.contentType) && timestamp(a.deliveryDeadline) && timestamp(a.createdAt) && e.ticketId === a.ticketId && workTicketStates.includes(e.state) && (e.paymentOperationId === null || uuid(e.paymentOperationId)) && (e.paymentState === null || ["executing", "staged", "settling", "pending", "settled", "failed", "expired"].includes(String(e.paymentState))) && ((e.paymentOperationId === null) === (e.paymentState === null)) && typeof e.resultAvailable === "boolean" && (!e.resultAvailable || digest(e.resultHash)) && (e.resultHash === null || digest(e.resultHash)) && (e.buyerVerdict === null || e.buyerVerdict === "accepted" || e.buyerVerdict === "disputed") && e.deliveryDeadline === a.deliveryDeadline && typeof e.deadlinePassed === "boolean" && (e.retentionExpiresAt === null || timestamp(e.retentionExpiresAt));
842
+ }
@@ -0,0 +1,2 @@
1
+ export declare const inspectionSchemaHash = "8ce432ff8bb61355db7c2d01e7a5048ec20ed0688087df7094134788a81c81e7";
2
+ export declare const inspectionSchemas: Record<string, unknown>;