m2m-market 0.1.1 → 2.0.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/README.md CHANGED
@@ -97,3 +97,7 @@ const tool = await new M2MToolAdapter(
97
97
  ```
98
98
 
99
99
  The dashboard spending policy and owner approval remain authoritative. Request-level limits can only make those controls stricter.
100
+
101
+ ## Company
102
+
103
+ M2M Market is operated by **M2M Market, Inc., a Delaware corporation**. The package remains branded **M2M Market**. Its current `UNLICENSED` package metadata is intentionally unchanged by this corporate-identity update; see the repository's `docs/legal-identity-and-licensing.md` for the licensing-state record.
package/ap2.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ export const AP2_SPEC_VERSION: '0.2';
2
+ export const AP2_SPEC_COMMIT: 'e1ea56db72a6385bce3e5c1112b3a56ce60acb43';
3
+ export const AP2_PROFILE_ID: 'm2m-ap2-v0.2-mandate-v1-es256-root-sd-jwt';
4
+
5
+ export type Ap2Mode = 'direct' | 'autonomous';
6
+ export type Ap2ReasonCode =
7
+ | 'unsupported_ap2_version'
8
+ | 'malformed_mandate'
9
+ | 'invalid_signature'
10
+ | 'issuer_untrusted'
11
+ | 'subject_mismatch'
12
+ | 'delegate_mismatch'
13
+ | 'quote_mismatch'
14
+ | 'amount_exceeds_authorization'
15
+ | 'resource_out_of_scope'
16
+ | 'mandate_expired'
17
+ | 'mandate_revoked'
18
+ | 'replay_detected'
19
+ | 'standing_authorization_not_permitted'
20
+ | 'explicit_mandate_required'
21
+ | 'ap2_valid_but_m2m_policy_refused'
22
+ | 'unsupported_ap2_currency_domain';
23
+
24
+ export interface Ap2MandateBundle {
25
+ profile: string;
26
+ ap2_spec_version: string;
27
+ ap2_spec_commit: string;
28
+ authorization_id: string;
29
+ quote_id: string;
30
+ quote_fingerprint: string;
31
+ authorization_fingerprint: string;
32
+ mode: Ap2Mode;
33
+ checkout_mandate_sd_jwt: string;
34
+ payment_mandate_sd_jwt: string;
35
+ open_checkout_mandate_sd_jwt?: string;
36
+ open_payment_mandate_sd_jwt?: string;
37
+ }
38
+
39
+ export interface Ap2ValidationResult {
40
+ valid: boolean;
41
+ reason_code?: Ap2ReasonCode | null;
42
+ profile: string;
43
+ mode?: Ap2Mode;
44
+ principal_id?: string;
45
+ delegate_id?: string;
46
+ authorization_id?: string;
47
+ plan_id?: string;
48
+ intent_id?: string;
49
+ quote_id?: string;
50
+ quote_fingerprint?: string;
51
+ amount?: Record<string, unknown>;
52
+ provider_id?: string;
53
+ service_id?: string;
54
+ valid_from?: number;
55
+ valid_until?: number;
56
+ policy_decision_reference?: string;
57
+ mandate_id?: string;
58
+ }
59
+
60
+ export interface Ap2ReceiptEvidence {
61
+ profile: string;
62
+ canonical_receipt_id: string;
63
+ authorization_id?: string;
64
+ quote_id?: string;
65
+ checkout_receipt_claims: Record<string, unknown>;
66
+ payment_receipt_claims: Record<string, unknown>;
67
+ reconciliation_state?: string;
68
+ outcome_verification_status: 'not_performed';
69
+ portable_outcome_verified: false;
70
+ }
71
+
72
+ export interface Ap2AdapterStatus {
73
+ adapter_id: 'm2m.ap2.authorization-evidence';
74
+ protocol: 'AP2';
75
+ protocol_spec_version: '0.2';
76
+ protocol_spec_commit: string;
77
+ profile: string;
78
+ adapter_available: boolean;
79
+ external_signing_enabled: false;
80
+ financial_execution_enabled: false;
81
+ standing_authorization_support: string;
82
+ explicit_mandate_support: boolean;
83
+ outcome_verification_status: 'not_performed';
84
+ }
85
+
86
+ export function validateAp2MandateBundle(value: Record<string, unknown>): Ap2MandateBundle;
87
+ export function validateAp2ValidationResult(value: Record<string, unknown>): Ap2ValidationResult;
88
+ export function validateAp2ReceiptEvidence(value: Record<string, unknown>): Ap2ReceiptEvidence;
89
+ export function validateAp2AdapterStatus(value: Record<string, unknown>): Ap2AdapterStatus;
package/ap2.js ADDED
@@ -0,0 +1,61 @@
1
+ export const AP2_SPEC_VERSION = '0.2';
2
+ export const AP2_SPEC_COMMIT = 'e1ea56db72a6385bce3e5c1112b3a56ce60acb43';
3
+ export const AP2_PROFILE_ID = 'm2m-ap2-v0.2-mandate-v1-es256-root-sd-jwt';
4
+
5
+ function object(value, message) {
6
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(message);
7
+ return value;
8
+ }
9
+ function text(value, message) {
10
+ if (typeof value !== 'string' || !value || value.length > 131072) throw new TypeError(message);
11
+ return value;
12
+ }
13
+
14
+ export function validateAp2MandateBundle(value) {
15
+ const item = object(value, 'Invalid AP2 mandate bundle');
16
+ if (item.profile !== AP2_PROFILE_ID || item.ap2_spec_version !== AP2_SPEC_VERSION) throw new TypeError('Unsupported AP2 protocol version');
17
+ if (item.ap2_spec_commit !== AP2_SPEC_COMMIT) throw new TypeError('Unsupported AP2 specification commit');
18
+ for (const key of ['authorization_id','quote_id','quote_fingerprint','authorization_fingerprint','checkout_mandate_sd_jwt','payment_mandate_sd_jwt']) {
19
+ text(item[key], 'Invalid AP2 mandate bundle');
20
+ }
21
+ if (!['direct','autonomous'].includes(item.mode)) throw new TypeError('Invalid AP2 mandate mode');
22
+ if (item.mode === 'autonomous') {
23
+ text(item.open_checkout_mandate_sd_jwt, 'Autonomous AP2 mandate chain missing');
24
+ text(item.open_payment_mandate_sd_jwt, 'Autonomous AP2 mandate chain missing');
25
+ }
26
+ return structuredClone(item);
27
+ }
28
+
29
+ export function validateAp2ValidationResult(value) {
30
+ const item = object(value, 'Invalid AP2 validation result');
31
+ if (item.profile !== AP2_PROFILE_ID || typeof item.valid !== 'boolean') throw new TypeError('Invalid AP2 validation result');
32
+ if (item.valid) {
33
+ if (item.reason_code !== null && item.reason_code !== undefined) throw new TypeError('Valid AP2 result cannot contain refusal reason');
34
+ for (const key of ['principal_id','delegate_id','authorization_id','quote_id','mandate_id']) text(item[key], 'Invalid AP2 validation result');
35
+ } else {
36
+ text(item.reason_code, 'Invalid AP2 refusal reason');
37
+ }
38
+ return structuredClone(item);
39
+ }
40
+
41
+ export function validateAp2ReceiptEvidence(value) {
42
+ const item = object(value, 'Invalid AP2 receipt evidence');
43
+ if (item.profile !== AP2_PROFILE_ID) throw new TypeError('Invalid AP2 receipt evidence');
44
+ text(item.canonical_receipt_id, 'Invalid AP2 receipt evidence');
45
+ object(item.checkout_receipt_claims, 'Invalid AP2 checkout receipt');
46
+ object(item.payment_receipt_claims, 'Invalid AP2 payment receipt');
47
+ if (item.outcome_verification_status !== 'not_performed' || item.portable_outcome_verified !== false) {
48
+ throw new TypeError('Phase 28 outcome verification must not be claimed');
49
+ }
50
+ return structuredClone(item);
51
+ }
52
+
53
+ export function validateAp2AdapterStatus(value) {
54
+ const item = object(value, 'Invalid AP2 adapter status');
55
+ if (item.adapter_id !== 'm2m.ap2.authorization-evidence' || item.protocol !== 'AP2') throw new TypeError('Invalid AP2 adapter status');
56
+ if (item.protocol_spec_version !== AP2_SPEC_VERSION || item.protocol_spec_commit !== AP2_SPEC_COMMIT) throw new TypeError('Unsupported AP2 protocol version');
57
+ if (item.profile !== AP2_PROFILE_ID) throw new TypeError('Unsupported AP2 proof profile');
58
+ if (item.external_signing_enabled !== false || item.financial_execution_enabled !== false) throw new TypeError('Unsafe Phase 27 adapter gate state');
59
+ if (item.outcome_verification_status !== 'not_performed') throw new TypeError('Phase 28 boundary violation');
60
+ return structuredClone(item);
61
+ }
@@ -0,0 +1,11 @@
1
+ import type { JsonObject } from './procurement.js';
2
+ export type CommercialModelName = 'fixed' | 'maximum_actual' | 'per_unit' | 'metered_session' | 'subscription' | 'capacity_reservation' | 'outcome_based';
3
+ export type ReconciliationState = 'fully_settled' | 'settled_below_reservation_released' | 'pending_authoritative_actual' | 'pending_external_settlement' | 'refund_pending' | 'partially_refunded' | 'fully_refunded' | 'failed_before_irreversible_action' | 'unknown_completion_reconciliation_required' | 'irreconcilable_inconsistent_evidence';
4
+ export interface CommercialModel extends JsonObject { schema_name: 'canonical_commercial_model_v1'; schema_version: '1.0.0'; object_type: 'CommercialModel'; model: CommercialModelName; authority_reference: string; maximum_exposure_base_units: string; pricing: JsonObject; refund_policy: JsonObject; autonomous_recurring_charge_enabled: false; start_at?: number; expires_at?: number; outcome_state?: string; }
5
+ export interface MeterEvent extends JsonObject { schema_name: 'canonical_meter_event_v1'; schema_version: '1.0.0'; object_type: 'MeterEvent'; transaction_id: string; session_id: string; service_version: string; meter_type: string; unit: string; previous_value: string; new_value: string; delta: string; authoritative_source: string; event_id: string; timestamp: number; evidence_reference?: string | null; evidence_hash?: string | null; event_fingerprint: string; }
6
+ export interface Refund extends JsonObject { schema_name: 'canonical_refund_v1'; schema_version: '1.0.0'; object_type: 'Refund'; refund_id: string; transaction_id: string; original_settlement_id: string; amount_base_units: string; reason: string; actor_reference: string; authorization_reference: string; rail_id: string; external_state: 'not_external' | 'pending_external' | 'verified_external'; transfer_verified: boolean; reconciliation_state: 'recorded' | 'refund_pending'; refund_fingerprint: string; }
7
+ export interface CommercialReconciliation extends JsonObject { schema_name: 'canonical_commercial_reconciliation_v1'; schema_version: '1.0.0'; object_type: 'CommercialReconciliation'; transaction_id: string; reconciliation_state: ReconciliationState; reserved_amount_base_units: string; actual_amount_base_units: string | null; release_amount_base_units: string | null; refunded_amount_base_units: string; automatic_financial_retry: false; alternate_rail_fallback: false; reconciliation_id: string; }
8
+ export function validateCommercialModel(value: JsonObject): CommercialModel;
9
+ export function validateMeterEvent(value: JsonObject): MeterEvent;
10
+ export function validateRefund(value: JsonObject): Refund;
11
+ export function validateCommercialReconciliation(value: JsonObject): CommercialReconciliation;
package/commercial.js ADDED
@@ -0,0 +1,30 @@
1
+ // Phase 23 representation-only commercial accounting validators. No financial actions.
2
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
3
+ const AMOUNT = /^(0|[1-9][0-9]{0,77})$/;
4
+ const POSITIVE_AMOUNT = /^[1-9][0-9]{0,77}$/;
5
+ const MODELS = new Set(['fixed','maximum_actual','per_unit','metered_session','subscription','capacity_reservation','outcome_based']);
6
+ const STATES = new Set(['fully_settled','settled_below_reservation_released','pending_authoritative_actual','pending_external_settlement','refund_pending','partially_refunded','fully_refunded','failed_before_irreversible_action','unknown_completion_reconciliation_required','irreconcilable_inconsistent_evidence']);
7
+ export function validateCommercialModel(value) {
8
+ if (!object(value) || value.schema_name !== 'canonical_commercial_model_v1' || value.schema_version !== '1.0.0' || value.object_type !== 'CommercialModel' || !MODELS.has(value.model)) throw new TypeError('Unsupported commercial model');
9
+ if (typeof value.maximum_exposure_base_units !== 'string' || !AMOUNT.test(value.maximum_exposure_base_units) || BigInt(value.maximum_exposure_base_units) <= 0n || BigInt(value.maximum_exposure_base_units) > (1n << 256n) - 1n) throw new TypeError('Invalid maximum exposure');
10
+ if (!object(value.pricing) || !object(value.refund_policy) || value.autonomous_recurring_charge_enabled !== false) throw new TypeError('Incomplete commercial model');
11
+ return structuredClone(value);
12
+ }
13
+ export function validateMeterEvent(value) {
14
+ if (!object(value) || value.schema_name !== 'canonical_meter_event_v1' || value.schema_version !== '1.0.0' || value.object_type !== 'MeterEvent') throw new TypeError('Unsupported meter event');
15
+ for (const key of ['previous_value','new_value','delta']) if (typeof value[key] !== 'string' || !AMOUNT.test(value[key])) throw new TypeError('Meter values must be exact integer strings');
16
+ if (BigInt(value.new_value) < BigInt(value.previous_value) || BigInt(value.delta) !== BigInt(value.new_value) - BigInt(value.previous_value) || value.authoritative_source === 'client_assertion') throw new TypeError('Invalid authoritative meter event');
17
+ return structuredClone(value);
18
+ }
19
+ export function validateRefund(value) {
20
+ if (!object(value) || value.schema_name !== 'canonical_refund_v1' || value.schema_version !== '1.0.0' || value.object_type !== 'Refund') throw new TypeError('Unsupported refund');
21
+ if (typeof value.amount_base_units !== 'string' || !POSITIVE_AMOUNT.test(value.amount_base_units) || BigInt(value.amount_base_units) > (1n << 256n) - 1n) throw new TypeError('Invalid refund amount');
22
+ for (const key of ['refund_id','transaction_id','original_settlement_id','reason','actor_reference','authorization_reference','rail_id','refund_fingerprint']) if (typeof value[key] !== 'string' || !value[key]) throw new TypeError('Refund authority/provenance is incomplete');
23
+ if (!['not_external','pending_external','verified_external'].includes(value.external_state) || typeof value.transfer_verified !== 'boolean' || !['recorded','refund_pending'].includes(value.reconciliation_state)) throw new TypeError('Invalid refund rail/reconciliation state');
24
+ return structuredClone(value);
25
+ }
26
+ export function validateCommercialReconciliation(value) {
27
+ if (!object(value) || value.schema_name !== 'canonical_commercial_reconciliation_v1' || value.schema_version !== '1.0.0' || value.object_type !== 'CommercialReconciliation' || !STATES.has(value.reconciliation_state)) throw new TypeError('Unsupported reconciliation');
28
+ if (value.automatic_financial_retry !== false || value.alternate_rail_fallback !== false) throw new TypeError('Unsafe retry/fallback state');
29
+ return structuredClone(value);
30
+ }
package/index.d.ts CHANGED
@@ -41,7 +41,7 @@ export class M2MConnectionClient {
41
41
  connectionToken: string;
42
42
  timeoutMs: number;
43
43
  constructor(options: M2MConnectionClientOptions);
44
- static fromEnvironment(env?: NodeJS.ProcessEnv): M2MConnectionClient;
44
+ static fromEnvironment(env?: Record<string, string | undefined>): M2MConnectionClient;
45
45
  request(method: string, path: string, body?: JsonObject): Promise<JsonObject>;
46
46
  testConnection(): Promise<JsonObject>;
47
47
  submit(options: SubmitOptions): Promise<JsonObject>;
@@ -51,5 +51,12 @@ export class M2MConnectionClient {
51
51
  queryId: string,
52
52
  options?: { timeoutMs?: number; pollMs?: number },
53
53
  ): Promise<JsonObject>;
54
+ purchase(options: ExecuteTaskOptions): Promise<JsonObject>;
55
+ /** @deprecated Use purchase. */
54
56
  executeTask(options: ExecuteTaskOptions): Promise<JsonObject>;
55
57
  }
58
+
59
+ export * from "./procurement.js";
60
+ export * from "./protocols.js";
61
+ export * from "./procurement-adapters.js";
62
+ export * from "./commercial.js";
package/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
1
3
  export const DEFAULT_API_BASE_URL = "https://api.m2mmarket.ai";
2
4
 
3
5
  export class M2MConnectionError extends Error {
@@ -49,7 +51,7 @@ export class M2MConnectionClient {
49
51
  Accept: "application/json",
50
52
  "Content-Type": "application/json",
51
53
  Authorization: `Bearer ${this.connectionToken}`,
52
- "X-Request-Id": crypto.randomUUID(),
54
+ "X-Request-Id": randomUUID(),
53
55
  },
54
56
  body: body === undefined ? undefined : JSON.stringify(body),
55
57
  signal: controller.signal,
@@ -131,14 +133,17 @@ export class M2MConnectionClient {
131
133
  throw new M2MConnectionError(`Query ${queryId} did not finish in time`);
132
134
  }
133
135
 
134
- async executeTask({
136
+ /** @deprecated Use purchase; Connect failover semantics are unchanged. */
137
+ executeTask(options) { return this.purchase(options); }
138
+
139
+ async purchase({
135
140
  category,
136
141
  payload,
137
142
  maximumPriceM2m,
138
143
  minimumReputation,
139
144
  maximumAttempts = 1,
140
145
  responseFormat = "JSON",
141
- taskId = `task-${crypto.randomUUID().replaceAll("-", "")}`,
146
+ taskId = `task-${randomUUID().replaceAll("-", "")}`,
142
147
  queryTimeoutMs = 60000,
143
148
  }) {
144
149
  maximumAttempts = Number(maximumAttempts);
@@ -191,3 +196,8 @@ export class M2MConnectionClient {
191
196
  });
192
197
  }
193
198
  }
199
+
200
+ export { M2MClient, M2MAPIError, A2AClient, candidateReference, validateQuoteResult, validateBaseUrl } from './procurement.js';
201
+ export { connectMcp, mcpScopes, MCP_RESOURCE } from './protocols.js';
202
+ export { M2MProcurementTools } from './procurement-adapters.js';
203
+ export { validateCommercialModel, validateMeterEvent, validateRefund, validateCommercialReconciliation } from './commercial.js';
package/mpp.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ export type MppMethod = 'tempo' | 'stripe';
2
+ export type MppIntent = 'charge' | 'session' | 'subscription';
3
+
4
+ export interface MppChallenge {
5
+ id: string;
6
+ realm: string;
7
+ method: MppMethod;
8
+ intent: MppIntent;
9
+ request: Record<string, unknown>;
10
+ expires?: string;
11
+ digest?: string;
12
+ description?: string;
13
+ opaque?: string;
14
+ header?: 'Payment-Authorization';
15
+ }
16
+
17
+ export interface MppReceipt {
18
+ method: MppMethod;
19
+ status: 'success';
20
+ reference: string;
21
+ timestamp: string;
22
+ externalId?: string;
23
+ intent?: MppIntent;
24
+ challengeId?: string;
25
+ channelId?: string;
26
+ acceptedCumulative?: string;
27
+ spent?: string;
28
+ units?: number;
29
+ txHash?: string;
30
+ subscriptionId?: string;
31
+ }
32
+
33
+ export interface MppAdapterStatus {
34
+ adapter_id: 'm2m.mpp';
35
+ protocol_spec: 'draft-httpauth-payment-01';
36
+ adapter_available: boolean;
37
+ live_financial_execution_enabled: false;
38
+ webhook_processing_enabled: false;
39
+ supported_method_intents: {
40
+ tempo: ['charge', 'session', 'subscription'];
41
+ stripe: ['charge'];
42
+ };
43
+ }
44
+
45
+ export function validateMppChallenge(value: unknown): MppChallenge;
46
+ export function validateMppReceipt(value: unknown): MppReceipt;
47
+ export function validateMppAdapterStatus(value: unknown): MppAdapterStatus;
package/mpp.js ADDED
@@ -0,0 +1,74 @@
1
+ const allowed = new Map([
2
+ ['tempo', new Set(['charge', 'session', 'subscription'])],
3
+ ['stripe', new Set(['charge'])],
4
+ ]);
5
+ const rawCardKeys = new Set(['pan','cardnumber','card_number','cvv','cvc','track1','track2','raw_card','cardcredentials','primaryaccountnumber']);
6
+
7
+ function text(value) {
8
+ if (typeof value !== 'string' || !value || value.length > 4096) throw new TypeError('Invalid MPP text');
9
+ return value;
10
+ }
11
+
12
+ function exact(value) {
13
+ if (typeof value !== 'string' || !/^(0|[1-9][0-9]{0,77})$/.test(value) || BigInt(value) > (1n << 256n) - 1n) {
14
+ throw new TypeError('MPP amount must be exact base units');
15
+ }
16
+ return value;
17
+ }
18
+
19
+ function safe(value) {
20
+ if (Array.isArray(value)) {
21
+ for (const child of value) safe(child);
22
+ } else if (value && typeof value === 'object') {
23
+ for (const [key, child] of Object.entries(value)) {
24
+ const normalized = key.toLowerCase().replaceAll('-', '_');
25
+ if (rawCardKeys.has(normalized) || rawCardKeys.has(normalized.replaceAll('_', ''))) {
26
+ throw new TypeError('Raw card data is forbidden');
27
+ }
28
+ safe(child);
29
+ }
30
+ } else if (typeof value === 'number' && !Number.isInteger(value)) {
31
+ throw new TypeError('Floating point payment values are forbidden');
32
+ }
33
+ }
34
+
35
+ export function validateMppChallenge(value) {
36
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid MPP challenge');
37
+ safe(value);
38
+ for (const key of ['id', 'realm', 'method', 'intent']) text(value[key]);
39
+ if (!allowed.get(value.method)?.has(value.intent)) throw new TypeError('Unsupported MPP method/intent');
40
+ if (!value.request || typeof value.request !== 'object' || Array.isArray(value.request)) throw new TypeError('MPP request is missing');
41
+ if ('amount' in value.request) exact(value.request.amount);
42
+ if (value.header !== undefined && value.header !== 'Payment-Authorization') throw new TypeError('Unsupported MPP credential header');
43
+ return structuredClone(value);
44
+ }
45
+
46
+ export function validateMppReceipt(value) {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.status !== 'success') throw new TypeError('Invalid MPP receipt');
48
+ safe(value);
49
+ const method = text(value.method);
50
+ text(value.reference);
51
+ text(value.timestamp);
52
+ if (!allowed.has(method)) throw new TypeError('Unsupported MPP method');
53
+ if ('spent' in value) {
54
+ const spent = BigInt(exact(value.spent));
55
+ const accepted = BigInt(exact(value.acceptedCumulative));
56
+ if (spent > accepted) throw new TypeError('MPP session spend exceeds authorization');
57
+ if (!Number.isInteger(value.units) || value.units < 0) throw new TypeError('Invalid MPP metered units');
58
+ if (value.reference !== value.channelId) throw new TypeError('MPP session reference mismatch');
59
+ }
60
+ return structuredClone(value);
61
+ }
62
+
63
+ export function validateMppAdapterStatus(value) {
64
+ if (!value || typeof value !== 'object' || Array.isArray(value) || value.adapter_id !== 'm2m.mpp') {
65
+ throw new TypeError('Invalid MPP adapter status');
66
+ }
67
+ if (value.protocol_spec !== 'draft-httpauth-payment-01') throw new TypeError('Unsupported MPP protocol version');
68
+ if (value.live_financial_execution_enabled !== false || value.webhook_processing_enabled !== false) {
69
+ throw new TypeError('Unsafe Phase 26 adapter gate state');
70
+ }
71
+ const expected = JSON.stringify({ tempo: ['charge','session','subscription'], stripe: ['charge'] });
72
+ if (JSON.stringify(value.supported_method_intents) !== expected) throw new TypeError('Unsupported MPP method capability set');
73
+ return structuredClone(value);
74
+ }
package/outcomes.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ export type VerificationDecision = 'verified_success' | 'verified_failure' | 'indeterminate';
2
+ export interface VerificationResult extends Record<string, unknown> {
3
+ schema_name: 'canonical_verification_result_v1'; schema_version: '1.0.0';
4
+ verification_id: string; transaction_id: string; decision: VerificationDecision; verification_status: VerificationDecision;
5
+ verification_policy_fingerprint: string; request_hash: string; result_hash: string; evidence_hash: string;
6
+ verification_decision_fingerprint: string; reason_codes: string[]; terminal: boolean;
7
+ }
8
+ export interface PortableReceipt extends Record<string, unknown> {
9
+ schema_name: 'canonical_procurement_receipt_v1'; schema_version: '1.0.0'; receipt_id: string; transaction_id: string;
10
+ verification_decision: VerificationDecision; verification_id: string; request_hash: string; result_hash: string;
11
+ verification_policy_fingerprint: string; integrity_fingerprint: string; rail_evidence?: Partial<Record<'native'|'x402'|'mpp'|'ap2', Record<string, unknown>>>;
12
+ }
13
+ export interface VerificationStatus extends Record<string, unknown> {
14
+ status: 'not_started' | 'awaiting_buyer_acceptance' | VerificationDecision;
15
+ verification?: VerificationResult | null;
16
+ }
17
+ export function validateVerificationResult(value: Record<string, unknown>): VerificationResult;
18
+ export function validatePortableReceipt(value: Record<string, unknown>): PortableReceipt;
19
+ export function validateVerificationStatus(value: Record<string, unknown>): VerificationStatus;
20
+ export class M2MOutcomeClient {
21
+ constructor(client: { _request(method: string, path: string, input?: Record<string, unknown>): Promise<Record<string, unknown>> });
22
+ getVerification(transactionId: string): Promise<VerificationStatus>;
23
+ getPortableReceipt(transactionId: string): Promise<PortableReceipt>;
24
+ submitBuyerAcceptance(transactionId: string, input: { acceptanceId: string; accepted: boolean }): Promise<VerificationStatus>;
25
+ }
package/outcomes.js ADDED
@@ -0,0 +1,56 @@
1
+ /** Phase 28 outcome-verification SDK companion. No automatic retries. */
2
+ const HEX64 = /^[0-9a-f]{64}$/;
3
+ const TX = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,511}$/;
4
+ const DECISIONS = new Set(['verified_success', 'verified_failure', 'indeterminate']);
5
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
6
+
7
+ function transactionId(value) {
8
+ if (typeof value !== 'string' || !TX.test(value)) throw new TypeError('Invalid canonical transaction ID');
9
+ return value;
10
+ }
11
+
12
+ export function validateVerificationResult(value) {
13
+ if (!object(value) || value.schema_name !== 'canonical_verification_result_v1' || value.schema_version !== '1.0.0') throw new TypeError('Unsupported verification result schema');
14
+ if (!DECISIONS.has(value.decision) || value.verification_status !== value.decision) throw new TypeError('Invalid verification decision');
15
+ for (const field of ['verification_policy_fingerprint', 'request_hash', 'result_hash', 'evidence_hash', 'verification_decision_fingerprint']) {
16
+ if (typeof value[field] !== 'string' || !HEX64.test(value[field])) throw new TypeError('Verification integrity hash is invalid');
17
+ }
18
+ if (!Array.isArray(value.reason_codes) || value.reason_codes.some((item) => typeof item !== 'string') || typeof value.terminal !== 'boolean') throw new TypeError('Verification result fields are invalid');
19
+ return structuredClone(value);
20
+ }
21
+
22
+ export function validatePortableReceipt(value) {
23
+ if (!object(value) || value.schema_name !== 'canonical_procurement_receipt_v1' || value.schema_version !== '1.0.0') throw new TypeError('Unsupported portable receipt schema');
24
+ for (const field of ['request_hash', 'result_hash', 'verification_policy_fingerprint', 'integrity_fingerprint']) {
25
+ if (typeof value[field] !== 'string' || !HEX64.test(value[field])) throw new TypeError('Portable receipt integrity hash is invalid');
26
+ }
27
+ if (!DECISIONS.has(value.verification_decision)) throw new TypeError('Portable receipt verification decision is invalid');
28
+ const rail = value.rail_evidence ?? {};
29
+ if (!object(rail) || Object.keys(rail).some((key) => !['native', 'x402', 'mpp', 'ap2'].includes(key))) throw new TypeError('Portable receipt rail evidence is invalid');
30
+ return structuredClone(value);
31
+ }
32
+
33
+ export function validateVerificationStatus(value) {
34
+ if (!object(value) || !new Set(['not_started', 'awaiting_buyer_acceptance', ...DECISIONS]).has(value.status)) throw new TypeError('Unsupported verification status');
35
+ if (value.verification != null) validateVerificationResult(value.verification);
36
+ return structuredClone(value);
37
+ }
38
+
39
+ export class M2MOutcomeClient {
40
+ constructor(client) {
41
+ if (!client || typeof client._request !== 'function') throw new TypeError('A canonical M2MClient is required');
42
+ this.client = client;
43
+ }
44
+ async getVerification(transactionIdValue) {
45
+ return validateVerificationStatus(await this.client._request('GET', `/procurement/transactions/${transactionId(transactionIdValue)}/verification`));
46
+ }
47
+ async getPortableReceipt(transactionIdValue) {
48
+ return validatePortableReceipt(await this.client._request('GET', `/procurement/transactions/${transactionId(transactionIdValue)}/receipt`));
49
+ }
50
+ async submitBuyerAcceptance(transactionIdValue, { acceptanceId, accepted } = {}) {
51
+ const tx = transactionId(transactionIdValue);
52
+ if (typeof acceptanceId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(acceptanceId)) throw new TypeError('Invalid buyer acceptance ID');
53
+ if (typeof accepted !== 'boolean') throw new TypeError('Buyer acceptance must be an explicit boolean');
54
+ return validateVerificationStatus(await this.client._request('POST', `/procurement/transactions/${tx}/buyer-acceptance`, { acceptance_id: acceptanceId, accepted }));
55
+ }
56
+ }
package/package.json CHANGED
@@ -1,63 +1,35 @@
1
1
  {
2
2
  "name": "m2m-market",
3
- "version": "0.1.1",
3
+ "version": "2.0.0",
4
4
  "description": "Customer SDK for connecting AI Agents to M2M Market",
5
+ "author": "M2M Market, Inc.",
5
6
  "type": "module",
6
7
  "main": "./index.js",
7
8
  "types": "./index.d.ts",
8
9
  "exports": {
9
- ".": {
10
- "types": "./index.d.ts",
11
- "import": "./index.js"
12
- },
13
- "./adapters": {
14
- "types": "./adapters.d.ts",
15
- "import": "./adapters.js"
16
- }
17
- },
18
- "files": [
19
- "index.js",
20
- "index.d.ts",
21
- "adapters.js",
22
- "adapters.d.ts",
23
- "README.md"
24
- ],
25
- "engines": {
26
- "node": ">=18"
10
+ ".": {"types": "./index.d.ts", "import": "./index.js"},
11
+ "./adapters": {"types": "./adapters.d.ts", "import": "./adapters.js"},
12
+ "./procurement": {"types": "./procurement.d.ts", "import": "./procurement.js"},
13
+ "./protocols": {"types": "./protocols.d.ts", "import": "./protocols.js"},
14
+ "./procurement-adapters": {"types": "./procurement-adapters.d.ts", "import": "./procurement-adapters.js"},
15
+ "./payments": {"types": "./payments.d.ts", "import": "./payments.js"},
16
+ "./commercial": {"types": "./commercial.d.ts", "import": "./commercial.js"},
17
+ "./x402": {"types": "./x402.d.ts", "import": "./x402.js"},
18
+ "./mpp": {"types": "./mpp.d.ts", "import": "./mpp.js"},
19
+ "./ap2": {"types": "./ap2.d.ts", "import": "./ap2.js"},
20
+ "./outcomes": {"types": "./outcomes.d.ts", "import": "./outcomes.js"},
21
+ "./reputation": {"types": "./reputation.d.ts", "import": "./reputation.js"}
27
22
  },
23
+ "files": ["index.js", "index.d.ts", "adapters.js", "adapters.d.ts", "README.md", "procurement.js", "procurement.d.ts", "protocols.js", "protocols.d.ts", "procurement-adapters.js", "procurement-adapters.d.ts", "payments.js", "payments.d.ts", "commercial.js", "commercial.d.ts", "x402.js", "x402.d.ts", "mpp.js", "mpp.d.ts", "ap2.js", "ap2.d.ts", "outcomes.js", "outcomes.d.ts", "reputation.js", "reputation.d.ts"],
24
+ "engines": {"node": ">=18"},
28
25
  "scripts": {
29
26
  "test": "node --test",
30
- "check": "node --check index.js && node --check adapters.js && npm test"
27
+ "check": "node --check index.js && node --check adapters.js && node --check procurement.js && node --check protocols.js && node --check procurement-adapters.js && node --check payments.js && node --check commercial.js && node --check x402.js && node --check mpp.js && node --check ap2.js && node --check outcomes.js && node --check reputation.js && npm test"
31
28
  },
32
- "keywords": [
33
- "ai-agent",
34
- "api-marketplace",
35
- "machine-to-machine",
36
- "sdk"
37
- ],
29
+ "keywords": ["ai-agent", "api-marketplace", "machine-to-machine", "sdk"],
38
30
  "license": "UNLICENSED",
39
- "repository": {
40
- "type": "git",
41
- "url": "git+https://github.com/castronyabola/m2m-marketplace-mvp.git",
42
- "directory": "m2m-marketplace-mvp/sdk/node"
43
- },
44
- "peerDependencies": {
45
- "@langchain/core": ">=0.3 <2",
46
- "openai": ">=4 <7",
47
- "zod": ">=3.23 <5"
48
- },
49
- "peerDependenciesMeta": {
50
- "@langchain/core": {
51
- "optional": true
52
- },
53
- "openai": {
54
- "optional": true
55
- },
56
- "zod": {
57
- "optional": true
58
- }
59
- },
60
- "publishConfig": {
61
- "access": "public"
62
- }
31
+ "repository": {"type": "git", "url": "git+https://github.com/castronyabola/m2m-marketplace-mvp.git", "directory": "m2m-marketplace-mvp/sdk/node"},
32
+ "peerDependencies": {"@langchain/core": ">=0.3 <2", "openai": ">=4 <7", "zod": ">=3.23 <5", "@modelcontextprotocol/client": "2.0.0"},
33
+ "peerDependenciesMeta": {"@langchain/core": {"optional": true}, "openai": {"optional": true}, "zod": {"optional": true}, "@modelcontextprotocol/client": {"optional": true}},
34
+ "publishConfig": {"access": "public"}
63
35
  }
package/payments.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { CommercialQuote, JsonObject, QuoteResult } from './procurement.js';
2
+ export interface PaymentAsset { asset: string; network: string; decimals: number; chain_id: number | null; contract_address: string | null; }
3
+ export interface PaymentPayer { principal_id: string; account_reference: string; wallet_address: string | null; wallet_kind: string; ownership_reference: string; authorization_reference: string; }
4
+ export interface PaymentDestination { provider_id: string; service_id: string; }
5
+ export interface ReversalCapabilities { release_before_execution: boolean; full_refund: boolean; partial_refund: boolean; protocol_native_reversal: boolean; no_reversal_after_finality: boolean; }
6
+ export interface SettlementOption {
7
+ interface_version: '1.0.0'; settlement_option_id: string; adapter_id: string; rail_id: string; asset: PaymentAsset;
8
+ amount_base_units: string; protocol_fee_base_units: string; provider_net_base_units: string;
9
+ payer: PaymentPayer; destination: PaymentDestination; source_quote_fingerprint: string;
10
+ commercial_authority_reference: string; policy_reference: string; rail_costs: JsonObject[];
11
+ rail_cost_status: 'not_quoted_execution_disabled' | 'no_additional_rail_cost';
12
+ execution_supported: boolean; execution_owner: string; reversal_capabilities: ReversalCapabilities;
13
+ }
14
+ export interface PaymentAwareCommercialQuote extends CommercialQuote { settlement_options?: SettlementOption[]; }
15
+ export type PaymentState = 'not_started' | 'pending' | 'completed' | 'failed_before_irreversible_action' | 'rejected' | 'unknown_completion' | 'reconciled';
16
+ export interface PaymentResult {
17
+ payment_id: string; state: PaymentState; possible_irreversible_action: boolean; finality_confirmed: boolean;
18
+ evidence_reference: string | null; reconciliation_outcome: 'completed' | 'not_executed' | null;
19
+ automatic_retry: false; alternative_rail_fallback: false; commercial_outcome_verified: false;
20
+ reconciliation_required: boolean; safe_release_before_execution: boolean;
21
+ }
22
+ export interface PaymentSelection {
23
+ interface_version: '1.0.0'; payment_id: string; binding_fingerprint: string; adapter_id: string;
24
+ quote_id: string; authorization_id: string; settlement_option: SettlementOption;
25
+ automatic_retry: false; alternative_rail_fallback: false; financial_action_authorized: false;
26
+ }
27
+ export type PaymentAwareQuoteResult = QuoteResult & { commercial_quote?: PaymentAwareCommercialQuote };
28
+ /** Wire validation only. No rail selection, financial authorization, signing or retries. */
29
+ export function validatePaymentQuoteResult(value: JsonObject): PaymentAwareQuoteResult;
package/payments.js ADDED
@@ -0,0 +1,30 @@
1
+ // Additive SDK v2 payment models. No network, payment, signing or retry behavior.
2
+ import { validateQuoteResult } from './procurement.js';
3
+
4
+ export function validatePaymentQuoteResult(value) {
5
+ const result = validateQuoteResult(value);
6
+ const quote = result.commercial_quote;
7
+ if (!quote || !Object.hasOwn(quote, 'settlement_options')) return result;
8
+ const options = quote.settlement_options;
9
+ if (!Array.isArray(options) || options.length < 1 || options.length > 32) throw new TypeError('Invalid settlement options');
10
+ const seen = new Set();
11
+ for (const option of options) {
12
+ if (!option || typeof option !== 'object' || Array.isArray(option) || option.interface_version !== '1.0.0') throw new TypeError('Unsupported settlement option');
13
+ for (const key of ['settlement_option_id', 'adapter_id', 'rail_id', 'source_quote_fingerprint', 'commercial_authority_reference', 'policy_reference']) {
14
+ if (typeof option[key] !== 'string' || !option[key]) throw new TypeError('Invalid settlement identity');
15
+ }
16
+ if (seen.has(option.adapter_id)) throw new TypeError('Ambiguous settlement adapter');
17
+ seen.add(option.adapter_id);
18
+ for (const key of ['amount_base_units', 'protocol_fee_base_units', 'provider_net_base_units']) {
19
+ const amount = option[key];
20
+ if (typeof amount !== 'string' || !/^(0|[1-9][0-9]{0,77})$/.test(amount) || BigInt(amount) > (1n << 256n) - 1n) throw new TypeError('Settlement amount must be an exact base-unit string');
21
+ }
22
+ const asset = option.asset;
23
+ if (!asset || typeof asset !== 'object' || !Number.isInteger(asset.decimals) || asset.decimals < 0 || asset.decimals > 255 || ['asset', 'network'].some(k => typeof asset[k] !== 'string' || !asset[k])) throw new TypeError('Invalid settlement asset');
24
+ if (['payer', 'destination', 'reversal_capabilities'].some(k => !option[k] || typeof option[k] !== 'object' || Array.isArray(option[k]))) throw new TypeError('Incomplete settlement context');
25
+ if (!Array.isArray(option.rail_costs) || option.rail_costs.length || !['no_additional_rail_cost', 'not_quoted_execution_disabled'].includes(option.rail_cost_status)) throw new TypeError('Unsupported rail cost representation');
26
+ if (typeof option.execution_supported !== 'boolean') throw new TypeError('Invalid execution capability');
27
+ if (option.rail_cost_status === 'not_quoted_execution_disabled' && option.execution_supported) throw new TypeError('Incomplete costs cannot imply execution capability');
28
+ }
29
+ return result;
30
+ }
@@ -0,0 +1,7 @@
1
+ import type { M2MClient, JsonObject } from './procurement.js';
2
+ export class M2MProcurementTools {
3
+ constructor(client: M2MClient, options?: { allowPurchase?: boolean });
4
+ definitions(options?: { api?: 'chat' | 'responses' }): JsonObject[];
5
+ invoke(name: string, args: string | { request: JsonObject }): Promise<JsonObject>;
6
+ asLangchainTools(): Promise<unknown[]>;
7
+ }