m2m-market 0.1.1 → 2.1.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 +31 -1
- package/adapters.js +39 -7
- package/ap2.d.ts +89 -0
- package/ap2.js +61 -0
- package/commercial.d.ts +11 -0
- package/commercial.js +30 -0
- package/index.d.ts +35 -2
- package/index.js +105 -7
- package/mpp.d.ts +47 -0
- package/mpp.js +74 -0
- package/outcomes.d.ts +25 -0
- package/outcomes.js +56 -0
- package/package.json +22 -50
- package/payments.d.ts +29 -0
- package/payments.js +30 -0
- package/procurement-adapters.d.ts +7 -0
- package/procurement-adapters.js +39 -0
- package/procurement.d.ts +65 -0
- package/procurement.js +195 -0
- package/protocols.d.ts +10 -0
- package/protocols.js +39 -0
- package/reputation.d.ts +58 -0
- package/reputation.js +90 -0
- package/x402.d.ts +92 -0
- package/x402.js +100 -0
package/README.md
CHANGED
|
@@ -52,7 +52,33 @@ const result = await client.executeTask({
|
|
|
52
52
|
console.log(result.response);
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
##
|
|
55
|
+
## Ask for an outcome
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
import { M2MConnectionClient, M2MNoMatchingServiceError } from "m2m-market";
|
|
59
|
+
|
|
60
|
+
const client = M2MConnectionClient.fromEnvironment();
|
|
61
|
+
const request = {
|
|
62
|
+
intent: "current weather in Nairobi",
|
|
63
|
+
payload: { city: "Nairobi" },
|
|
64
|
+
requiredCapabilities: ["current_weather"],
|
|
65
|
+
expect: ["temperature_c"],
|
|
66
|
+
maximumPriceM2m: "0.05",
|
|
67
|
+
maximumAttempts: 3, // 1-5; the dashboard policy may lower it
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
// Preview first: no funds are reserved and no Provider is called.
|
|
71
|
+
console.log(await client.discover(request));
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const result = await client.purchase(request);
|
|
75
|
+
console.log(result.response, result.attempts_limited_by_authorization);
|
|
76
|
+
await client.submitAcceptance(result.query_id, { acceptanceId: "job-42", accepted: true }); // evidence only
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (!(error instanceof M2MNoMatchingServiceError)) throw error;
|
|
79
|
+
// Nothing was paid; relax the request or pick another category.
|
|
80
|
+
}
|
|
81
|
+
```
|
|
56
82
|
|
|
57
83
|
```js
|
|
58
84
|
console.log(await M2MConnectionClient.fromEnvironment().testConnection());
|
|
@@ -97,3 +123,7 @@ const tool = await new M2MToolAdapter(
|
|
|
97
123
|
```
|
|
98
124
|
|
|
99
125
|
The dashboard spending policy and owner approval remain authoritative. Request-level limits can only make those controls stricter.
|
|
126
|
+
|
|
127
|
+
## Company
|
|
128
|
+
|
|
129
|
+
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/adapters.js
CHANGED
|
@@ -15,7 +15,27 @@ export function openAIToolDefinition() {
|
|
|
15
15
|
properties: {
|
|
16
16
|
category: {
|
|
17
17
|
type: "string",
|
|
18
|
-
description: "Marketplace service category, such as
|
|
18
|
+
description: "Marketplace service category, such as weather_climate. Provide this or intent.",
|
|
19
|
+
},
|
|
20
|
+
intent: {
|
|
21
|
+
type: "string",
|
|
22
|
+
description: "Plain-language outcome needed, such as 'current weather in Nairobi'. Provide this or category.",
|
|
23
|
+
},
|
|
24
|
+
required_capabilities: {
|
|
25
|
+
type: "array",
|
|
26
|
+
items: { type: "string" },
|
|
27
|
+
description: "Capabilities the service must advertise, such as current_weather.",
|
|
28
|
+
},
|
|
29
|
+
expect: {
|
|
30
|
+
type: "array",
|
|
31
|
+
items: { type: "string" },
|
|
32
|
+
description: "Output fields the result must contain, such as temperature_c.",
|
|
33
|
+
},
|
|
34
|
+
maximum_attempts: {
|
|
35
|
+
type: "integer",
|
|
36
|
+
minimum: 1,
|
|
37
|
+
maximum: 5,
|
|
38
|
+
description: "Provider attempts allowed if a provider fails; the dashboard policy may lower it.",
|
|
19
39
|
},
|
|
20
40
|
payload: {
|
|
21
41
|
type: "object",
|
|
@@ -33,7 +53,7 @@ export function openAIToolDefinition() {
|
|
|
33
53
|
description: "Optional stricter minimum Provider reputation.",
|
|
34
54
|
},
|
|
35
55
|
},
|
|
36
|
-
required: ["
|
|
56
|
+
required: ["payload"],
|
|
37
57
|
additionalProperties: false,
|
|
38
58
|
},
|
|
39
59
|
},
|
|
@@ -51,23 +71,31 @@ export class M2MToolAdapter {
|
|
|
51
71
|
|
|
52
72
|
async invoke({
|
|
53
73
|
category,
|
|
54
|
-
|
|
74
|
+
intent,
|
|
75
|
+
payload = {},
|
|
76
|
+
required_capabilities,
|
|
77
|
+
expect,
|
|
78
|
+
maximum_attempts,
|
|
55
79
|
maximum_price_m2m,
|
|
56
80
|
minimum_reputation,
|
|
57
81
|
}) {
|
|
58
|
-
const result = await this.client.
|
|
82
|
+
const result = await this.client.purchase({
|
|
59
83
|
category,
|
|
84
|
+
intent,
|
|
60
85
|
payload,
|
|
86
|
+
requiredCapabilities: required_capabilities ?? this.defaultPolicy.requiredCapabilities,
|
|
87
|
+
integrationTypes: this.defaultPolicy.integrationTypes,
|
|
88
|
+
expect: expect ?? this.defaultPolicy.expect,
|
|
61
89
|
maximumPriceM2m:
|
|
62
90
|
maximum_price_m2m ?? this.defaultPolicy.maximumPriceM2m,
|
|
63
91
|
minimumReputation:
|
|
64
92
|
minimum_reputation ?? this.defaultPolicy.minimumReputation,
|
|
65
|
-
maximumAttempts: this.defaultPolicy.maximumAttempts ?? 1,
|
|
93
|
+
maximumAttempts: maximum_attempts ?? this.defaultPolicy.maximumAttempts ?? 1,
|
|
66
94
|
responseFormat: this.defaultPolicy.responseFormat ?? "JSON",
|
|
67
95
|
});
|
|
68
96
|
return {
|
|
69
97
|
status: result.status,
|
|
70
|
-
category,
|
|
98
|
+
category: category || intent,
|
|
71
99
|
provider_id: result.provider_id,
|
|
72
100
|
service_id: result.service_id,
|
|
73
101
|
result: result.response,
|
|
@@ -105,8 +133,12 @@ export class M2MToolAdapter {
|
|
|
105
133
|
name: M2M_TOOL_NAME,
|
|
106
134
|
description: M2M_TOOL_DESCRIPTION,
|
|
107
135
|
schema: z.object({
|
|
108
|
-
category: z.string().min(1),
|
|
136
|
+
category: z.string().min(1).optional(),
|
|
137
|
+
intent: z.string().min(1).optional(),
|
|
109
138
|
payload: z.object({}).catchall(z.unknown()),
|
|
139
|
+
required_capabilities: z.array(z.string()).optional(),
|
|
140
|
+
expect: z.array(z.string()).optional(),
|
|
141
|
+
maximum_attempts: z.number().int().min(1).max(5).optional(),
|
|
110
142
|
maximum_price_m2m: z.string().optional(),
|
|
111
143
|
minimum_reputation: z.number().int().min(0).max(100).optional(),
|
|
112
144
|
}),
|
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
|
+
}
|
package/commercial.d.ts
ADDED
|
@@ -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
|
@@ -13,6 +13,9 @@ export class M2MConnectionError extends Error {
|
|
|
13
13
|
constructor(message: string, options?: M2MConnectionErrorOptions);
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
/** No validated service matches the request; nothing was reserved or paid. */
|
|
17
|
+
export class M2MNoMatchingServiceError extends M2MConnectionError {}
|
|
18
|
+
|
|
16
19
|
export interface M2MConnectionClientOptions {
|
|
17
20
|
baseUrl?: string;
|
|
18
21
|
connectionToken: string;
|
|
@@ -21,8 +24,14 @@ export interface M2MConnectionClientOptions {
|
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
export interface SubmitOptions {
|
|
24
|
-
category
|
|
27
|
+
/** Provide category, intent, or both. */
|
|
28
|
+
category?: string;
|
|
29
|
+
intent?: string;
|
|
25
30
|
payload: JsonObject;
|
|
31
|
+
requiredCapabilities?: string[];
|
|
32
|
+
integrationTypes?: string[];
|
|
33
|
+
/** Output fields the result must contain. */
|
|
34
|
+
expect?: string[];
|
|
26
35
|
maximumPriceM2m?: string | number;
|
|
27
36
|
minimumReputation?: number;
|
|
28
37
|
maximumAttempts?: number;
|
|
@@ -36,20 +45,44 @@ export interface ExecuteTaskOptions extends Omit<SubmitOptions, "attemptNumber"
|
|
|
36
45
|
queryTimeoutMs?: number;
|
|
37
46
|
}
|
|
38
47
|
|
|
48
|
+
export interface DiscoverOptions {
|
|
49
|
+
category?: string;
|
|
50
|
+
intent?: string;
|
|
51
|
+
payload?: JsonObject;
|
|
52
|
+
requiredCapabilities?: string[];
|
|
53
|
+
integrationTypes?: string[];
|
|
54
|
+
expect?: string[];
|
|
55
|
+
maximumPriceM2m?: string | number;
|
|
56
|
+
minimumReputation?: number;
|
|
57
|
+
responseFormat?: string;
|
|
58
|
+
limit?: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
39
61
|
export class M2MConnectionClient {
|
|
40
62
|
baseUrl: string;
|
|
41
63
|
connectionToken: string;
|
|
42
64
|
timeoutMs: number;
|
|
43
65
|
constructor(options: M2MConnectionClientOptions);
|
|
44
|
-
static fromEnvironment(env?:
|
|
66
|
+
static fromEnvironment(env?: Record<string, string | undefined>): M2MConnectionClient;
|
|
45
67
|
request(method: string, path: string, body?: JsonObject): Promise<JsonObject>;
|
|
46
68
|
testConnection(): Promise<JsonObject>;
|
|
47
69
|
submit(options: SubmitOptions): Promise<JsonObject>;
|
|
70
|
+
/** Preview matching services without reserving funds or invoking a Provider. */
|
|
71
|
+
discover(options?: DiscoverOptions): Promise<JsonObject>;
|
|
72
|
+
/** Evidence only; does not change settlement, reputation or ranking. */
|
|
73
|
+
submitAcceptance(queryId: string, options: { acceptanceId: string; accepted: boolean }): Promise<JsonObject>;
|
|
48
74
|
getQueryStatus(queryId: string): Promise<JsonObject>;
|
|
49
75
|
getTaskStatus(taskId: string): Promise<JsonObject>;
|
|
50
76
|
waitForQuery(
|
|
51
77
|
queryId: string,
|
|
52
78
|
options?: { timeoutMs?: number; pollMs?: number },
|
|
53
79
|
): Promise<JsonObject>;
|
|
80
|
+
purchase(options: ExecuteTaskOptions): Promise<JsonObject>;
|
|
81
|
+
/** @deprecated Use purchase. */
|
|
54
82
|
executeTask(options: ExecuteTaskOptions): Promise<JsonObject>;
|
|
55
83
|
}
|
|
84
|
+
|
|
85
|
+
export * from "./procurement.js";
|
|
86
|
+
export * from "./protocols.js";
|
|
87
|
+
export * from "./procurement-adapters.js";
|
|
88
|
+
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 {
|
|
@@ -9,6 +11,13 @@ export class M2MConnectionError extends Error {
|
|
|
9
11
|
}
|
|
10
12
|
}
|
|
11
13
|
|
|
14
|
+
export class M2MNoMatchingServiceError extends M2MConnectionError {
|
|
15
|
+
constructor(message, options) {
|
|
16
|
+
super(message, options);
|
|
17
|
+
this.name = "M2MNoMatchingServiceError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
12
21
|
export class M2MConnectionClient {
|
|
13
22
|
constructor({
|
|
14
23
|
connectionToken,
|
|
@@ -49,14 +58,17 @@ export class M2MConnectionClient {
|
|
|
49
58
|
Accept: "application/json",
|
|
50
59
|
"Content-Type": "application/json",
|
|
51
60
|
Authorization: `Bearer ${this.connectionToken}`,
|
|
52
|
-
"X-Request-Id":
|
|
61
|
+
"X-Request-Id": randomUUID(),
|
|
53
62
|
},
|
|
54
63
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
55
64
|
signal: controller.signal,
|
|
56
65
|
});
|
|
57
66
|
const payload = await response.json().catch(() => ({ error: "Invalid API response" }));
|
|
58
67
|
if (!response.ok) {
|
|
59
|
-
|
|
68
|
+
const ErrorClass = payload && payload.code === "no_matching_service"
|
|
69
|
+
? M2MNoMatchingServiceError
|
|
70
|
+
: M2MConnectionError;
|
|
71
|
+
throw new ErrorClass(
|
|
60
72
|
payload.error || payload.message || "M2M request failed",
|
|
61
73
|
{ status: response.status, payload },
|
|
62
74
|
);
|
|
@@ -79,7 +91,11 @@ export class M2MConnectionClient {
|
|
|
79
91
|
|
|
80
92
|
submit({
|
|
81
93
|
category,
|
|
94
|
+
intent,
|
|
82
95
|
payload,
|
|
96
|
+
requiredCapabilities,
|
|
97
|
+
integrationTypes,
|
|
98
|
+
expect,
|
|
83
99
|
maximumPriceM2m,
|
|
84
100
|
minimumReputation,
|
|
85
101
|
maximumAttempts,
|
|
@@ -88,17 +104,23 @@ export class M2MConnectionClient {
|
|
|
88
104
|
attemptNumber = 1,
|
|
89
105
|
excludedCandidates = [],
|
|
90
106
|
}) {
|
|
91
|
-
if (!String(category || "").trim()
|
|
107
|
+
if (!String(category || "").trim() && !String(intent || "").trim()) {
|
|
108
|
+
throw new TypeError("A service category or an intent is required");
|
|
109
|
+
}
|
|
92
110
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
93
111
|
throw new TypeError("Service payload must be an object");
|
|
94
112
|
}
|
|
95
113
|
const body = {
|
|
96
|
-
category: String(category).trim(),
|
|
97
114
|
payload,
|
|
98
115
|
response_format: responseFormat,
|
|
99
116
|
attempt_number: Number(attemptNumber),
|
|
100
117
|
excluded_candidates: [...excludedCandidates],
|
|
101
118
|
};
|
|
119
|
+
if (String(category || "").trim()) body.category = String(category).trim();
|
|
120
|
+
if (String(intent || "").trim()) body.intent = String(intent).trim();
|
|
121
|
+
if (requiredCapabilities?.length) body.required_capabilities = [...requiredCapabilities];
|
|
122
|
+
if (integrationTypes?.length) body.integration_types = [...integrationTypes];
|
|
123
|
+
if (expect?.length) body.expect = [...expect];
|
|
102
124
|
if (maximumPriceM2m !== undefined) body.maximum_price_m2m = String(maximumPriceM2m);
|
|
103
125
|
if (minimumReputation !== undefined) body.minimum_reputation = Number(minimumReputation);
|
|
104
126
|
if (maximumAttempts !== undefined) body.maximum_attempts = Number(maximumAttempts);
|
|
@@ -106,6 +128,50 @@ export class M2MConnectionClient {
|
|
|
106
128
|
return this.request("POST", "/connect/execute", body);
|
|
107
129
|
}
|
|
108
130
|
|
|
131
|
+
/** Preview matching services without reserving funds or invoking a Provider. */
|
|
132
|
+
async discover({
|
|
133
|
+
category,
|
|
134
|
+
intent,
|
|
135
|
+
payload,
|
|
136
|
+
requiredCapabilities,
|
|
137
|
+
integrationTypes,
|
|
138
|
+
expect,
|
|
139
|
+
maximumPriceM2m,
|
|
140
|
+
minimumReputation,
|
|
141
|
+
responseFormat = "JSON",
|
|
142
|
+
limit = 10,
|
|
143
|
+
} = {}) {
|
|
144
|
+
if (!String(category || "").trim() && !String(intent || "").trim()) {
|
|
145
|
+
throw new TypeError("A service category or an intent is required");
|
|
146
|
+
}
|
|
147
|
+
if (payload !== undefined && (!payload || typeof payload !== "object" || Array.isArray(payload))) {
|
|
148
|
+
throw new TypeError("Service payload must be an object");
|
|
149
|
+
}
|
|
150
|
+
const body = { response_format: responseFormat, limit: Number(limit) };
|
|
151
|
+
if (String(category || "").trim()) body.category = String(category).trim();
|
|
152
|
+
if (String(intent || "").trim()) body.intent = String(intent).trim();
|
|
153
|
+
if (payload !== undefined) body.payload = payload;
|
|
154
|
+
if (requiredCapabilities?.length) body.required_capabilities = [...requiredCapabilities];
|
|
155
|
+
if (integrationTypes?.length) body.integration_types = [...integrationTypes];
|
|
156
|
+
if (expect?.length) body.expect = [...expect];
|
|
157
|
+
if (maximumPriceM2m !== undefined) body.maximum_price_m2m = String(maximumPriceM2m);
|
|
158
|
+
if (minimumReputation !== undefined) body.minimum_reputation = Number(minimumReputation);
|
|
159
|
+
const result = await this.request("POST", "/connect/discover", body);
|
|
160
|
+
if (!result.discovery || typeof result.discovery !== "object") {
|
|
161
|
+
throw new M2MConnectionError("Discovery response is missing the discovery record");
|
|
162
|
+
}
|
|
163
|
+
return result.discovery;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Evidence only: does not change settlement, reputation or ranking. */
|
|
167
|
+
submitAcceptance(queryId, { acceptanceId, accepted } = {}) {
|
|
168
|
+
if (typeof accepted !== "boolean") throw new TypeError("accepted must be a boolean");
|
|
169
|
+
return this.request("POST", `/connect/queries/${queryId}/acceptance`, {
|
|
170
|
+
acceptance_id: acceptanceId,
|
|
171
|
+
accepted,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
109
175
|
getQueryStatus(queryId) {
|
|
110
176
|
return this.request("GET", `/connect/queries/${queryId}`);
|
|
111
177
|
}
|
|
@@ -131,20 +197,31 @@ export class M2MConnectionClient {
|
|
|
131
197
|
throw new M2MConnectionError(`Query ${queryId} did not finish in time`);
|
|
132
198
|
}
|
|
133
199
|
|
|
134
|
-
|
|
200
|
+
/** @deprecated Use purchase; Connect failover semantics are unchanged. */
|
|
201
|
+
executeTask(options) { return this.purchase(options); }
|
|
202
|
+
|
|
203
|
+
async purchase({
|
|
135
204
|
category,
|
|
205
|
+
intent,
|
|
136
206
|
payload,
|
|
207
|
+
requiredCapabilities,
|
|
208
|
+
integrationTypes,
|
|
209
|
+
expect,
|
|
137
210
|
maximumPriceM2m,
|
|
138
211
|
minimumReputation,
|
|
139
212
|
maximumAttempts = 1,
|
|
140
213
|
responseFormat = "JSON",
|
|
141
|
-
taskId = `task-${
|
|
214
|
+
taskId = `task-${randomUUID().replaceAll("-", "")}`,
|
|
142
215
|
queryTimeoutMs = 60000,
|
|
143
216
|
}) {
|
|
144
217
|
maximumAttempts = Number(maximumAttempts);
|
|
145
218
|
if (!Number.isInteger(maximumAttempts) || maximumAttempts < 1 || maximumAttempts > 5) {
|
|
146
219
|
throw new TypeError("Maximum attempts must be between 1 and 5");
|
|
147
220
|
}
|
|
221
|
+
if (!String(category || "").trim() && !String(intent || "").trim()) {
|
|
222
|
+
throw new TypeError("A service category or an intent is required");
|
|
223
|
+
}
|
|
224
|
+
const requestedAttempts = maximumAttempts;
|
|
148
225
|
|
|
149
226
|
const attempts = [];
|
|
150
227
|
let attemptNumber = 1;
|
|
@@ -153,7 +230,11 @@ export class M2MConnectionClient {
|
|
|
153
230
|
while (attemptNumber <= maximumAttempts) {
|
|
154
231
|
const accepted = await this.submit({
|
|
155
232
|
category,
|
|
233
|
+
intent,
|
|
156
234
|
payload,
|
|
235
|
+
requiredCapabilities,
|
|
236
|
+
integrationTypes,
|
|
237
|
+
expect,
|
|
157
238
|
maximumPriceM2m,
|
|
158
239
|
minimumReputation,
|
|
159
240
|
maximumAttempts,
|
|
@@ -162,6 +243,11 @@ export class M2MConnectionClient {
|
|
|
162
243
|
attemptNumber,
|
|
163
244
|
excludedCandidates,
|
|
164
245
|
});
|
|
246
|
+
// The dashboard authorization can lower the attempt limit; honour it.
|
|
247
|
+
const serverAttempts = Number(accepted.maximum_attempts);
|
|
248
|
+
if (Number.isInteger(serverAttempts) && serverAttempts >= 1) {
|
|
249
|
+
maximumAttempts = Math.min(maximumAttempts, serverAttempts);
|
|
250
|
+
}
|
|
165
251
|
const terminal = ["settled", "released"].includes(
|
|
166
252
|
String(accepted.lifecycle_state || "").toLowerCase(),
|
|
167
253
|
)
|
|
@@ -178,7 +264,14 @@ export class M2MConnectionClient {
|
|
|
178
264
|
});
|
|
179
265
|
|
|
180
266
|
if (String(terminal.lifecycle_state || "").toLowerCase() === "settled") {
|
|
181
|
-
return {
|
|
267
|
+
return {
|
|
268
|
+
...terminal,
|
|
269
|
+
task_id: taskId,
|
|
270
|
+
attempts,
|
|
271
|
+
requested_attempts: requestedAttempts,
|
|
272
|
+
attempts_limited_by_authorization: maximumAttempts < requestedAttempts,
|
|
273
|
+
autonomous_completion: true,
|
|
274
|
+
};
|
|
182
275
|
}
|
|
183
276
|
|
|
184
277
|
const task = await this.getTaskStatus(taskId);
|
|
@@ -191,3 +284,8 @@ export class M2MConnectionClient {
|
|
|
191
284
|
});
|
|
192
285
|
}
|
|
193
286
|
}
|
|
287
|
+
|
|
288
|
+
export { M2MClient, M2MAPIError, A2AClient, candidateReference, validateQuoteResult, validateBaseUrl } from './procurement.js';
|
|
289
|
+
export { connectMcp, mcpScopes, MCP_RESOURCE } from './protocols.js';
|
|
290
|
+
export { M2MProcurementTools } from './procurement-adapters.js';
|
|
291
|
+
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;
|