m2m-market 2.6.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -151,6 +151,19 @@ With `candidateId` and a `null` need, the request is sent as given:
151
151
  - Each attempt uses its own key derived from your `idempotencyKey` and the listing, so repeating a call never pays twice.
152
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
153
 
154
+ ### Status and payment
155
+ A purchase result also carries two standard fields, lifted to the top level from `purchase`
156
+ when a purchase happened (they are absent for `planned`, `needs_input`, `no_match` and
157
+ `over_price_cap`). `status` and `purchase` keep their existing values.
158
+
159
+ | Field | Values |
160
+ |---|---|
161
+ | `standard_status` | `Pending`, `Completed`, `Failed` |
162
+ | `standard_payment` | `Pending`, `Charged`, `Refunded` |
163
+
164
+ External purchases also carry the fee, when M2M has recorded it: `protocol_fee_m2m`,
165
+ `protocol_fee_bps`, `seller_m2m` and `fee_state` (`held`, `charged` or `returned`).
166
+
154
167
  ### Pending and rejected purchases
155
168
  If `status` is `pending`, collect the result with the request in `resume`. The same
156
169
  key is never paid twice:
@@ -165,6 +178,21 @@ the payment did settle, marked `reconciled_settled` and the charge stands.
165
178
 
166
179
  `searchExternal` and `purchaseExternal` are deprecated. They still work and warn.
167
180
 
181
+ ## Timing
182
+ Each purchase result has `timing` (milliseconds), so you can see where time went:
183
+
184
+ | Field | Meaning |
185
+ |---|---|
186
+ | `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`. |
187
+ | `timing.m2m.request_ms`, `response_ms`, `total_ms` | M2M latency: M2M's time before calling the provider, after the provider answered, and both together. |
188
+ | `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). |
189
+
190
+ After a purchase the SDK reports its own figures to M2M without awaiting, so your
191
+ dashboard can also show your network round trip to M2M. The report never delays or
192
+ changes a purchase. It is on by default with the global `fetch`; turn it off with
193
+ `new M2MConnectionClient({ ..., reportTiming: false })`. With your own `fetchImpl`
194
+ it is off unless you pass `reportTiming: true`. A dry run is not reported.
195
+
168
196
  ## OpenAI-compatible tool
169
197
 
170
198
  ```bash
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 {
@@ -78,6 +80,14 @@ export interface BuyExternalResult extends JsonObject {
78
80
  candidate_id?: string;
79
81
  idempotency_key?: string;
80
82
  attempts?: Array<{ candidate_id: string; outcome: string }>;
83
+ /** Lifted from purchase when a purchase happened. Absent for planned, needs_input, no_match and over_price_cap. */
84
+ standard_status?: 'Pending' | 'Completed' | 'Failed';
85
+ standard_payment?: 'Pending' | 'Charged' | 'Refunded';
86
+ /** Fee fields of an external purchase, when recorded. Amounts are M2M units as strings. */
87
+ protocol_fee_m2m?: string;
88
+ protocol_fee_bps?: number;
89
+ seller_m2m?: string;
90
+ fee_state?: 'held' | 'charged' | 'returned';
81
91
  candidates?: BuyExternalCandidate[];
82
92
  /** Dry run only: other listings with price and any missing fields. */
83
93
  alternatives?: BuyExternalCandidate[];
@@ -148,3 +158,21 @@ export * from "./procurement.js";
148
158
  export * from "./protocols.js";
149
159
  export * from "./procurement-adapters.js";
150
160
  export * from "./commercial.js";
161
+
162
+ /** Timing of one purchase: M2M latency, the provider leg and this Agent's own figures (ms). */
163
+ export interface TransactionTiming {
164
+ v: 1;
165
+ m2m: { request_ms: number | null; response_ms: number | null; total_ms: number | null } | null;
166
+ provider: {
167
+ status: number | null; dns_ms: number | null; connect_ms: number | null; tls_ms: number | null;
168
+ sent_ms: number | null; ttfb_ms: number | null; ttlb_ms: number | null; rtt_ms: number | null;
169
+ processing_ms_est: number | null; error: string | null;
170
+ } | null;
171
+ agent?: {
172
+ call_total_ms?: number; call_ttfb_ms?: number; call_ttlb_ms?: number;
173
+ submit_to_terminal_ms?: number; poll_interval_ms?: number;
174
+ rtt_ms?: number | null; waiting_for_result_ms?: number | null;
175
+ } | null;
176
+ }
177
+
178
+ export const SDK_VERSION: string;
package/index.js CHANGED
@@ -33,12 +33,18 @@ function deprecated(name, replacement) {
33
33
  process.emitWarning(`${name} is deprecated; use ${replacement}`, "DeprecationWarning");
34
34
  }
35
35
 
36
+ // Standard status, payment and fee fields the server puts on `purchase`. Copied to the top level
37
+ // when present (additive: `purchase` and `status` keep their values).
38
+ const LIFTED_PURCHASE_FIELDS = ["standard_status", "standard_payment", "protocol_fee_m2m", "protocol_fee_bps", "seller_m2m", "fee_state"];
36
39
  // Shape a purchase reply: status, candidate, attempts and, when pending, a resume request.
37
40
  function finishExternal(result, candidateId, key, options, attempts) {
38
41
  const purchase = result.purchase && typeof result.purchase === "object" ? result.purchase : {};
39
42
  const status = String(purchase.status || result.status || "");
40
43
  attempts.push({ candidate_id: candidateId, outcome: status });
41
44
  const out = { ...result, status, candidate_id: candidateId, attempts };
45
+ for (const field of LIFTED_PURCHASE_FIELDS) {
46
+ if (Object.prototype.hasOwnProperty.call(purchase, field)) out[field] = purchase[field];
47
+ }
42
48
  if (status === "pending") {
43
49
  const values = {};
44
50
  if (Object.prototype.hasOwnProperty.call(options, "body")) values.body = options.body;
@@ -48,17 +54,33 @@ function finishExternal(result, candidateId, key, options, attempts) {
48
54
  return out;
49
55
  }
50
56
 
57
+ export const SDK_VERSION = "2.8.0";
58
+
59
+ const ms = (value) => Math.max(0, Math.round(value));
60
+
61
+ /** result.timing: M2M's view from the response plus this SDK's own figures. */
62
+ function mergeTiming(result, local) {
63
+ if (!local || Object.keys(local).length === 0) return;
64
+ const server = result.timing && typeof result.timing === "object" ? result.timing : {};
65
+ result.timing = { ...server, agent: { ...(server.agent || {}), ...local } };
66
+ }
67
+
51
68
  export class M2MConnectionClient {
52
69
  constructor({
53
70
  connectionToken,
54
71
  baseUrl = DEFAULT_API_BASE_URL,
55
72
  timeoutMs = 30000,
56
- fetchImpl = globalThis.fetch,
73
+ fetchImpl,
74
+ reportTiming,
57
75
  } = {}) {
58
76
  this.baseUrl = String(baseUrl || DEFAULT_API_BASE_URL).replace(/\/$/, "");
59
77
  this.connectionToken = String(connectionToken || "").trim();
60
78
  this.timeoutMs = Math.max(Number(timeoutMs || 30000), 1000);
61
- this.fetchImpl = fetchImpl;
79
+ this.fetchImpl = fetchImpl ?? globalThis.fetch;
80
+ // Send this SDK's own timing to M2M after a purchase (best effort, never awaited).
81
+ // On by default with the global fetch; off with a custom fetchImpl unless asked for.
82
+ this.reportTiming = reportTiming === undefined ? fetchImpl === undefined : Boolean(reportTiming);
83
+ this._lastTiming = {};
62
84
  if (!this.baseUrl.startsWith("https://")) {
63
85
  throw new TypeError("M2M connection base URL must use HTTPS");
64
86
  }
@@ -81,6 +103,7 @@ export class M2MConnectionClient {
81
103
  async request(method, path, body) {
82
104
  const controller = new AbortController();
83
105
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
106
+ const started = performance.now();
84
107
  try {
85
108
  const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
86
109
  method,
@@ -93,7 +116,14 @@ export class M2MConnectionClient {
93
116
  body: body === undefined ? undefined : JSON.stringify(body),
94
117
  signal: controller.signal,
95
118
  });
119
+ const headersAt = performance.now();
96
120
  const payload = await response.json().catch(() => ({ error: "Invalid API response" }));
121
+ const done = performance.now();
122
+ this._lastTiming = {
123
+ call_total_ms: ms(done - started),
124
+ call_ttfb_ms: ms(headersAt - started),
125
+ call_ttlb_ms: ms(done - started),
126
+ };
97
127
  if (!response.ok) {
98
128
  const ErrorClass = payload && payload.code === "no_matching_service"
99
129
  ? M2MNoMatchingServiceError
@@ -115,6 +145,28 @@ export class M2MConnectionClient {
115
145
  }
116
146
  }
117
147
 
148
+ /** Report this SDK's timing for one transaction. Fire-and-forget; never throws or delays. */
149
+ _sendTiming(target, agent) {
150
+ if (!this.reportTiming || !agent || agent.call_total_ms === undefined) return;
151
+ const controller = new AbortController();
152
+ const timer = setTimeout(() => controller.abort(), 2000);
153
+ if (typeof timer.unref === "function") timer.unref();
154
+ Promise.resolve()
155
+ .then(() => this.fetchImpl(`${this.baseUrl}/connect/timing`, {
156
+ method: "POST",
157
+ headers: {
158
+ Accept: "application/json",
159
+ "Content-Type": "application/json",
160
+ Authorization: `Bearer ${this.connectionToken}`,
161
+ "X-Request-Id": randomUUID(),
162
+ },
163
+ body: JSON.stringify({ ...target, agent: { ...agent, sdk: `node ${SDK_VERSION}` } }),
164
+ signal: controller.signal,
165
+ }))
166
+ .catch(() => {})
167
+ .finally(() => clearTimeout(timer));
168
+ }
169
+
118
170
  testConnection() {
119
171
  return this.request("POST", "/connect/test", {});
120
172
  }
@@ -296,7 +348,11 @@ export class M2MConnectionClient {
296
348
  if (Object.prototype.hasOwnProperty.call(values, "body")) options.body = values.body;
297
349
  if (values.query && typeof values.query === "object" && !Array.isArray(values.query)) options.query = values.query;
298
350
  const result = await this._purchaseExternal(pinned, options);
299
- return finishExternal(result, pinned, callKey, options, []);
351
+ const local = { ...this._lastTiming };
352
+ const out = finishExternal(result, pinned, callKey, options, []);
353
+ mergeTiming(out, local);
354
+ if (!dryRun) this._sendTiming({ idempotency_key: callKey }, local);
355
+ return out;
300
356
  }
301
357
 
302
358
  const found = await this._searchExternal(text, { limit });
@@ -363,7 +419,10 @@ export class M2MConnectionClient {
363
419
  refused.push(describe(entry, (error.payload || {}).fields || []));
364
420
  continue;
365
421
  }
422
+ const local = { ...this._lastTiming };
366
423
  const out = finishExternal(result, cid, key, options, attempts);
424
+ mergeTiming(out, local);
425
+ if (!dryRun) this._sendTiming({ idempotency_key: key }, local);
367
426
  if (dryRun) {
368
427
  out.alternatives = ranked.filter((item) => item.listing.candidate_id !== cid).slice(0, 5).map((item) => describe(item));
369
428
  }
@@ -448,6 +507,7 @@ export class M2MConnectionClient {
448
507
  let excludedCandidates = [];
449
508
 
450
509
  while (attemptNumber <= maximumAttempts) {
510
+ const submittedAt = performance.now();
451
511
  const accepted = await this.submit({
452
512
  category,
453
513
  intent,
@@ -468,11 +528,20 @@ export class M2MConnectionClient {
468
528
  if (Number.isInteger(serverAttempts) && serverAttempts >= 1) {
469
529
  maximumAttempts = Math.min(maximumAttempts, serverAttempts);
470
530
  }
471
- const terminal = ["settled", "released"].includes(
531
+ const submitTiming = { ...this._lastTiming };
532
+ let terminal = ["settled", "released"].includes(
472
533
  String(accepted.lifecycle_state || "").toLowerCase(),
473
534
  )
474
535
  ? accepted
475
536
  : await this.waitForQuery(accepted.query_id, { timeoutMs: queryTimeoutMs });
537
+ const local = {
538
+ ...submitTiming,
539
+ submit_to_terminal_ms: ms(performance.now() - submittedAt),
540
+ poll_interval_ms: 1000,
541
+ };
542
+ terminal = { ...terminal };
543
+ mergeTiming(terminal, local);
544
+ if (terminal.query_id) this._sendTiming({ query_id: String(terminal.query_id) }, local);
476
545
 
477
546
  attempts.push({
478
547
  attempt_number: attemptNumber,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "m2m-market",
3
- "version": "2.6.0",
3
+ "version": "2.8.0",
4
4
  "description": "Customer SDK for connecting AI Agents to M2M Market",
5
5
  "author": "M2M Market, Inc.",
6
6
  "type": "module",
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.6.0' });
35
+ const client = new sdk.Client({ name: 'm2m-market', version: '2.8.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