m2m-market 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -90
- package/adapters.d.ts +1 -0
- package/adapters.js +3 -2
- package/index.d.ts +31 -4
- package/index.js +141 -29
- package/package.json +1 -1
- package/protocols.js +1 -1
package/README.md
CHANGED
|
@@ -99,109 +99,86 @@ 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
|
```
|
|
118
|
+
Your Agent token policy and the account limits always apply, whether or not you
|
|
119
|
+
set `maxPriceUsdc`. Search matches whole words.
|
|
115
120
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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`. |
|
|
120
128
|
|
|
121
|
-
###
|
|
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.
|
|
122
133
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
`has_query_schema`, `schema_coverage`. M2M always uses the listing's method.
|
|
126
|
-
`method` is optional and must match it.
|
|
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.
|
|
127
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
|
-
// POST with a JSON body
|
|
133
|
-
await client.purchaseExternal(listing.candidate_id, {
|
|
134
|
-
body: { text: "hello", lang: "en" },
|
|
135
|
-
});
|
|
142
|
+
await client.buyExternal("convert currencies", { amount: 100, from: "USD", to: "GBP" },
|
|
143
|
+
{ candidateId: "m2m-federated-candidate-v1-..." });
|
|
136
144
|
```
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
Input is checked against the listing's schema before anything is signed or
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
`
|
|
148
|
-
|
|
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`.
|
|
163
|
-
|
|
164
|
-
## Describe what you need
|
|
165
|
-
`buyExternal` does the search, the listing choice and the request building for
|
|
166
|
-
you. Give a short `need` and the data to send. M2M finds a listing, matches your
|
|
167
|
-
data to its input schema by exact field name, and buys it. Nothing is invented:
|
|
168
|
-
a field you do not supply is never filled in.
|
|
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:
|
|
169
157
|
```js
|
|
170
|
-
const
|
|
171
|
-
"weather forecast",
|
|
172
|
-
{ city: "Paris", units: "metric" }, // values by schema field name
|
|
173
|
-
{ maxPriceUsdc: "0.01" }, // optional, can only lower the ceiling
|
|
174
|
-
);
|
|
175
|
-
console.log(result.status, result.purchase);
|
|
158
|
+
const done = await client.buyExternal(null, result.resume.inputs, result.resume.options);
|
|
176
159
|
```
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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.
|
|
181
165
|
|
|
182
|
-
|
|
183
|
-
|---|---|
|
|
184
|
-
| a purchase status (`completed`, `pending`, `paid_request_rejected`, ...) | A listing was bought. The result has `purchase`, `candidate_id`, `idempotency_key` and `attempts`. |
|
|
185
|
-
| `planned` | `dryRun` only. Nothing was charged. |
|
|
186
|
-
| `needs_input` | No listing could be built from your data. `candidates` (up to 3) each list `input_schema`, `missing` (such as `body.city`) and `invalid`. Nothing was charged. Add the fields and call again. |
|
|
187
|
-
| `no_match` | Nothing matched `need`. |
|
|
188
|
-
| `over_price_cap` | Every match costs more than `maxPriceUsdc`. |
|
|
166
|
+
`searchExternal` and `purchaseExternal` are deprecated. They still work and warn.
|
|
189
167
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
the call
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
named `buy_external_service`.
|
|
168
|
+
## Timing
|
|
169
|
+
Each purchase result has `timing` (milliseconds), so you can see where time went:
|
|
170
|
+
|
|
171
|
+
| Field | Meaning |
|
|
172
|
+
|---|---|
|
|
173
|
+
| `timing.agent.call_total_ms`, `call_ttfb_ms`, `call_ttlb_ms` | Measured by this SDK on your machine: the whole call, time to the first response byte, time to the last byte. Native purchases also have `submit_to_terminal_ms` and `poll_interval_ms`. |
|
|
174
|
+
| `timing.m2m.request_ms`, `response_ms`, `total_ms` | M2M latency: M2M's time before calling the provider, after the provider answered, and both together. |
|
|
175
|
+
| `timing.provider` | M2M's call to the provider: `dns_ms`, `connect_ms` (one network round trip, also `rtt_ms`), `tls_ms`, `sent_ms`, `ttfb_ms` and `ttlb_ms` from the start of the call, the HTTP `status`, and `processing_ms_est` (an estimate of the provider's own processing time). |
|
|
176
|
+
|
|
177
|
+
After a purchase the SDK reports its own figures to M2M without awaiting, so your
|
|
178
|
+
dashboard can also show your network round trip to M2M. The report never delays or
|
|
179
|
+
changes a purchase. It is on by default with the global `fetch`; turn it off with
|
|
180
|
+
`new M2MConnectionClient({ ..., reportTiming: false })`. With your own `fetchImpl`
|
|
181
|
+
it is off unless you pass `reportTiming: true`. A dry run is not reported.
|
|
205
182
|
|
|
206
183
|
## OpenAI-compatible tool
|
|
207
184
|
|
package/adapters.d.ts
CHANGED
package/adapters.js
CHANGED
|
@@ -174,6 +174,7 @@ export function buyExternalToolDefinition() {
|
|
|
174
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
175
|
additionalProperties: true,
|
|
176
176
|
},
|
|
177
|
+
candidate_id: { type: "string", description: "Optional. Buy this listing, taken from a needs_input or planned result, instead of the cheapest match." },
|
|
177
178
|
max_price_usdc: { type: "string", description: "Optional price ceiling in USDC, such as '0.01'. Account limits always apply." },
|
|
178
179
|
dry_run: { type: "boolean", description: "Check what would be bought without charging." },
|
|
179
180
|
},
|
|
@@ -192,8 +193,8 @@ export class M2MExternalToolAdapter {
|
|
|
192
193
|
this.client = client;
|
|
193
194
|
}
|
|
194
195
|
|
|
195
|
-
invoke({ need, inputs, max_price_usdc, dry_run = false }) {
|
|
196
|
-
return this.client.buyExternal(need, inputs, { maxPriceUsdc: max_price_usdc, dryRun: dry_run === true });
|
|
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 });
|
|
197
198
|
}
|
|
198
199
|
|
|
199
200
|
async invokeJson(argumentsValue) {
|
package/index.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export interface M2MConnectionClientOptions {
|
|
|
21
21
|
connectionToken: string;
|
|
22
22
|
timeoutMs?: number;
|
|
23
23
|
fetchImpl?: typeof fetch;
|
|
24
|
+
/** Report this SDK's own timing to M2M after a purchase (best effort). Default: true with the global fetch, false with a custom fetchImpl. */
|
|
25
|
+
reportTiming?: boolean;
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
export interface SubmitOptions {
|
|
@@ -49,6 +51,8 @@ export interface ExecuteTaskOptions extends Omit<SubmitOptions, "attemptNumber"
|
|
|
49
51
|
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
|
|
50
52
|
|
|
51
53
|
export interface BuyExternalOptions {
|
|
54
|
+
/** 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. */
|
|
55
|
+
candidateId?: string;
|
|
52
56
|
/** Optional price cap in USDC, for example "0.01". It can only lower the ceiling; Agent token policy and account limits always apply. */
|
|
53
57
|
maxPriceUsdc?: string | number;
|
|
54
58
|
/** Return the validated plan without charging. */
|
|
@@ -61,6 +65,7 @@ export interface BuyExternalOptions {
|
|
|
61
65
|
export interface BuyExternalCandidate {
|
|
62
66
|
candidate_id: string;
|
|
63
67
|
name: string;
|
|
68
|
+
description?: string;
|
|
64
69
|
price_usdc_base_units: string;
|
|
65
70
|
method: string;
|
|
66
71
|
input_schema: JsonObject;
|
|
@@ -76,8 +81,10 @@ export interface BuyExternalResult extends JsonObject {
|
|
|
76
81
|
idempotency_key?: string;
|
|
77
82
|
attempts?: Array<{ candidate_id: string; outcome: string }>;
|
|
78
83
|
candidates?: BuyExternalCandidate[];
|
|
79
|
-
/**
|
|
80
|
-
|
|
84
|
+
/** Dry run only: other listings with price and any missing fields. */
|
|
85
|
+
alternatives?: BuyExternalCandidate[];
|
|
86
|
+
/** Present when status is pending: buyExternal(null, resume.inputs, resume.options) collects it. */
|
|
87
|
+
resume?: { inputs: JsonObject; options: BuyExternalOptions };
|
|
81
88
|
}
|
|
82
89
|
export interface PurchaseExternalOptions {
|
|
83
90
|
/** Return the plan without charging, journaling or signing. purchase.status is "planned". */
|
|
@@ -118,10 +125,12 @@ export class M2MConnectionClient {
|
|
|
118
125
|
discover(options?: DiscoverOptions): Promise<JsonObject>;
|
|
119
126
|
/** Buy one external x402 Bazaar resource for this Agent. Reuse idempotencyKey to fetch a pending result. */
|
|
120
127
|
/** Find x402 Bazaar resources M2M can buy for this Agent (read-only). */
|
|
128
|
+
/** @deprecated Use buyExternal(need, inputs, { dryRun: true }). */
|
|
121
129
|
searchExternal(intent: string, options?: { limit?: number; cursor?: string }): Promise<JsonObject>;
|
|
130
|
+
/** @deprecated Use buyExternal(null, { body, query }, { candidateId, idempotencyKey }). */
|
|
122
131
|
purchaseExternal(candidateId: string, options?: PurchaseExternalOptions): Promise<JsonObject>;
|
|
123
|
-
/** Describe what you need and give your data.
|
|
124
|
-
buyExternal(need: string, inputs?: JsonObject | null, options?: BuyExternalOptions): Promise<BuyExternalResult>;
|
|
132
|
+
/** Find and buy an x402 service. Describe what you need and give your data. This is the only method you need. */
|
|
133
|
+
buyExternal(need: string | null, inputs?: JsonObject | null, options?: BuyExternalOptions): Promise<BuyExternalResult>;
|
|
125
134
|
/** Evidence only; does not change settlement, reputation or ranking. */
|
|
126
135
|
submitAcceptance(queryId: string, options: { acceptanceId: string; accepted: boolean }): Promise<JsonObject>;
|
|
127
136
|
getQueryStatus(queryId: string): Promise<JsonObject>;
|
|
@@ -141,3 +150,21 @@ export * from "./procurement.js";
|
|
|
141
150
|
export * from "./protocols.js";
|
|
142
151
|
export * from "./procurement-adapters.js";
|
|
143
152
|
export * from "./commercial.js";
|
|
153
|
+
|
|
154
|
+
/** Timing of one purchase: M2M latency, the provider leg and this Agent's own figures (ms). */
|
|
155
|
+
export interface TransactionTiming {
|
|
156
|
+
v: 1;
|
|
157
|
+
m2m: { request_ms: number | null; response_ms: number | null; total_ms: number | null } | null;
|
|
158
|
+
provider: {
|
|
159
|
+
status: number | null; dns_ms: number | null; connect_ms: number | null; tls_ms: number | null;
|
|
160
|
+
sent_ms: number | null; ttfb_ms: number | null; ttlb_ms: number | null; rtt_ms: number | null;
|
|
161
|
+
processing_ms_est: number | null; error: string | null;
|
|
162
|
+
} | null;
|
|
163
|
+
agent?: {
|
|
164
|
+
call_total_ms?: number; call_ttfb_ms?: number; call_ttlb_ms?: number;
|
|
165
|
+
submit_to_terminal_ms?: number; poll_interval_ms?: number;
|
|
166
|
+
rtt_ms?: number | null; waiting_for_result_ms?: number | null;
|
|
167
|
+
} | null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export const SDK_VERSION: string;
|
package/index.js
CHANGED
|
@@ -26,17 +26,55 @@ const PRE_CHARGE_REFUSALS = new Set([
|
|
|
26
26
|
]);
|
|
27
27
|
const PRE_CHARGE_ATTEMPTS = 3;
|
|
28
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
|
+
|
|
51
|
+
export const SDK_VERSION = "2.7.0";
|
|
52
|
+
|
|
53
|
+
const ms = (value) => Math.max(0, Math.round(value));
|
|
54
|
+
|
|
55
|
+
/** result.timing: M2M's view from the response plus this SDK's own figures. */
|
|
56
|
+
function mergeTiming(result, local) {
|
|
57
|
+
if (!local || Object.keys(local).length === 0) return;
|
|
58
|
+
const server = result.timing && typeof result.timing === "object" ? result.timing : {};
|
|
59
|
+
result.timing = { ...server, agent: { ...(server.agent || {}), ...local } };
|
|
60
|
+
}
|
|
61
|
+
|
|
29
62
|
export class M2MConnectionClient {
|
|
30
63
|
constructor({
|
|
31
64
|
connectionToken,
|
|
32
65
|
baseUrl = DEFAULT_API_BASE_URL,
|
|
33
66
|
timeoutMs = 30000,
|
|
34
|
-
fetchImpl
|
|
67
|
+
fetchImpl,
|
|
68
|
+
reportTiming,
|
|
35
69
|
} = {}) {
|
|
36
70
|
this.baseUrl = String(baseUrl || DEFAULT_API_BASE_URL).replace(/\/$/, "");
|
|
37
71
|
this.connectionToken = String(connectionToken || "").trim();
|
|
38
72
|
this.timeoutMs = Math.max(Number(timeoutMs || 30000), 1000);
|
|
39
|
-
this.fetchImpl = fetchImpl;
|
|
73
|
+
this.fetchImpl = fetchImpl ?? globalThis.fetch;
|
|
74
|
+
// Send this SDK's own timing to M2M after a purchase (best effort, never awaited).
|
|
75
|
+
// On by default with the global fetch; off with a custom fetchImpl unless asked for.
|
|
76
|
+
this.reportTiming = reportTiming === undefined ? fetchImpl === undefined : Boolean(reportTiming);
|
|
77
|
+
this._lastTiming = {};
|
|
40
78
|
if (!this.baseUrl.startsWith("https://")) {
|
|
41
79
|
throw new TypeError("M2M connection base URL must use HTTPS");
|
|
42
80
|
}
|
|
@@ -59,6 +97,7 @@ export class M2MConnectionClient {
|
|
|
59
97
|
async request(method, path, body) {
|
|
60
98
|
const controller = new AbortController();
|
|
61
99
|
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
100
|
+
const started = performance.now();
|
|
62
101
|
try {
|
|
63
102
|
const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
64
103
|
method,
|
|
@@ -71,7 +110,14 @@ export class M2MConnectionClient {
|
|
|
71
110
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
72
111
|
signal: controller.signal,
|
|
73
112
|
});
|
|
113
|
+
const headersAt = performance.now();
|
|
74
114
|
const payload = await response.json().catch(() => ({ error: "Invalid API response" }));
|
|
115
|
+
const done = performance.now();
|
|
116
|
+
this._lastTiming = {
|
|
117
|
+
call_total_ms: ms(done - started),
|
|
118
|
+
call_ttfb_ms: ms(headersAt - started),
|
|
119
|
+
call_ttlb_ms: ms(done - started),
|
|
120
|
+
};
|
|
75
121
|
if (!response.ok) {
|
|
76
122
|
const ErrorClass = payload && payload.code === "no_matching_service"
|
|
77
123
|
? M2MNoMatchingServiceError
|
|
@@ -93,6 +139,28 @@ export class M2MConnectionClient {
|
|
|
93
139
|
}
|
|
94
140
|
}
|
|
95
141
|
|
|
142
|
+
/** Report this SDK's timing for one transaction. Fire-and-forget; never throws or delays. */
|
|
143
|
+
_sendTiming(target, agent) {
|
|
144
|
+
if (!this.reportTiming || !agent || agent.call_total_ms === undefined) return;
|
|
145
|
+
const controller = new AbortController();
|
|
146
|
+
const timer = setTimeout(() => controller.abort(), 2000);
|
|
147
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
148
|
+
Promise.resolve()
|
|
149
|
+
.then(() => this.fetchImpl(`${this.baseUrl}/connect/timing`, {
|
|
150
|
+
method: "POST",
|
|
151
|
+
headers: {
|
|
152
|
+
Accept: "application/json",
|
|
153
|
+
"Content-Type": "application/json",
|
|
154
|
+
Authorization: `Bearer ${this.connectionToken}`,
|
|
155
|
+
"X-Request-Id": randomUUID(),
|
|
156
|
+
},
|
|
157
|
+
body: JSON.stringify({ ...target, agent: { ...agent, sdk: `node ${SDK_VERSION}` } }),
|
|
158
|
+
signal: controller.signal,
|
|
159
|
+
}))
|
|
160
|
+
.catch(() => {})
|
|
161
|
+
.finally(() => clearTimeout(timer));
|
|
162
|
+
}
|
|
163
|
+
|
|
96
164
|
testConnection() {
|
|
97
165
|
return this.request("POST", "/connect/test", {});
|
|
98
166
|
}
|
|
@@ -186,7 +254,7 @@ export class M2MConnectionClient {
|
|
|
186
254
|
* The same key is never paid twice.
|
|
187
255
|
*/
|
|
188
256
|
/** Find x402 Bazaar resources M2M can buy for this Agent (read-only). Search matches whole words. */
|
|
189
|
-
|
|
257
|
+
_searchExternal(intent, { limit = 10, cursor } = {}) {
|
|
190
258
|
if (!String(intent || "").trim()) throw new Error("intent is required");
|
|
191
259
|
const body = { intent: String(intent).trim(), limit };
|
|
192
260
|
if (cursor) body.cursor = cursor;
|
|
@@ -199,7 +267,7 @@ export class M2MConnectionClient {
|
|
|
199
267
|
* Put sensitive values in the body, not the query. The server validates all of them before anything is paid.
|
|
200
268
|
* dryRun: true charges, journals and signs nothing; purchase.status is "planned" with the request the purchase would use.
|
|
201
269
|
*/
|
|
202
|
-
async
|
|
270
|
+
async _purchaseExternal(candidateId, { idempotencyKey, method, body, query, dryRun = false } = {}) {
|
|
203
271
|
const key = String(idempotencyKey || randomUUID());
|
|
204
272
|
if (key.length < 8 || key.length > 128) throw new Error("idempotencyKey must be 8-128 characters");
|
|
205
273
|
if (!String(candidateId || "").trim()) throw new Error("candidateId is required");
|
|
@@ -221,26 +289,46 @@ export class M2MConnectionClient {
|
|
|
221
289
|
return { idempotency_key: key, ...result };
|
|
222
290
|
}
|
|
223
291
|
|
|
292
|
+
/** @deprecated Use buyExternal(need, inputs, { dryRun: true }); it also lists alternatives. */
|
|
293
|
+
searchExternal(intent, options) {
|
|
294
|
+
deprecated("searchExternal", "buyExternal(need, inputs, { dryRun: true })");
|
|
295
|
+
return this._searchExternal(intent, options);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** @deprecated Use buyExternal(null, { body, query }, { candidateId, idempotencyKey }). */
|
|
299
|
+
purchaseExternal(candidateId, options) {
|
|
300
|
+
deprecated("purchaseExternal", "buyExternal(null, { body, query }, { candidateId, idempotencyKey })");
|
|
301
|
+
return this._purchaseExternal(candidateId, options);
|
|
302
|
+
}
|
|
303
|
+
|
|
224
304
|
/**
|
|
225
|
-
* Describe what you need and give your data.
|
|
305
|
+
* Find and buy an x402 service. Describe what you need and give your data. This is the only method you need.
|
|
226
306
|
*
|
|
227
|
-
*
|
|
228
|
-
* below it), maps `inputs` to each listing's schema by exact field name, and buys the
|
|
307
|
+
* With `need`, M2M searches the x402 Bazaar, keeps listings it can buy (and, with maxPriceUsdc, priced at or
|
|
308
|
+
* below it), maps `inputs` to each listing's schema by exact field name, and buys the cheapest listing the
|
|
229
309
|
* inputs satisfy. maxPriceUsdc is optional and can only lower the ceiling: the Agent token policy and the
|
|
230
310
|
* account limits always apply. Use inputs.body or inputs.query to give a whole body or query as is.
|
|
231
311
|
*
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
*
|
|
312
|
+
* `candidateId` pins one listing. With `need` as well, that listing is found by search and your inputs are
|
|
313
|
+
* matched to its schema. With `need` null, the request is sent as given (inputs.body, inputs.query) and
|
|
314
|
+
* `idempotencyKey` is used as is. That is also how a pending result is collected:
|
|
315
|
+
* client.buyExternal(null, r.resume.inputs, r.resume.options).
|
|
316
|
+
*
|
|
317
|
+
* dryRun charges, journals and signs nothing. The result has status "planned", the chosen listing's method,
|
|
318
|
+
* URL, price and request, and `alternatives`: other listings with price and any missing fields.
|
|
319
|
+
*
|
|
320
|
+
* Resolves with `status`: the purchase status (completed, pending, paid_request_rejected, ...) plus purchase,
|
|
321
|
+
* candidate_id, idempotency_key, attempts and, for pending, `resume`; or planned (dryRun), needs_input (up to 3
|
|
322
|
+
* candidates with description, input_schema, missing, invalid), no_match, over_price_cap.
|
|
235
323
|
*
|
|
236
324
|
* Another listing is tried only after a refusal that happened before any charge, at most 3 in all.
|
|
237
325
|
* After a charge, a pending result or a rejected paid request it stops; a different seller is never tried.
|
|
238
|
-
* Each attempt uses its own key derived from idempotencyKey and the listing.
|
|
239
|
-
* client.purchaseExternal(r.resume.candidateId, r.resume.options).
|
|
326
|
+
* Each attempt uses its own key derived from idempotencyKey and the listing.
|
|
240
327
|
*/
|
|
241
|
-
async buyExternal(need, inputs, { maxPriceUsdc, dryRun = false, idempotencyKey, limit = 25 } = {}) {
|
|
328
|
+
async buyExternal(need, inputs, { candidateId, maxPriceUsdc, dryRun = false, idempotencyKey, limit = 25 } = {}) {
|
|
242
329
|
const text = String(need || "").trim();
|
|
243
|
-
|
|
330
|
+
const pinned = String(candidateId || "").trim();
|
|
331
|
+
if (!text && !pinned) throw new Error("need or candidateId is required");
|
|
244
332
|
if (inputs !== undefined && inputs !== null && (typeof inputs !== "object" || Array.isArray(inputs))) {
|
|
245
333
|
throw new TypeError("inputs must be an object");
|
|
246
334
|
}
|
|
@@ -248,8 +336,22 @@ export class M2MConnectionClient {
|
|
|
248
336
|
const callKey = String(idempotencyKey || randomUUID());
|
|
249
337
|
if (callKey.length < 8 || callKey.length > 128) throw new Error("idempotencyKey must be 8-128 characters");
|
|
250
338
|
|
|
251
|
-
|
|
252
|
-
|
|
339
|
+
if (pinned && !text) {
|
|
340
|
+
const values = inputs || {};
|
|
341
|
+
const options = { idempotencyKey: callKey, dryRun };
|
|
342
|
+
if (Object.prototype.hasOwnProperty.call(values, "body")) options.body = values.body;
|
|
343
|
+
if (values.query && typeof values.query === "object" && !Array.isArray(values.query)) options.query = values.query;
|
|
344
|
+
const result = await this._purchaseExternal(pinned, options);
|
|
345
|
+
const local = { ...this._lastTiming };
|
|
346
|
+
const out = finishExternal(result, pinned, callKey, options, []);
|
|
347
|
+
mergeTiming(out, local);
|
|
348
|
+
if (!dryRun) this._sendTiming({ idempotency_key: callKey }, local);
|
|
349
|
+
return out;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const found = await this._searchExternal(text, { limit });
|
|
353
|
+
let listings = (Array.isArray(found.listings) ? found.listings : []).filter((item) => item && typeof item === "object");
|
|
354
|
+
if (pinned) listings = listings.filter((item) => item.candidate_id === pinned);
|
|
253
355
|
const priced = [];
|
|
254
356
|
listings.forEach((listing, position) => {
|
|
255
357
|
let price;
|
|
@@ -279,6 +381,7 @@ export class M2MConnectionClient {
|
|
|
279
381
|
return {
|
|
280
382
|
candidate_id: listing.candidate_id,
|
|
281
383
|
name: listing.name,
|
|
384
|
+
description: listing.description,
|
|
282
385
|
price_usdc_base_units: listing.price_usdc_base_units,
|
|
283
386
|
method: listing.method,
|
|
284
387
|
input_schema: schema,
|
|
@@ -291,32 +394,31 @@ export class M2MConnectionClient {
|
|
|
291
394
|
const refused = [];
|
|
292
395
|
for (const entry of usable) {
|
|
293
396
|
const { listing, built } = entry;
|
|
294
|
-
const
|
|
295
|
-
const key = createHash("sha256").update(`${callKey}:${
|
|
397
|
+
const cid = String(listing.candidate_id);
|
|
398
|
+
const key = createHash("sha256").update(`${callKey}:${cid}`).digest("hex");
|
|
296
399
|
const options = { idempotencyKey: key, dryRun };
|
|
297
400
|
if (listing.method) options.method = String(listing.method);
|
|
298
401
|
if (built.has_body) options.body = built.body;
|
|
299
402
|
if (built.has_query) options.query = built.query;
|
|
300
403
|
let result;
|
|
301
404
|
try {
|
|
302
|
-
result = await this.
|
|
405
|
+
result = await this._purchaseExternal(cid, options);
|
|
303
406
|
} catch (error) {
|
|
304
407
|
const code = error instanceof M2MConnectionError ? String((error.payload || {}).code || "") : "";
|
|
305
408
|
if (!PRE_CHARGE_REFUSALS.has(code)) {
|
|
306
|
-
if (error && typeof error === "object") error.attempts = [...attempts, { candidate_id:
|
|
409
|
+
if (error && typeof error === "object") error.attempts = [...attempts, { candidate_id: cid, outcome: code || "error" }];
|
|
307
410
|
throw error;
|
|
308
411
|
}
|
|
309
|
-
attempts.push({ candidate_id:
|
|
412
|
+
attempts.push({ candidate_id: cid, outcome: code });
|
|
310
413
|
refused.push(describe(entry, (error.payload || {}).fields || []));
|
|
311
414
|
continue;
|
|
312
415
|
}
|
|
313
|
-
const
|
|
314
|
-
const
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
if (
|
|
318
|
-
|
|
319
|
-
out.resume = { candidateId, options: resumeOptions };
|
|
416
|
+
const local = { ...this._lastTiming };
|
|
417
|
+
const out = finishExternal(result, cid, key, options, attempts);
|
|
418
|
+
mergeTiming(out, local);
|
|
419
|
+
if (!dryRun) this._sendTiming({ idempotency_key: key }, local);
|
|
420
|
+
if (dryRun) {
|
|
421
|
+
out.alternatives = ranked.filter((item) => item.listing.candidate_id !== cid).slice(0, 5).map((item) => describe(item));
|
|
320
422
|
}
|
|
321
423
|
return out;
|
|
322
424
|
}
|
|
@@ -399,6 +501,7 @@ export class M2MConnectionClient {
|
|
|
399
501
|
let excludedCandidates = [];
|
|
400
502
|
|
|
401
503
|
while (attemptNumber <= maximumAttempts) {
|
|
504
|
+
const submittedAt = performance.now();
|
|
402
505
|
const accepted = await this.submit({
|
|
403
506
|
category,
|
|
404
507
|
intent,
|
|
@@ -419,11 +522,20 @@ export class M2MConnectionClient {
|
|
|
419
522
|
if (Number.isInteger(serverAttempts) && serverAttempts >= 1) {
|
|
420
523
|
maximumAttempts = Math.min(maximumAttempts, serverAttempts);
|
|
421
524
|
}
|
|
422
|
-
const
|
|
525
|
+
const submitTiming = { ...this._lastTiming };
|
|
526
|
+
let terminal = ["settled", "released"].includes(
|
|
423
527
|
String(accepted.lifecycle_state || "").toLowerCase(),
|
|
424
528
|
)
|
|
425
529
|
? accepted
|
|
426
530
|
: await this.waitForQuery(accepted.query_id, { timeoutMs: queryTimeoutMs });
|
|
531
|
+
const local = {
|
|
532
|
+
...submitTiming,
|
|
533
|
+
submit_to_terminal_ms: ms(performance.now() - submittedAt),
|
|
534
|
+
poll_interval_ms: 1000,
|
|
535
|
+
};
|
|
536
|
+
terminal = { ...terminal };
|
|
537
|
+
mergeTiming(terminal, local);
|
|
538
|
+
if (terminal.query_id) this._sendTiming({ query_id: String(terminal.query_id) }, local);
|
|
427
539
|
|
|
428
540
|
attempts.push({
|
|
429
541
|
attempt_number: attemptNumber,
|
package/package.json
CHANGED
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.7.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
|