@telemai/sdk 0.6.0 → 0.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
@@ -48,7 +48,7 @@ const telem = new Telem({
48
48
  apiKey: "tlm_...",
49
49
  baseUrl: "https://router.telem.ai",
50
50
  timeoutMs: 60_000, // per attempt
51
- maxRetries: 2, // on 5xx, network errors and 429
51
+ maxRetries: 2, // on 429, network errors and 5xx (not 5xx on search or fetch)
52
52
  tier: "extended", // client-wide search defaults go here
53
53
  })
54
54
  ```
@@ -232,6 +232,23 @@ returns the agent itself: its status, query, frequency and plan version.
232
232
  `monitor.agentState` shows it on the monitor; when the agent did not start, the
233
233
  create's `monitor.agentNote` says why. Read `iterateChanges` with `for await`.
234
234
 
235
+ `createMany` takes an array of `create`'s options, each with its `query`, and returns
236
+ one result per monitor, in your order: its `status`, its `monitor` or its `error`, and its
237
+ `idempotencyKey`. It sends them in calls of 10, gives each its own key (or yours, as
238
+ `idempotencyKey`), and sends again only the monitors answered with a 429 or a 409
239
+ `idempotency_in_progress` (still being made). A call that fails whole, or an abort
240
+ (`code: "aborted"`) once a call was sent, throws with `results` (each monitor's last answer
241
+ so far) and `idempotencyKeys` (every key), and says the monitors may exist: send the
242
+ monitors without a final 201 or 200 again with the same keys.
243
+
244
+ ```ts
245
+ const results = await telem.monitors.createMany([
246
+ { query: "Nvidia files a new 8-K with the SEC", ttl: "30d" },
247
+ { query: "AMD files a new 8-K with the SEC", ttl: "30d", frequency: "1h" },
248
+ ])
249
+ for (const result of results) console.log(result.index, result.status, result.monitor?.id ?? result.error)
250
+ ```
251
+
235
252
  `telem.monitors` also has `get` and `list`. `poll` is deprecated and warns once:
236
253
  read the agent's changes with `iterateChanges` instead.
237
254
  See [Monitors](https://docs.telem.ai/resources/monitors/) for the fields, the errors and
@@ -378,8 +395,9 @@ try {
378
395
  // error.code === "timeout": one attempt took longer than timeoutMs
379
396
  } else if (error instanceof TelemError) {
380
397
  error.status // the HTTP status, or undefined when nothing was sent
381
- error.code // "invalid_request" | "unsupported_server_version" | "connection_error", or a server code
398
+ error.code // "invalid_request" | "unsupported_server_version" | "connection_error" | "invalid_response" | "aborted", or a server code
382
399
  error.details // the parsed response body, or the raw text
400
+ error.retryAfter // the response's Retry-After in seconds, when it sent a number
383
401
  }
384
402
  }
385
403
  ```
@@ -387,16 +405,29 @@ try {
387
405
  | Situation | Result |
388
406
  |---|---|
389
407
  | Bad input (empty query, empty URL list, a monitor with an agent and no `ttl`) | `TelemError`, `code: "invalid_request"`, nothing sent |
390
- | Network failure | `TelemError`, `code: "connection_error"`, after the retries |
391
- | 5xx or 429 | Retried with backoff (`Retry-After` applies), then `TelemError` with the status |
408
+ | Network failure | `TelemError`, `code: "connection_error"`, after the retries. A search or fetch is retried only when the request never left (in Node: connection refused, host not found) |
409
+ | 5xx | Retried with backoff (`Retry-After` applies), then `TelemError` with the status. A search or fetch is not retried |
410
+ | 429 | Retried with backoff (`Retry-After` applies), then `TelemError` with the status |
392
411
  | Other 4xx | `TelemError` with the status and the code from the server, not retried |
393
- | Attempt longer than `timeoutMs` | `TimeoutError`, not retried |
412
+ | Attempt longer than `timeoutMs` | `TimeoutError`, not retried, except by `monitors.create` and `monitors.createMany`, which send it again with the same keys |
413
+ | A change-stream position (`seq`, `next_cursor`, `watermark`) in a 2xx body that is not a whole number | `TelemError`, `code: "invalid_response"`, naming the field and the value; `details` is that value and `status` is unset |
414
+ | A `monitors.createMany` answer without one result per monitor sent, a result with no `index` or `status`, or two results with the same `index` | `TelemError`, `code: "invalid_response"`, with `results` and `idempotencyKeys` on the error. The monitors may exist |
415
+ | `monitors.createMany` aborted after it sent a call | `TelemError`, `code: "aborted"`, `cause` is the reason, with `results` and `idempotencyKeys` on the error |
394
416
 
395
417
  `monitors.create` sends an `Idempotency-Key` header, a new one per call unless you
396
418
  pass `idempotencyKey`. It retries a 429, a 409 `idempotency_in_progress`, a network
397
419
  failure and a timeout for up to about 2 minutes, with the same key. For 24 hours, a
398
420
  retry with the same key returns the first monitor instead of creating a second one.
399
- A different API key makes a new monitor. A 5xx is not retried.
421
+ A different API key makes a new monitor. A 5xx is not retried. A `maxRetries` you pass
422
+ caps these retries, and those of `monitors.createMany`. `monitors.createMany`
423
+ also retries a 502 or 504, with the same keys: a long call can outlast the edge.
424
+
425
+ Search and fetch are not retried on a `5xx`: a gateway error can follow a search or fetch
426
+ that was already billed, so a second send could bill it again. Send it again yourself only
427
+ when Telem's own body says nothing was charged: a `503` whose `error.details.detail` is a
428
+ string (for a fetch, `error.code` is `unavailable`) was refused with nothing charged, and an
429
+ error with an `interaction_id` (`error.details.detail.interaction_id` for a search,
430
+ `error.details.error.interaction_id` for a fetch) ran with every provider failed.
400
431
 
401
432
  See [Resources → Errors](https://docs.telem.ai/resources/errors/) for how the plugins show a failed call.
402
433
 
@@ -9,6 +9,7 @@ var TelemError = class extends Error {
9
9
  this.status = options.status;
10
10
  this.code = options.code;
11
11
  this.details = options.details;
12
+ if (options.retryAfter !== void 0) this.retryAfter = options.retryAfter;
12
13
  }
13
14
  };
14
15
  var TimeoutError = class extends TelemError {
@@ -32,6 +33,11 @@ function asObject(value) {
32
33
  function asArray(value) {
33
34
  return Array.isArray(value) ? value : [];
34
35
  }
36
+ var optString = (v) => typeof v === "string" ? v : null;
37
+ var optStrings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null;
38
+ var optInt = (v) => Number.isInteger(v) ? v : null;
39
+ var optBool = (v) => typeof v === "boolean" ? v : null;
40
+ var optObject = (v) => isObject(v) ? v : null;
35
41
  function invalidRequest(message) {
36
42
  return new TelemError(message, { code: "invalid_request" });
37
43
  }
@@ -82,12 +88,13 @@ function defaultMessage(status) {
82
88
  return `Unexpected status code ${status}`;
83
89
  }
84
90
  var BLOCKED_MESSAGE = "The request was blocked by a firewall before it reached Telem; the text may have characters that are not allowed.";
85
- function statusError(status, body) {
91
+ function statusError(status, body, retryAfter = null) {
86
92
  const fallback = status === 403 && !isObject(body) ? BLOCKED_MESSAGE : defaultMessage(status);
87
93
  return new TelemError(detailFromBody(body) ?? fallback, {
88
94
  status,
89
95
  code: codeFromBody(body),
90
- details: body
96
+ details: body,
97
+ retryAfter: retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter) ? Number(retryAfter) : void 0
91
98
  });
92
99
  }
93
100
  function connectionError(url, cause) {
@@ -101,6 +108,16 @@ function connectionError(url, cause) {
101
108
  function isRetryable(status) {
102
109
  return status >= 500 || status === 429;
103
110
  }
111
+ var NEVER_SENT = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN"]);
112
+ function neverSent(failure) {
113
+ const codes = (value) => {
114
+ if (typeof value !== "object" || value === null) return [];
115
+ const error = value;
116
+ return Array.isArray(error.errors) ? error.errors.flatMap(codes) : [error.code];
117
+ };
118
+ const found = codes(failure?.cause);
119
+ return found.length > 0 && found.every((code) => typeof code === "string" && NEVER_SENT.has(code));
120
+ }
104
121
  function shouldRetry(mode, status, body) {
105
122
  if (mode === "all") return isRetryable(status);
106
123
  if (status === 429) return true;
@@ -119,7 +136,10 @@ function jittered(ms) {
119
136
  return ms + Math.random() * Math.max(1e3, ms / 2);
120
137
  }
121
138
  function idempotentDelay(retryAfter, attempt) {
122
- if (retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter)) return jittered(Number(retryAfter) * 1e3);
139
+ return idempotentWait(retryAfter !== null && /^\s*\d+\s*$/.test(retryAfter) ? Number(retryAfter) : null, attempt);
140
+ }
141
+ function idempotentWait(seconds, attempt) {
142
+ if (seconds !== null) return jittered(seconds * 1e3);
123
143
  return Math.min(jittered(BASE_DELAY_MS * 2 ** attempt), MAX_IDEMPOTENT_BACKOFF_MS);
124
144
  }
125
145
  async function request(config, method, path, body, abort, retry = "all", extra = {}) {
@@ -196,21 +216,23 @@ async function request(config, method, path, body, abort, retry = "all", extra =
196
216
  }
197
217
  throw new TimeoutError(`request to ${url} timed out after ${config.timeoutMs}ms`, cause);
198
218
  }
199
- if (retry === "rate_limit" || attempt >= maxRetries || !fits(wait)) throw connectionError(url, cause);
219
+ if (retry === "rate_limit" || retry === "metered" && !neverSent(cause)) throw connectionError(url, cause);
220
+ if (attempt >= maxRetries || !fits(wait)) throw connectionError(url, cause);
200
221
  await pause(wait);
201
222
  continue;
202
223
  } finally {
203
224
  signal?.removeEventListener("abort", onAbort2);
204
225
  }
205
226
  if (received.status >= 200 && received.status < 300) return received.body;
206
- if (shouldRetry(retry, received.status, received.body) && attempt < maxRetries) {
227
+ const lostReply = retry === "idempotent" && extra.lostReplyStatuses?.includes(received.status) === true;
228
+ if ((lostReply || shouldRetry(retry, received.status, received.body)) && attempt < maxRetries) {
207
229
  const wait = delay(received.retryAfter, attempt);
208
230
  if (fits(wait)) {
209
231
  await pause(wait);
210
232
  continue;
211
233
  }
212
234
  }
213
- throw statusError(received.status, received.body);
235
+ throw statusError(received.status, received.body, received.retryAfter);
214
236
  }
215
237
  }
216
238
  }
@@ -379,8 +401,14 @@ export {
379
401
  isObject,
380
402
  asObject,
381
403
  asArray,
404
+ optString,
405
+ optStrings,
406
+ optInt,
407
+ optBool,
408
+ optObject,
382
409
  invalidRequest,
383
410
  stringList,
411
+ idempotentWait,
384
412
  request,
385
413
  RESERVED_METADATA,
386
414
  sha256,