m2m-market 2.4.1 → 2.6.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 +59 -55
- package/adapters.d.ts +20 -0
- package/adapters.js +56 -0
- package/index.d.ts +42 -0
- package/index.js +165 -3
- package/matching.js +106 -0
- package/package.json +2 -2
- package/protocols.js +1 -1
package/README.md
CHANGED
|
@@ -99,67 +99,71 @@ try {
|
|
|
99
99
|
console.log(await M2MConnectionClient.fromEnvironment().testConnection());
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
## Buy an x402
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
102
|
+
## Buy an x402 service
|
|
103
|
+
`buyExternal` is the one method for buying from the x402 Bazaar. Describe what you
|
|
104
|
+
need and give the data to send. M2M finds a listing, matches your data to its
|
|
105
|
+
input schema by exact field name, and buys it. M2M pays the seller in USDC on
|
|
106
|
+
Base and charges your Agent's M2M balance, within the limits M2M sets for your
|
|
107
|
+
account. Nothing is invented: a field you do not supply is never filled in, and
|
|
108
|
+
no language model builds the request.
|
|
108
109
|
```js
|
|
109
|
-
|
|
110
|
-
const
|
|
110
|
+
// Check first. Nothing is charged, journaled or signed.
|
|
111
|
+
const plan = await client.buyExternal("convert currencies", { amount: 100, from: "USD", to: "GBP" }, { dryRun: true });
|
|
112
|
+
console.log(plan.status, plan.purchase, plan.alternatives);
|
|
111
113
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
+
// Then buy. maxPriceUsdc is optional and can only lower the ceiling.
|
|
115
|
+
const result = await client.buyExternal("convert currencies", { amount: 100, from: "USD", to: "GBP" }, { maxPriceUsdc: "0.01" });
|
|
116
|
+
console.log(result.status, result.purchase);
|
|
114
117
|
```
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
`
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
118
|
+
Your Agent token policy and the account limits always apply, whether or not you
|
|
119
|
+
set `maxPriceUsdc`. Search matches whole words.
|
|
120
|
+
|
|
121
|
+
| `status` | Meaning |
|
|
122
|
+
|---|---|
|
|
123
|
+
| a purchase status (`completed`, `pending`, `paid_request_rejected`, ...) | A listing was bought. The result has `purchase`, `candidate_id`, `idempotency_key` and `attempts`. |
|
|
124
|
+
| `planned` | `dryRun` only. Nothing was charged. `alternatives` lists other listings with price and any missing fields. |
|
|
125
|
+
| `needs_input` | No listing could be built from your data. `candidates` (up to 3) each list `description`, `input_schema`, `missing` (such as `body.city`) and `invalid`. Nothing was charged. Add the fields and call again. |
|
|
126
|
+
| `no_match` | Nothing matched `need`. |
|
|
127
|
+
| `over_price_cap` | Every match costs more than `maxPriceUsdc`. |
|
|
128
|
+
|
|
129
|
+
### Giving the data
|
|
130
|
+
- **By field name:** `{ city: "Paris" }`. A value goes to the body or the query, whichever the listing's schema names. Names must match the schema exactly.
|
|
131
|
+
- **Whole body or query:** `inputs.body` and `inputs.query` are sent as given. Use them for listings with no schema.
|
|
132
|
+
- **GET or POST:** you never choose. M2M uses the method the listing declares.
|
|
133
|
+
|
|
134
|
+
Put sensitive values in the body, not the query. Query values are stored with the
|
|
135
|
+
purchase record; only a hash of the body is stored.
|
|
136
|
+
|
|
137
|
+
### Choosing a listing
|
|
138
|
+
By default `buyExternal` buys the cheapest listing your data satisfies. To buy a
|
|
139
|
+
specific one, take its `candidate_id` from `alternatives` or `candidates` and pass
|
|
140
|
+
it with the same `need` and `inputs`:
|
|
128
141
|
```js
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
142
|
+
await client.buyExternal("convert currencies", { amount: 100, from: "USD", to: "GBP" },
|
|
143
|
+
{ candidateId: "m2m-federated-candidate-v1-..." });
|
|
144
|
+
```
|
|
145
|
+
With `candidateId` and a `null` need, the request is sent as given:
|
|
146
|
+
`{ body, query }` as inputs, and `idempotencyKey` is used as is.
|
|
147
|
+
|
|
148
|
+
### Safety rules
|
|
149
|
+
- Another listing is tried only after a refusal that happened before any charge, at most 3 in all.
|
|
150
|
+
- After a charge, a `pending` result or `paid_request_rejected`, the call stops. A different seller is never tried.
|
|
151
|
+
- Each attempt uses its own key derived from your `idempotencyKey` and the listing, so repeating a call never pays twice.
|
|
152
|
+
- Input is checked against the listing's schema before anything is signed or charged. A refusal rejects the promise with the reason in `error.payload.code` (`input_required`, `input_invalid` with a `fields` list, `candidate_not_consumable`, `method_mismatch`, `input_too_large`, and others). Nothing is charged.
|
|
153
|
+
|
|
154
|
+
### Pending and rejected purchases
|
|
155
|
+
If `status` is `pending`, collect the result with the request in `resume`. The same
|
|
156
|
+
key is never paid twice:
|
|
157
|
+
```js
|
|
158
|
+
const done = await client.buyExternal(null, result.resume.inputs, result.resume.options);
|
|
136
159
|
```
|
|
160
|
+
If the seller refuses the paid request, `purchase.status` is `paid_request_rejected`,
|
|
161
|
+
with `http_status`, `method` and `rejection: { http_status, reason }`. The request
|
|
162
|
+
is not retried. The purchase stays pending until M2M checks the payment on the
|
|
163
|
+
chain. It is then released and the charge returned (`reconciled_released`), or, if
|
|
164
|
+
the payment did settle, marked `reconciled_settled` and the charge stands.
|
|
137
165
|
|
|
138
|
-
|
|
139
|
-
purchase record; only a hash of the body is stored. Calls with no `method`,
|
|
140
|
-
`body` or `query` send the same request as before.
|
|
141
|
-
|
|
142
|
-
### Refusals and rejected requests
|
|
143
|
-
|
|
144
|
-
Input is checked against the listing's schema before anything is signed or
|
|
145
|
-
charged. A refusal rejects the promise and nothing is charged. The reason code
|
|
146
|
-
is in the error payload: `candidate_not_consumable`, `method_unknown`,
|
|
147
|
-
`method_unsupported`, `method_mismatch`, `body_not_accepted`,
|
|
148
|
-
`body_type_unsupported`, `input_required`, `input_invalid` (with a `fields` list
|
|
149
|
-
of `path` and `code`), `input_too_large` (413) and `query_conflict`.
|
|
150
|
-
|
|
151
|
-
If the seller refuses the paid request, `purchase.status` is
|
|
152
|
-
`paid_request_rejected`, with `http_status`, `method` and
|
|
153
|
-
`rejection: { http_status, reason }`. The reason is one of `bad_request`,
|
|
154
|
-
`unauthorized`, `payment_required`, `forbidden`, `not_found`,
|
|
155
|
-
`method_not_allowed`, `payload_too_large`, `unsupported_media_type`,
|
|
156
|
-
`unprocessable_input`, `rate_limited`, `seller_error` or `other_non_2xx`. The
|
|
157
|
-
request is not retried. The purchase stays pending
|
|
158
|
-
(`charge_policy: "retained_pending_review"`) until M2M checks the payment on
|
|
159
|
-
the chain. It is then released and the charge is returned, and the status
|
|
160
|
-
becomes `reconciled_released`. If the payment did settle, the status becomes
|
|
161
|
-
`reconciled_settled` and the charge stands. The same applies to
|
|
162
|
-
`seller_error_refund_pending_review`.
|
|
166
|
+
`searchExternal` and `purchaseExternal` are deprecated. They still work and warn.
|
|
163
167
|
|
|
164
168
|
## OpenAI-compatible tool
|
|
165
169
|
|
package/adapters.d.ts
CHANGED
|
@@ -35,3 +35,23 @@ export function createOpenAIToolHandler(
|
|
|
35
35
|
definition: JsonObject;
|
|
36
36
|
handle: (toolCall: { function: { arguments: string } }) => Promise<string>;
|
|
37
37
|
};
|
|
38
|
+
|
|
39
|
+
export const M2M_BUY_EXTERNAL_TOOL_NAME: "buy_external_service";
|
|
40
|
+
export const M2M_BUY_EXTERNAL_TOOL_DESCRIPTION: string;
|
|
41
|
+
export interface BuyExternalToolArguments {
|
|
42
|
+
need: string;
|
|
43
|
+
inputs?: JsonObject;
|
|
44
|
+
candidate_id?: string;
|
|
45
|
+
max_price_usdc?: string;
|
|
46
|
+
dry_run?: boolean;
|
|
47
|
+
}
|
|
48
|
+
export function buyExternalToolDefinition(): JsonObject;
|
|
49
|
+
export class M2MExternalToolAdapter {
|
|
50
|
+
constructor(client: M2MConnectionClient);
|
|
51
|
+
invoke(argumentsValue: BuyExternalToolArguments): Promise<JsonObject>;
|
|
52
|
+
invokeJson(argumentsValue: string | BuyExternalToolArguments): Promise<string>;
|
|
53
|
+
}
|
|
54
|
+
export function createBuyExternalToolHandler(client: M2MConnectionClient): {
|
|
55
|
+
definition: JsonObject;
|
|
56
|
+
handle: (toolCall: { function: { arguments: string } }) => Promise<string>;
|
|
57
|
+
};
|
package/adapters.js
CHANGED
|
@@ -154,3 +154,59 @@ export function createOpenAIToolHandler(client, options = {}) {
|
|
|
154
154
|
handle: (toolCall) => adapter.invokeJson(toolCall.function.arguments),
|
|
155
155
|
};
|
|
156
156
|
}
|
|
157
|
+
|
|
158
|
+
export const M2M_BUY_EXTERNAL_TOOL_NAME = "buy_external_service";
|
|
159
|
+
export const M2M_BUY_EXTERNAL_TOOL_DESCRIPTION =
|
|
160
|
+
"Describe what you need and give the data to send. M2M finds a matching paid x402 service, checks your data against its input schema and buys it. If the data does not fit any service the result is needs_input with the fields to add; nothing is charged. Use dry_run to check first.";
|
|
161
|
+
|
|
162
|
+
export function buyExternalToolDefinition() {
|
|
163
|
+
return {
|
|
164
|
+
type: "function",
|
|
165
|
+
function: {
|
|
166
|
+
name: M2M_BUY_EXTERNAL_TOOL_NAME,
|
|
167
|
+
description: M2M_BUY_EXTERNAL_TOOL_DESCRIPTION,
|
|
168
|
+
parameters: {
|
|
169
|
+
type: "object",
|
|
170
|
+
properties: {
|
|
171
|
+
need: { type: "string", description: "What you need, in a few plain words, such as 'token price on Base'." },
|
|
172
|
+
inputs: {
|
|
173
|
+
type: "object",
|
|
174
|
+
description: "Values to send, by field name, such as {\"city\": \"Paris\"}. Use 'body' or 'query' for a whole request body or query as is.",
|
|
175
|
+
additionalProperties: true,
|
|
176
|
+
},
|
|
177
|
+
candidate_id: { type: "string", description: "Optional. Buy this listing, taken from a needs_input or planned result, instead of the cheapest match." },
|
|
178
|
+
max_price_usdc: { type: "string", description: "Optional price ceiling in USDC, such as '0.01'. Account limits always apply." },
|
|
179
|
+
dry_run: { type: "boolean", description: "Check what would be bought without charging." },
|
|
180
|
+
},
|
|
181
|
+
required: ["need"],
|
|
182
|
+
additionalProperties: false,
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export class M2MExternalToolAdapter {
|
|
189
|
+
constructor(client) {
|
|
190
|
+
if (!(client instanceof M2MConnectionClient)) {
|
|
191
|
+
throw new TypeError("M2MExternalToolAdapter requires an M2MConnectionClient");
|
|
192
|
+
}
|
|
193
|
+
this.client = client;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
invoke({ need, inputs, candidate_id, max_price_usdc, dry_run = false }) {
|
|
197
|
+
return this.client.buyExternal(need, inputs, { candidateId: candidate_id, maxPriceUsdc: max_price_usdc, dryRun: dry_run === true });
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async invokeJson(argumentsValue) {
|
|
201
|
+
const parsed = typeof argumentsValue === "string" ? JSON.parse(argumentsValue) : argumentsValue;
|
|
202
|
+
return JSON.stringify(await this.invoke(parsed));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function createBuyExternalToolHandler(client) {
|
|
207
|
+
const adapter = new M2MExternalToolAdapter(client);
|
|
208
|
+
return {
|
|
209
|
+
definition: buyExternalToolDefinition(),
|
|
210
|
+
handle: (toolCall) => adapter.invokeJson(toolCall.function.arguments),
|
|
211
|
+
};
|
|
212
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -48,7 +48,45 @@ export interface ExecuteTaskOptions extends Omit<SubmitOptions, "attemptNumber"
|
|
|
48
48
|
|
|
49
49
|
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
|
|
50
50
|
|
|
51
|
+
export interface BuyExternalOptions {
|
|
52
|
+
/** Pin one listing. With a need, it is found by search and inputs are matched to its schema. Without a need, the request is sent as given and idempotencyKey is used as is. */
|
|
53
|
+
candidateId?: string;
|
|
54
|
+
/** Optional price cap in USDC, for example "0.01". It can only lower the ceiling; Agent token policy and account limits always apply. */
|
|
55
|
+
maxPriceUsdc?: string | number;
|
|
56
|
+
/** Return the validated plan without charging. */
|
|
57
|
+
dryRun?: boolean;
|
|
58
|
+
/** Key for the whole call. Each listing attempt uses a key derived from it, so a repeat never pays twice. */
|
|
59
|
+
idempotencyKey?: string;
|
|
60
|
+
/** Search result limit, 1 to 25. */
|
|
61
|
+
limit?: number;
|
|
62
|
+
}
|
|
63
|
+
export interface BuyExternalCandidate {
|
|
64
|
+
candidate_id: string;
|
|
65
|
+
name: string;
|
|
66
|
+
description?: string;
|
|
67
|
+
price_usdc_base_units: string;
|
|
68
|
+
method: string;
|
|
69
|
+
input_schema: JsonObject;
|
|
70
|
+
/** Required fields not supplied, such as "body.city" or "query.q". */
|
|
71
|
+
missing: string[];
|
|
72
|
+
/** Validation errors from the server, as { path, code }. */
|
|
73
|
+
invalid: JsonObject[];
|
|
74
|
+
}
|
|
75
|
+
export interface BuyExternalResult extends JsonObject {
|
|
76
|
+
/** A purchase status, or planned, needs_input, no_match, over_price_cap. */
|
|
77
|
+
status: string;
|
|
78
|
+
candidate_id?: string;
|
|
79
|
+
idempotency_key?: string;
|
|
80
|
+
attempts?: Array<{ candidate_id: string; outcome: string }>;
|
|
81
|
+
candidates?: BuyExternalCandidate[];
|
|
82
|
+
/** Dry run only: other listings with price and any missing fields. */
|
|
83
|
+
alternatives?: BuyExternalCandidate[];
|
|
84
|
+
/** Present when status is pending: buyExternal(null, resume.inputs, resume.options) collects it. */
|
|
85
|
+
resume?: { inputs: JsonObject; options: BuyExternalOptions };
|
|
86
|
+
}
|
|
51
87
|
export interface PurchaseExternalOptions {
|
|
88
|
+
/** Return the plan without charging, journaling or signing. purchase.status is "planned". */
|
|
89
|
+
dryRun?: boolean;
|
|
52
90
|
/** Reuse the same key to fetch a pending result. A key reused with a different request is refused (409). */
|
|
53
91
|
idempotencyKey?: string;
|
|
54
92
|
/** Must match the listing's method (`consumption.method`). Optional. */
|
|
@@ -85,8 +123,12 @@ export class M2MConnectionClient {
|
|
|
85
123
|
discover(options?: DiscoverOptions): Promise<JsonObject>;
|
|
86
124
|
/** Buy one external x402 Bazaar resource for this Agent. Reuse idempotencyKey to fetch a pending result. */
|
|
87
125
|
/** Find x402 Bazaar resources M2M can buy for this Agent (read-only). */
|
|
126
|
+
/** @deprecated Use buyExternal(need, inputs, { dryRun: true }). */
|
|
88
127
|
searchExternal(intent: string, options?: { limit?: number; cursor?: string }): Promise<JsonObject>;
|
|
128
|
+
/** @deprecated Use buyExternal(null, { body, query }, { candidateId, idempotencyKey }). */
|
|
89
129
|
purchaseExternal(candidateId: string, options?: PurchaseExternalOptions): Promise<JsonObject>;
|
|
130
|
+
/** Find and buy an x402 service. Describe what you need and give your data. This is the only method you need. */
|
|
131
|
+
buyExternal(need: string | null, inputs?: JsonObject | null, options?: BuyExternalOptions): Promise<BuyExternalResult>;
|
|
90
132
|
/** Evidence only; does not change settlement, reputation or ranking. */
|
|
91
133
|
submitAcceptance(queryId: string, options: { acceptanceId: string; accepted: boolean }): Promise<JsonObject>;
|
|
92
134
|
getQueryStatus(queryId: string): Promise<JsonObject>;
|
package/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { matchInputs, usdcToBaseUnits } from './matching.js';
|
|
2
3
|
|
|
3
4
|
export const DEFAULT_API_BASE_URL = "https://api.m2mmarket.ai";
|
|
4
5
|
|
|
@@ -18,6 +19,35 @@ export class M2MNoMatchingServiceError extends M2MConnectionError {
|
|
|
18
19
|
}
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
// Refusals raised before anything is charged. Only these allow trying the next listing.
|
|
23
|
+
const PRE_CHARGE_REFUSALS = new Set([
|
|
24
|
+
"input_required", "input_invalid", "candidate_not_consumable", "method_unknown", "method_unsupported",
|
|
25
|
+
"method_mismatch", "body_not_accepted", "body_type_unsupported", "query_conflict", "input_too_large",
|
|
26
|
+
]);
|
|
27
|
+
const PRE_CHARGE_ATTEMPTS = 3;
|
|
28
|
+
|
|
29
|
+
const warned = new Set();
|
|
30
|
+
function deprecated(name, replacement) {
|
|
31
|
+
if (warned.has(name)) return;
|
|
32
|
+
warned.add(name);
|
|
33
|
+
process.emitWarning(`${name} is deprecated; use ${replacement}`, "DeprecationWarning");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Shape a purchase reply: status, candidate, attempts and, when pending, a resume request.
|
|
37
|
+
function finishExternal(result, candidateId, key, options, attempts) {
|
|
38
|
+
const purchase = result.purchase && typeof result.purchase === "object" ? result.purchase : {};
|
|
39
|
+
const status = String(purchase.status || result.status || "");
|
|
40
|
+
attempts.push({ candidate_id: candidateId, outcome: status });
|
|
41
|
+
const out = { ...result, status, candidate_id: candidateId, attempts };
|
|
42
|
+
if (status === "pending") {
|
|
43
|
+
const values = {};
|
|
44
|
+
if (Object.prototype.hasOwnProperty.call(options, "body")) values.body = options.body;
|
|
45
|
+
if (options.query !== undefined) values.query = options.query;
|
|
46
|
+
out.resume = { inputs: values, options: { candidateId, idempotencyKey: key } };
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
21
51
|
export class M2MConnectionClient {
|
|
22
52
|
constructor({
|
|
23
53
|
connectionToken,
|
|
@@ -178,7 +208,7 @@ export class M2MConnectionClient {
|
|
|
178
208
|
* The same key is never paid twice.
|
|
179
209
|
*/
|
|
180
210
|
/** Find x402 Bazaar resources M2M can buy for this Agent (read-only). Search matches whole words. */
|
|
181
|
-
|
|
211
|
+
_searchExternal(intent, { limit = 10, cursor } = {}) {
|
|
182
212
|
if (!String(intent || "").trim()) throw new Error("intent is required");
|
|
183
213
|
const body = { intent: String(intent).trim(), limit };
|
|
184
214
|
if (cursor) body.cursor = cursor;
|
|
@@ -189,8 +219,9 @@ export class M2MConnectionClient {
|
|
|
189
219
|
* Optional request fields, sent only when supplied (a call without them sends the same JSON as before):
|
|
190
220
|
* method (must match the listing), body (any JSON value, undefined means no body) and query (object).
|
|
191
221
|
* Put sensitive values in the body, not the query. The server validates all of them before anything is paid.
|
|
222
|
+
* dryRun: true charges, journals and signs nothing; purchase.status is "planned" with the request the purchase would use.
|
|
192
223
|
*/
|
|
193
|
-
async
|
|
224
|
+
async _purchaseExternal(candidateId, { idempotencyKey, method, body, query, dryRun = false } = {}) {
|
|
194
225
|
const key = String(idempotencyKey || randomUUID());
|
|
195
226
|
if (key.length < 8 || key.length > 128) throw new Error("idempotencyKey must be 8-128 characters");
|
|
196
227
|
if (!String(candidateId || "").trim()) throw new Error("candidateId is required");
|
|
@@ -207,10 +238,141 @@ export class M2MConnectionClient {
|
|
|
207
238
|
if (method !== undefined && method !== null) payload.method = method.trim().toUpperCase();
|
|
208
239
|
if (body !== undefined) payload.body = body;
|
|
209
240
|
if (query !== undefined && query !== null) payload.query = query;
|
|
241
|
+
if (dryRun) payload.dry_run = true;
|
|
210
242
|
const result = await this.request("POST", "/connect/x402/purchase", payload);
|
|
211
243
|
return { idempotency_key: key, ...result };
|
|
212
244
|
}
|
|
213
245
|
|
|
246
|
+
/** @deprecated Use buyExternal(need, inputs, { dryRun: true }); it also lists alternatives. */
|
|
247
|
+
searchExternal(intent, options) {
|
|
248
|
+
deprecated("searchExternal", "buyExternal(need, inputs, { dryRun: true })");
|
|
249
|
+
return this._searchExternal(intent, options);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** @deprecated Use buyExternal(null, { body, query }, { candidateId, idempotencyKey }). */
|
|
253
|
+
purchaseExternal(candidateId, options) {
|
|
254
|
+
deprecated("purchaseExternal", "buyExternal(null, { body, query }, { candidateId, idempotencyKey })");
|
|
255
|
+
return this._purchaseExternal(candidateId, options);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Find and buy an x402 service. Describe what you need and give your data. This is the only method you need.
|
|
260
|
+
*
|
|
261
|
+
* With `need`, M2M searches the x402 Bazaar, keeps listings it can buy (and, with maxPriceUsdc, priced at or
|
|
262
|
+
* below it), maps `inputs` to each listing's schema by exact field name, and buys the cheapest listing the
|
|
263
|
+
* inputs satisfy. maxPriceUsdc is optional and can only lower the ceiling: the Agent token policy and the
|
|
264
|
+
* account limits always apply. Use inputs.body or inputs.query to give a whole body or query as is.
|
|
265
|
+
*
|
|
266
|
+
* `candidateId` pins one listing. With `need` as well, that listing is found by search and your inputs are
|
|
267
|
+
* matched to its schema. With `need` null, the request is sent as given (inputs.body, inputs.query) and
|
|
268
|
+
* `idempotencyKey` is used as is. That is also how a pending result is collected:
|
|
269
|
+
* client.buyExternal(null, r.resume.inputs, r.resume.options).
|
|
270
|
+
*
|
|
271
|
+
* dryRun charges, journals and signs nothing. The result has status "planned", the chosen listing's method,
|
|
272
|
+
* URL, price and request, and `alternatives`: other listings with price and any missing fields.
|
|
273
|
+
*
|
|
274
|
+
* Resolves with `status`: the purchase status (completed, pending, paid_request_rejected, ...) plus purchase,
|
|
275
|
+
* candidate_id, idempotency_key, attempts and, for pending, `resume`; or planned (dryRun), needs_input (up to 3
|
|
276
|
+
* candidates with description, input_schema, missing, invalid), no_match, over_price_cap.
|
|
277
|
+
*
|
|
278
|
+
* Another listing is tried only after a refusal that happened before any charge, at most 3 in all.
|
|
279
|
+
* After a charge, a pending result or a rejected paid request it stops; a different seller is never tried.
|
|
280
|
+
* Each attempt uses its own key derived from idempotencyKey and the listing.
|
|
281
|
+
*/
|
|
282
|
+
async buyExternal(need, inputs, { candidateId, maxPriceUsdc, dryRun = false, idempotencyKey, limit = 25 } = {}) {
|
|
283
|
+
const text = String(need || "").trim();
|
|
284
|
+
const pinned = String(candidateId || "").trim();
|
|
285
|
+
if (!text && !pinned) throw new Error("need or candidateId is required");
|
|
286
|
+
if (inputs !== undefined && inputs !== null && (typeof inputs !== "object" || Array.isArray(inputs))) {
|
|
287
|
+
throw new TypeError("inputs must be an object");
|
|
288
|
+
}
|
|
289
|
+
const cap = maxPriceUsdc === undefined || maxPriceUsdc === null ? null : usdcToBaseUnits(maxPriceUsdc);
|
|
290
|
+
const callKey = String(idempotencyKey || randomUUID());
|
|
291
|
+
if (callKey.length < 8 || callKey.length > 128) throw new Error("idempotencyKey must be 8-128 characters");
|
|
292
|
+
|
|
293
|
+
if (pinned && !text) {
|
|
294
|
+
const values = inputs || {};
|
|
295
|
+
const options = { idempotencyKey: callKey, dryRun };
|
|
296
|
+
if (Object.prototype.hasOwnProperty.call(values, "body")) options.body = values.body;
|
|
297
|
+
if (values.query && typeof values.query === "object" && !Array.isArray(values.query)) options.query = values.query;
|
|
298
|
+
const result = await this._purchaseExternal(pinned, options);
|
|
299
|
+
return finishExternal(result, pinned, callKey, options, []);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const found = await this._searchExternal(text, { limit });
|
|
303
|
+
let listings = (Array.isArray(found.listings) ? found.listings : []).filter((item) => item && typeof item === "object");
|
|
304
|
+
if (pinned) listings = listings.filter((item) => item.candidate_id === pinned);
|
|
305
|
+
const priced = [];
|
|
306
|
+
listings.forEach((listing, position) => {
|
|
307
|
+
let price;
|
|
308
|
+
try { price = BigInt(String(listing.price_usdc_base_units)); } catch { return; }
|
|
309
|
+
if (listing.candidate_id) priced.push({ position, price, listing });
|
|
310
|
+
});
|
|
311
|
+
if (priced.length === 0) return { status: "no_match", searched: listings.length };
|
|
312
|
+
const affordable = priced.filter((entry) => cap === null || entry.price <= cap);
|
|
313
|
+
if (affordable.length === 0) {
|
|
314
|
+
return { status: "over_price_cap", searched: listings.length, max_price_usdc_base_units: String(cap) };
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
const ranked = affordable.map((entry) => ({ ...entry, built: matchInputs(entry.listing, inputs) }));
|
|
318
|
+
ranked.sort((a, b) => {
|
|
319
|
+
if (a.built.satisfied !== b.built.satisfied) return a.built.satisfied ? -1 : 1;
|
|
320
|
+
if (a.price !== b.price) return a.price < b.price ? -1 : 1;
|
|
321
|
+
return a.position - b.position;
|
|
322
|
+
});
|
|
323
|
+
const usable = ranked.filter((entry) => entry.built.satisfied).slice(0, PRE_CHARGE_ATTEMPTS);
|
|
324
|
+
|
|
325
|
+
const describe = ({ listing, built }, invalid = []) => {
|
|
326
|
+
const declared = listing.input && typeof listing.input === "object" ? listing.input : {};
|
|
327
|
+
const schema = {};
|
|
328
|
+
for (const key of ["body_required", "body_schema", "query_schema", "schema_truncated"]) {
|
|
329
|
+
if (key in declared) schema[key] = declared[key];
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
candidate_id: listing.candidate_id,
|
|
333
|
+
name: listing.name,
|
|
334
|
+
description: listing.description,
|
|
335
|
+
price_usdc_base_units: listing.price_usdc_base_units,
|
|
336
|
+
method: listing.method,
|
|
337
|
+
input_schema: schema,
|
|
338
|
+
missing: [...built.missing],
|
|
339
|
+
invalid: [...invalid],
|
|
340
|
+
};
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
const attempts = [];
|
|
344
|
+
const refused = [];
|
|
345
|
+
for (const entry of usable) {
|
|
346
|
+
const { listing, built } = entry;
|
|
347
|
+
const cid = String(listing.candidate_id);
|
|
348
|
+
const key = createHash("sha256").update(`${callKey}:${cid}`).digest("hex");
|
|
349
|
+
const options = { idempotencyKey: key, dryRun };
|
|
350
|
+
if (listing.method) options.method = String(listing.method);
|
|
351
|
+
if (built.has_body) options.body = built.body;
|
|
352
|
+
if (built.has_query) options.query = built.query;
|
|
353
|
+
let result;
|
|
354
|
+
try {
|
|
355
|
+
result = await this._purchaseExternal(cid, options);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
const code = error instanceof M2MConnectionError ? String((error.payload || {}).code || "") : "";
|
|
358
|
+
if (!PRE_CHARGE_REFUSALS.has(code)) {
|
|
359
|
+
if (error && typeof error === "object") error.attempts = [...attempts, { candidate_id: cid, outcome: code || "error" }];
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
attempts.push({ candidate_id: cid, outcome: code });
|
|
363
|
+
refused.push(describe(entry, (error.payload || {}).fields || []));
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const out = finishExternal(result, cid, key, options, attempts);
|
|
367
|
+
if (dryRun) {
|
|
368
|
+
out.alternatives = ranked.filter((item) => item.listing.candidate_id !== cid).slice(0, 5).map((item) => describe(item));
|
|
369
|
+
}
|
|
370
|
+
return out;
|
|
371
|
+
}
|
|
372
|
+
const candidates = refused.length > 0 ? refused : ranked.slice(0, 3).map((entry) => describe(entry));
|
|
373
|
+
return { status: "needs_input", candidates, attempts };
|
|
374
|
+
}
|
|
375
|
+
|
|
214
376
|
/** Evidence only: does not change settlement, reputation or ranking. */
|
|
215
377
|
submitAcceptance(queryId, { acceptanceId, accepted } = {}) {
|
|
216
378
|
if (typeof accepted !== "boolean") throw new TypeError("accepted must be a boolean");
|
package/matching.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Map an Agent's inputs to the request one x402 Bazaar listing expects.
|
|
2
|
+
//
|
|
3
|
+
// Pure and deterministic: no network, no model. Values are matched to schema
|
|
4
|
+
// properties by exact name and copied unchanged. Nothing is invented. The server
|
|
5
|
+
// validates the final request again before anything is signed or charged, so a
|
|
6
|
+
// local mismatch can only cause a refusal before payment, never a wrong purchase.
|
|
7
|
+
|
|
8
|
+
const USDC_DECIMALS = 6;
|
|
9
|
+
|
|
10
|
+
/** Convert a USDC amount such as "0.01" to base units (6 decimals) as a BigInt, rounding down. */
|
|
11
|
+
export function usdcToBaseUnits(value) {
|
|
12
|
+
const text = String(value ?? "").trim();
|
|
13
|
+
const found = /^(\d+)(?:\.(\d+))?$/.exec(text);
|
|
14
|
+
if (!found) throw new RangeError("maxPriceUsdc must be a decimal number such as '0.01'");
|
|
15
|
+
const fraction = (found[2] || "").slice(0, USDC_DECIMALS).padEnd(USDC_DECIMALS, "0");
|
|
16
|
+
const units = BigInt(found[1]) * 10n ** BigInt(USDC_DECIMALS) + BigInt(fraction || "0");
|
|
17
|
+
if (units <= 0n) throw new RangeError("maxPriceUsdc must be greater than zero");
|
|
18
|
+
return units;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
22
|
+
|
|
23
|
+
function properties(schema) {
|
|
24
|
+
if (!isObject(schema)) return null;
|
|
25
|
+
const known = schema.properties;
|
|
26
|
+
const type = schema.type;
|
|
27
|
+
return (type === undefined || type === null || type === "object") && isObject(known) ? known : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function required(schema) {
|
|
31
|
+
return isObject(schema) && Array.isArray(schema.required)
|
|
32
|
+
? schema.required.filter((name) => typeof name === "string")
|
|
33
|
+
: [];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const has = (object, name) => Object.prototype.hasOwnProperty.call(object, name);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Build the body and query for `listing` from `inputs`.
|
|
40
|
+
* `inputs` may carry values by field name, or an explicit `body` and/or `query` used as given.
|
|
41
|
+
* Returns { satisfied, has_body, body, has_query, query, missing }.
|
|
42
|
+
*/
|
|
43
|
+
export function matchInputs(listing, inputs) {
|
|
44
|
+
const values = isObject(inputs) ? inputs : {};
|
|
45
|
+
const declared = isObject(listing?.input) ? listing.input : {};
|
|
46
|
+
const method = String(listing?.method || "").toUpperCase();
|
|
47
|
+
const missing = [];
|
|
48
|
+
let body = null;
|
|
49
|
+
let hasBody = false;
|
|
50
|
+
const bodyNames = new Set();
|
|
51
|
+
|
|
52
|
+
if (method !== "GET") {
|
|
53
|
+
const bodySchema = declared.body_schema;
|
|
54
|
+
const props = properties(bodySchema);
|
|
55
|
+
const bodyRequired = declared.body_required === true;
|
|
56
|
+
if (has(values, "body")) {
|
|
57
|
+
body = values.body;
|
|
58
|
+
hasBody = true;
|
|
59
|
+
if (props && isObject(body)) {
|
|
60
|
+
for (const name of required(bodySchema)) if (!has(body, name)) missing.push(`body.${name}`);
|
|
61
|
+
}
|
|
62
|
+
} else if (props) {
|
|
63
|
+
body = {};
|
|
64
|
+
for (const name of Object.keys(props)) {
|
|
65
|
+
if (has(values, name)) {
|
|
66
|
+
body[name] = values[name];
|
|
67
|
+
bodyNames.add(name);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
hasBody = bodyRequired || bodyNames.size > 0;
|
|
71
|
+
for (const name of required(bodySchema)) if (!has(body, name)) missing.push(`body.${name}`);
|
|
72
|
+
if (!hasBody) body = null;
|
|
73
|
+
} else if (bodyRequired) {
|
|
74
|
+
missing.push("body");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
let query = null;
|
|
79
|
+
let hasQuery = false;
|
|
80
|
+
const querySchema = declared.query_schema;
|
|
81
|
+
const queryProps = properties(querySchema);
|
|
82
|
+
if (isObject(values.query)) {
|
|
83
|
+
query = values.query;
|
|
84
|
+
hasQuery = true;
|
|
85
|
+
if (queryProps) {
|
|
86
|
+
for (const name of required(querySchema)) if (!has(query, name)) missing.push(`query.${name}`);
|
|
87
|
+
}
|
|
88
|
+
} else if (queryProps) {
|
|
89
|
+
query = {};
|
|
90
|
+
for (const name of Object.keys(queryProps)) {
|
|
91
|
+
if (has(values, name) && !bodyNames.has(name)) query[name] = values[name];
|
|
92
|
+
}
|
|
93
|
+
hasQuery = Object.keys(query).length > 0;
|
|
94
|
+
for (const name of required(querySchema)) if (!has(query, name)) missing.push(`query.${name}`);
|
|
95
|
+
if (!hasQuery) query = null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
satisfied: missing.length === 0,
|
|
100
|
+
has_body: hasBody,
|
|
101
|
+
body: hasBody ? body : null,
|
|
102
|
+
has_query: hasQuery,
|
|
103
|
+
query: hasQuery ? query : null,
|
|
104
|
+
missing,
|
|
105
|
+
};
|
|
106
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "m2m-market",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.6.0",
|
|
4
4
|
"description": "Customer SDK for connecting AI Agents to M2M Market",
|
|
5
5
|
"author": "M2M Market, Inc.",
|
|
6
6
|
"type": "module",
|
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
"./outcomes": {"types": "./outcomes.d.ts", "import": "./outcomes.js"},
|
|
21
21
|
"./reputation": {"types": "./reputation.d.ts", "import": "./reputation.js"}
|
|
22
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"],
|
|
23
|
+
"files": ["index.js", "index.d.ts", "matching.js", "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
24
|
"engines": {"node": ">=18"},
|
|
25
25
|
"scripts": {
|
|
26
26
|
"test": "node --test",
|
package/protocols.js
CHANGED
|
@@ -32,7 +32,7 @@ export async function connectMcp({ accessToken, timeoutMs = 30000, fetchImpl = g
|
|
|
32
32
|
const transport = new sdk.StreamableHTTPClientTransport(new URL(MCP_RESOURCE), {
|
|
33
33
|
fetch: guardedFetch, reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 1000, maxReconnectionDelay: 1000, reconnectionDelayGrowFactor: 1 }
|
|
34
34
|
});
|
|
35
|
-
const client = new sdk.Client({ name: 'm2m-market', version: '2.
|
|
35
|
+
const client = new sdk.Client({ name: 'm2m-market', version: '2.6.0' });
|
|
36
36
|
try { await client.connect(transport); }
|
|
37
37
|
catch { await client.close().catch(() => {}); throw new M2MAPIError('mcp_connection_failed'); }
|
|
38
38
|
return client; // caller closes it in finally; no automatic paid call or replay
|