@telemai/sdk 0.7.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/dist/index.d.ts CHANGED
@@ -323,6 +323,30 @@ type MonitorCreateOptions = MonitorCreateCommonOptions & ({
323
323
  });
324
324
  /** The `preset` of `monitors.create`. */
325
325
  type MonitorPreset = "article" | "person" | "company" | "listing";
326
+ /** One monitor of `monitors.createMany`: its `query` and the options of `create`.
327
+ * `idempotencyKey` is this monitor's own key; the call takes the `signal`. */
328
+ type MonitorCreateManyItem = {
329
+ query: string;
330
+ } & WithoutSignal<MonitorCreateOptions>;
331
+ /** `Omit` for each member of a union, so the `agent`/`ttl` pairing holds. */
332
+ type WithoutSignal<T> = T extends unknown ? Omit<T, "signal"> : never;
333
+ /** One monitor's answer in `monitors.createMany`. */
334
+ type MonitorBatchResult = {
335
+ /** The monitor's position in the array you passed. */
336
+ index: number;
337
+ /** `201`: made. `200` with `replayed`: made before, under the same key. Any other
338
+ * status is this monitor's own error. */
339
+ status: number;
340
+ monitor: Monitor | null;
341
+ replayed: boolean;
342
+ /** `{ code, message }`, and `param` when a field is at fault. */
343
+ error: Json | null;
344
+ /** With a `429`: the seconds to wait before you send this monitor again. */
345
+ retryAfter: number | null;
346
+ /** The key this monitor was sent with: send it again with the same key. */
347
+ idempotencyKey: string;
348
+ raw: Json;
349
+ };
326
350
  /** Options for `monitors.update`. Send at least one field. */
327
351
  type MonitorUpdateOptions = {
328
352
  /** `"paused"` or `"active"`. */
@@ -732,6 +756,18 @@ type MonitorsResource = {
732
756
  * `ttl` is required: a create without it throws a `TelemError` (`invalid_request`)
733
757
  * before anything is sent. */
734
758
  create(query: string, options: MonitorCreateOptions): Promise<Monitor>;
759
+ /** Create many monitors, ten per call, one call after another. One result per monitor,
760
+ * in the order given; a monitor that fails does not stop the others. Each call retries
761
+ * as `create` does, and after a 502 or 504 too, then only the monitors answered with a 429 (or a 409
762
+ * `idempotency_in_progress`) are sent again, with their keys, for up to about 120 s per
763
+ * call. A bad monitor, an unknown option, a monitor that is not JSON or a key given
764
+ * twice throws a `TelemError` (`invalid_request`) naming the index, before anything is
765
+ * sent. Once a call was sent, any failure (a call refused whole, an abort as `aborted`)
766
+ * throws with `results` (each monitor's last answer so far) and `idempotencyKeys` (every
767
+ * monitor's key) on the error, and its message says the monitors may exist. */
768
+ createMany(items: MonitorCreateManyItem[], options?: {
769
+ signal?: AbortSignal;
770
+ }): Promise<MonitorBatchResult[]>;
735
771
  list(options?: MonitorListOptions): Promise<Monitor[]>;
736
772
  listPage(options?: MonitorListOptions): Promise<MonitorPage>;
737
773
  get(monitorId: string, options?: {
@@ -803,7 +839,12 @@ type TelemClientErrorCode =
803
839
  /** The request never produced a response (DNS, refused, reset, TLS). */
804
840
  | "connection_error"
805
841
  /** The request was still outstanding when the timeout fired. */
806
- | "timeout";
842
+ | "timeout"
843
+ /** A 2xx body carried a value the client cannot use safely, such as a change-stream
844
+ * position (`seq`, `watermark`, `next_cursor`) that is not a whole number. */
845
+ | "invalid_response"
846
+ /** `monitors.createMany` was aborted after it sent a call: `cause` is the reason. */
847
+ | "aborted";
807
848
  type TelemErrorOptions = {
808
849
  /** HTTP status that produced this error; absent for transport failures. */
809
850
  status?: number;
@@ -813,11 +854,20 @@ type TelemErrorOptions = {
813
854
  /** Parsed response body (or raw text when it would not parse). */
814
855
  details?: unknown;
815
856
  cause?: unknown;
857
+ /** The response's `Retry-After`, in seconds, when it sent one as a number. */
858
+ retryAfter?: number;
816
859
  };
817
860
  declare class TelemError extends Error {
818
861
  status?: number;
819
862
  code?: TelemClientErrorCode | (string & {});
820
863
  details?: unknown;
864
+ /** The response's `Retry-After`, in seconds, when it sent one as a number. */
865
+ retryAfter?: number;
866
+ /** From `monitors.createMany`: each monitor's last answer before it failed, in order.
867
+ * Not enumerable, so serialising the error does not write a `webhookSecret`. */
868
+ results?: MonitorBatchResult[];
869
+ /** From `monitors.createMany`: every monitor's key, in order. Not enumerable. */
870
+ idempotencyKeys?: string[];
821
871
  constructor(message: string, options?: TelemErrorOptions);
822
872
  }
823
873
  /** The request never produced a response in time. Always `code: "timeout"`. */
@@ -967,4 +1017,4 @@ declare class Telem {
967
1017
  providers(): Promise<ProviderInfo[]>;
968
1018
  }
969
1019
 
970
- export { type AgentCompileState, type AgentDocument, type AgentState, type ApplyResult, type ChangeRecord, type ChangeSubject, type ChangesPage, type CompanyList, type CompanyListRow, type CompanySheet, type DataMap, type ExpansionConfirmFields, type ExpansionRecord, type ExpansionsPage, type FeedbackResult, type FetchOptions, type FetchResponse, type FetchResult, type Json, type Monitor, type MonitorChangesAcrossOptions, type MonitorChangesAcrossScope, type MonitorChangesOptions, type MonitorCompaniesOptions, type MonitorCreateOptions, type MonitorExpansionsOptions, type MonitorFeedbackOptions, type MonitorInputs, type MonitorIterateChangesOptions, type MonitorListOptions, type MonitorPage, type MonitorPollOptions, type MonitorPreset, type MonitorUpdateOptions, type MonitorsChangesPage, type MonitorsResource, type OnboardingCandidate, type OnboardingCompany, type OnboardingExample, type OnboardingMarks, type OnboardingSheet, type ProviderInfo, type ProviderRun, RESERVED_METADATA, type SearchDefaults, type SearchOptions, type SearchResponse, type SearchResult, type SessionResults, type SessionSummary, type SessionsResource, type SnapshotArgs, Telem, type TelemClientErrorCode, TelemError, type TelemErrorOptions, type TelemOptions, TimeoutError, type TrajectoryArgs, type TrajectoryEnvelope, type TrajectorySnapshot, buildMetadata, buildSnapshot, contentAnchor, Telem as default, eventNodeKey, fingerprint, sessionKey, snapshotNodeKey, toolMarker, verifyWebhook, windowAnchor, withTrajectory };
1020
+ export { type AgentCompileState, type AgentDocument, type AgentState, type ApplyResult, type ChangeRecord, type ChangeSubject, type ChangesPage, type CompanyList, type CompanyListRow, type CompanySheet, type DataMap, type ExpansionConfirmFields, type ExpansionRecord, type ExpansionsPage, type FeedbackResult, type FetchOptions, type FetchResponse, type FetchResult, type Json, type Monitor, type MonitorBatchResult, type MonitorChangesAcrossOptions, type MonitorChangesAcrossScope, type MonitorChangesOptions, type MonitorCompaniesOptions, type MonitorCreateManyItem, type MonitorCreateOptions, type MonitorExpansionsOptions, type MonitorFeedbackOptions, type MonitorInputs, type MonitorIterateChangesOptions, type MonitorListOptions, type MonitorPage, type MonitorPollOptions, type MonitorPreset, type MonitorUpdateOptions, type MonitorsChangesPage, type MonitorsResource, type OnboardingCandidate, type OnboardingCompany, type OnboardingExample, type OnboardingMarks, type OnboardingSheet, type ProviderInfo, type ProviderRun, RESERVED_METADATA, type SearchDefaults, type SearchOptions, type SearchResponse, type SearchResult, type SessionResults, type SessionSummary, type SessionsResource, type SnapshotArgs, Telem, type TelemClientErrorCode, TelemError, type TelemErrorOptions, type TelemOptions, TimeoutError, type TrajectoryArgs, type TrajectoryEnvelope, type TrajectorySnapshot, buildMetadata, buildSnapshot, contentAnchor, Telem as default, eventNodeKey, fingerprint, sessionKey, snapshotNodeKey, toolMarker, verifyWebhook, windowAnchor, withTrajectory };
package/dist/index.js CHANGED
@@ -9,8 +9,14 @@ import {
9
9
  contentAnchor,
10
10
  eventNodeKey,
11
11
  fingerprint,
12
+ idempotentWait,
12
13
  invalidRequest,
13
14
  isObject,
15
+ optBool,
16
+ optInt,
17
+ optObject,
18
+ optString,
19
+ optStrings,
14
20
  request,
15
21
  sessionKey,
16
22
  snapshotNodeKey,
@@ -19,10 +25,10 @@ import {
19
25
  windowAnchor,
20
26
  wireMetadata,
21
27
  withTrajectory
22
- } from "./chunk-TST6J3VA.js";
28
+ } from "./chunk-274HRD4N.js";
23
29
 
24
30
  // src/version.ts
25
- var VERSION = "0.7.0";
31
+ var VERSION = "0.8.0";
26
32
 
27
33
  // src/config.ts
28
34
  var DEFAULT_BASE_URL = "https://router.telem.ai";
@@ -169,23 +175,24 @@ function fetchBody(url, options, defaults) {
169
175
  function fetchResult(run) {
170
176
  const row = asObject(asArray(asObject(run.output_payload).fetched_results)[0]);
171
177
  return {
172
- url: row.url || run.query || "",
173
- canonicalUrl: row.canonical_url ?? null,
174
- title: row.title || "",
175
- status: row.status || run.status || "",
176
- content: row.content ?? null,
177
- contentTruncated: row.content_truncated ?? null,
178
- contentFormat: row.content_format ?? null,
179
- contentSha256: row.content_sha256 ?? null,
180
- contentType: row.content_type ?? null,
181
- contentRef: row.content_ref ?? null,
182
- provider: row.provider || "",
183
- httpStatus: row.http_status ?? null,
184
- fetchedAt: row.fetched_at ?? null,
185
- // Key presence, not truthiness: a row that really reported 0 ms keeps its 0.
186
- latencyMs: ("latency_ms" in row ? row.latency_ms : run.latency_ms) ?? null,
187
- providerMetadata: row.provider_metadata ?? null,
188
- error: row.error || run.error || null,
178
+ url: optString(row.url) || optString(run.query) || "",
179
+ canonicalUrl: optString(row.canonical_url),
180
+ title: optString(row.title) || "",
181
+ status: optString(row.status) || optString(run.status) || "",
182
+ content: optString(row.content),
183
+ contentTruncated: optBool(row.content_truncated),
184
+ contentFormat: optString(row.content_format),
185
+ contentSha256: optString(row.content_sha256),
186
+ contentType: optString(row.content_type),
187
+ contentRef: optObject(row.content_ref),
188
+ provider: optString(row.provider) || "",
189
+ httpStatus: optInt(row.http_status),
190
+ fetchedAt: optString(row.fetched_at),
191
+ // Key presence, not truthiness: a row that really reported 0 ms keeps its 0. A
192
+ // malformed row value falls back to the run's, as a missing one does.
193
+ latencyMs: optInt(row.latency_ms) ?? optInt(run.latency_ms),
194
+ providerMetadata: optObject(row.provider_metadata),
195
+ error: optObject(row.error) || optObject(run.error) || null,
189
196
  batchIndex: run.batch_index ?? 0,
190
197
  raw: row
191
198
  };
@@ -203,7 +210,7 @@ function buildFetchResponse(interaction) {
203
210
  }
204
211
  async function fetchUrls(config, url, options) {
205
212
  const body = fetchBody(url, options, config.fetchDefaults);
206
- return buildFetchResponse(await request(config, "POST", "/v1/fetch", body, options.signal));
213
+ return buildFetchResponse(await request(config, "POST", "/v1/fetch", body, options.signal, "metered"));
207
214
  }
208
215
 
209
216
  // src/methods/search.ts
@@ -305,21 +312,21 @@ function assertV2(data) {
305
312
  }
306
313
  function searchResults(envelope, provider) {
307
314
  return asArray(envelope.results).filter(isObject).map((row) => ({
308
- url: row.url || "",
309
- title: row.title || "",
310
- summary: row.summary ?? null,
311
- excerpt: row.excerpt ?? null,
312
- fullContent: row.full_content ?? null,
313
- publishDate: row.publish_date ?? null,
314
- rank: row.rank ?? null,
315
- thumbnail: row.thumbnail ?? null,
316
- favicon: row.favicon ?? null,
317
- source: row.source ?? null,
318
- enrichments: row.enrichments ?? null,
319
- fetchMeta: row.fetch_meta ?? null,
320
- imageUrl: row.image_url ?? null,
321
- imageWidth: row.image_width ?? null,
322
- imageHeight: row.image_height ?? null,
315
+ url: optString(row.url) || "",
316
+ title: optString(row.title) || "",
317
+ summary: optString(row.summary),
318
+ excerpt: optStrings(row.excerpt),
319
+ fullContent: optObject(row.full_content),
320
+ publishDate: optString(row.publish_date),
321
+ rank: optInt(row.rank),
322
+ thumbnail: optString(row.thumbnail),
323
+ favicon: optString(row.favicon),
324
+ source: optObject(row.source),
325
+ enrichments: optObject(row.enrichments),
326
+ fetchMeta: optObject(row.fetch_meta),
327
+ imageUrl: optString(row.image_url),
328
+ imageWidth: optInt(row.image_width),
329
+ imageHeight: optInt(row.image_height),
323
330
  provider,
324
331
  raw: row
325
332
  }));
@@ -366,7 +373,7 @@ function buildSearchResponse(interaction) {
366
373
  }
367
374
  async function search(config, query, options) {
368
375
  const body = searchBody(config, query, options);
369
- const data = await request(config, "POST", "/v1/interactions", body, options.signal);
376
+ const data = await request(config, "POST", "/v1/interactions", body, options.signal, "metered");
370
377
  assertV2(data);
371
378
  return buildSearchResponse(data);
372
379
  }
@@ -389,7 +396,7 @@ function agentStateFrom(data) {
389
396
  needsAttention: data.needs_attention === true,
390
397
  planVersion: typeof data.plan_version === "number" ? data.plan_version : null,
391
398
  nextRunAt: typeof data.next_run_at === "string" ? data.next_run_at : null,
392
- watermark: Number(data.watermark ?? 0),
399
+ watermark: finite(data.watermark),
393
400
  // No compile job yet is null, not an object of empty strings.
394
401
  compile: isObject(data.compile) ? {
395
402
  jobId: String(data.compile.job_id ?? ""),
@@ -431,10 +438,17 @@ function agentDocumentFrom(body) {
431
438
  if (typeof data.spend_usd === "number") document.spendUsd = data.spend_usd;
432
439
  return document;
433
440
  }
441
+ function position(value, field) {
442
+ const n = typeof value === "number" ? value : typeof value === "string" && /^\d+$/.test(value) ? Number(value) : NaN;
443
+ if (Number.isSafeInteger(n) && n >= 0) return n;
444
+ const sent = value === void 0 ? "missing" : JSON.stringify(value) ?? String(value);
445
+ const shown = sent.length > 40 ? `${sent.slice(0, 40)}\u2026` : sent;
446
+ throw new TelemError(`${field} is not a stream position: ${shown}`, { code: "invalid_response", details: value });
447
+ }
434
448
  function changeRecordFrom(entry) {
435
449
  const subject = asObject(entry.subject);
436
450
  return {
437
- seq: Number(entry.seq ?? 0),
451
+ seq: position(entry.seq, "change seq"),
438
452
  type: String(entry.type ?? ""),
439
453
  kind: String(entry.kind ?? ""),
440
454
  monitorId: String(entry.monitor_id ?? ""),
@@ -454,8 +468,8 @@ function changesPageFrom(body) {
454
468
  const data = asObject(body);
455
469
  return {
456
470
  changes: asArray(data.changes).filter(isObject).map(changeRecordFrom),
457
- nextCursor: Number(data.next_cursor ?? 0),
458
- watermark: Number(data.watermark ?? 0)
471
+ nextCursor: position(data.next_cursor, "changes page next_cursor"),
472
+ watermark: position(data.watermark, "changes page watermark")
459
473
  };
460
474
  }
461
475
  function monitorsChangesPageFrom(body) {
@@ -563,6 +577,10 @@ function dataMapFrom(body) {
563
577
  raw: data
564
578
  };
565
579
  }
580
+ function finite(value) {
581
+ const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
582
+ return Number.isFinite(n) ? n : 0;
583
+ }
566
584
  function companyFrom(entry) {
567
585
  return {
568
586
  companyId: String(entry.company_id ?? ""),
@@ -575,17 +593,17 @@ function companyFrom(entry) {
575
593
  newsroomUrl: String(entry.newsroom_url ?? ""),
576
594
  teamPage: String(entry.team_page ?? ""),
577
595
  tier: String(entry.tier ?? ""),
578
- rank: Number(entry.rank ?? 0),
596
+ rank: finite(entry.rank),
579
597
  raw: entry
580
598
  };
581
599
  }
582
600
  function companyListFrom(body) {
583
601
  const data = asObject(body);
584
602
  return {
585
- total: Number(data.total ?? 0),
586
- priorityCount: Number(data.priority_count ?? 0),
587
- offset: Number(data.offset ?? 0),
588
- limit: Number(data.limit ?? 0),
603
+ total: finite(data.total),
604
+ priorityCount: finite(data.priority_count),
605
+ offset: finite(data.offset),
606
+ limit: finite(data.limit),
589
607
  nextOffset: typeof data.next_offset === "number" ? data.next_offset : null,
590
608
  companies: asArray(data.companies).filter(isObject).map(companyFrom),
591
609
  raw: data
@@ -636,6 +654,140 @@ function acrossQuery(scope, options) {
636
654
  if (options.cursor !== void 0) params.set("cursor", options.cursor);
637
655
  return readQuery(params, options);
638
656
  }
657
+ function createBody(config, query, options) {
658
+ const given = options ?? {};
659
+ const agent = given.agent == null ? true : Boolean(given.agent);
660
+ if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
661
+ const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
662
+ if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
663
+ throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
664
+ }
665
+ const monitorOptions = {};
666
+ if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
667
+ if (given.includeDomains !== void 0) {
668
+ monitorOptions.include_domains = given.includeDomains;
669
+ }
670
+ if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
671
+ const body = { query, options: monitorOptions };
672
+ if (given.metadata !== void 0) body.metadata = given.metadata;
673
+ if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
674
+ if (given.ttl !== void 0) body.ttl = given.ttl;
675
+ if (given.inputs != null) {
676
+ body.inputs = given.inputs;
677
+ const vertical = config.defaults.vertical;
678
+ if (vertical !== void 0 && !("vertical" in given.inputs)) {
679
+ body.inputs = { ...given.inputs, vertical };
680
+ }
681
+ }
682
+ body.agent = agent;
683
+ if (given.preset != null) body.preset = given.preset;
684
+ if (given.tags != null) body.tags = given.tags;
685
+ return { body, key };
686
+ }
687
+ var MAY_EXIST = "The monitor may exist: list monitors before you create it again.";
688
+ var MAY_EXIST_MANY = "The monitors may exist: list monitors before you create them again.";
689
+ function mayExist(note) {
690
+ return (error) => {
691
+ if (error instanceof TimeoutError) throw new TimeoutError(`${error.message}. ${note}`, error.cause);
692
+ throw error;
693
+ };
694
+ }
695
+ var BATCH_SIZE = 10;
696
+ var GATEWAY_TIMEOUTS = [502, 504];
697
+ var ITEM_FIELDS = /* @__PURE__ */ new Set([
698
+ "query",
699
+ "frequency",
700
+ "search",
701
+ "includeDomains",
702
+ "metadata",
703
+ "webhookUrl",
704
+ "tags",
705
+ "idempotencyKey",
706
+ "ttl",
707
+ "agent",
708
+ "inputs",
709
+ "preset"
710
+ ]);
711
+ function invalidBatch(message) {
712
+ return new TelemError(message, { code: "invalid_response" });
713
+ }
714
+ function batchAnswer(data, sent, keys) {
715
+ const answer = /* @__PURE__ */ new Map();
716
+ const results = isObject(data) ? data.results : void 0;
717
+ const count = `the batch answer does not have one result for each of the ${sent.length} monitors sent`;
718
+ if (!Array.isArray(results)) return { answer, problem: invalidBatch(count) };
719
+ let problem = results.length !== sent.length ? invalidBatch(count) : null;
720
+ for (const entry of results) {
721
+ try {
722
+ const [position2, result] = batchEntry(entry, sent, keys, answer);
723
+ answer.set(position2, result);
724
+ } catch (error) {
725
+ if (!(error instanceof TelemError)) throw error;
726
+ problem ??= error;
727
+ }
728
+ }
729
+ return { answer, problem };
730
+ }
731
+ function batchEntry(entry, sent, keys, answer) {
732
+ const index = isObject(entry) ? entry.index : void 0;
733
+ if (!isObject(entry) || !Number.isInteger(index) || index < 0 || index >= sent.length) {
734
+ throw invalidBatch("a batch result has no valid index");
735
+ }
736
+ if (!Number.isInteger(entry.status)) throw invalidBatch(`batch result ${index} has no status`);
737
+ const position2 = sent[index];
738
+ if (answer.has(position2)) throw invalidBatch(`two batch results have index ${index}`);
739
+ return [
740
+ position2,
741
+ {
742
+ index: position2,
743
+ status: entry.status,
744
+ monitor: isObject(entry.monitor) ? monitorFrom(entry.monitor) : null,
745
+ replayed: entry.replayed === true,
746
+ error: optObject(entry.error),
747
+ retryAfter: optInt(entry.retry_after),
748
+ idempotencyKey: keys[position2],
749
+ raw: entry
750
+ }
751
+ ];
752
+ }
753
+ function comesBack(result) {
754
+ if (result === void 0 || result.status === 429) return true;
755
+ return result.status === 409 && isObject(result.error) && result.error.code === "idempotency_in_progress";
756
+ }
757
+ function failed(error, results, keys) {
758
+ const message = withNote(error.message);
759
+ const { status, code, details, retryAfter } = error;
760
+ const thrown = error instanceof TimeoutError ? new TimeoutError(message, error.cause) : new TelemError(message, { status, code, details, retryAfter, cause: error });
761
+ return attach(thrown, results, keys);
762
+ }
763
+ function aborted(reason, results, keys) {
764
+ const thrown = new TelemError(withNote("monitors.createMany() was aborted"), { code: "aborted", cause: reason });
765
+ return attach(thrown, results, keys);
766
+ }
767
+ function withNote(message) {
768
+ return `${message}${message.endsWith(".") ? "" : "."} ${MAY_EXIST_MANY}`;
769
+ }
770
+ function attach(thrown, results, keys) {
771
+ const answered = results.filter((result) => result !== void 0);
772
+ Object.defineProperty(thrown, "results", { value: answered, writable: true, configurable: true });
773
+ Object.defineProperty(thrown, "idempotencyKeys", { value: [...keys], writable: true, configurable: true });
774
+ return thrown;
775
+ }
776
+ async function pause(config, ms, signal) {
777
+ if (!signal) return config.sleep(ms);
778
+ if (signal.aborted) throw signal.reason ?? new Error("aborted");
779
+ let onAbort = () => {
780
+ };
781
+ const aborted2 = new Promise((_, reject) => {
782
+ onAbort = () => reject(signal.reason ?? new Error("aborted"));
783
+ signal.addEventListener("abort", onAbort, { once: true });
784
+ });
785
+ try {
786
+ await Promise.race([config.sleep(ms), aborted2]);
787
+ } finally {
788
+ signal.removeEventListener("abort", onAbort);
789
+ }
790
+ }
639
791
  function createMonitors(config) {
640
792
  const path = (monitorId, suffix = "") => {
641
793
  if (!monitorId || /^\.+$/.test(monitorId)) throw invalidRequest("a monitor id is required");
@@ -663,50 +815,89 @@ function createMonitors(config) {
663
815
  return {
664
816
  /** Create a monitor. Telem runs `query` on the schedule, and its agent keeps what matches. */
665
817
  async create(query, options) {
666
- const given = options ?? {};
667
- const agent = given.agent == null ? true : Boolean(given.agent);
668
- if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
669
- const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
670
- if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
671
- throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
672
- }
673
- const monitorOptions = {};
674
- if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
675
- if (given.includeDomains !== void 0) {
676
- monitorOptions.include_domains = given.includeDomains;
677
- }
678
- if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
679
- const body = { query, options: monitorOptions };
680
- if (given.metadata !== void 0) body.metadata = given.metadata;
681
- if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
682
- if (given.ttl !== void 0) body.ttl = given.ttl;
683
- if (given.inputs != null) {
684
- body.inputs = given.inputs;
685
- const vertical = config.defaults.vertical;
686
- if (vertical !== void 0 && !("vertical" in given.inputs)) {
687
- body.inputs = { ...given.inputs, vertical };
688
- }
689
- }
690
- body.agent = agent;
691
- if (given.preset != null) body.preset = given.preset;
692
- if (given.tags != null) body.tags = given.tags;
818
+ const { body, key } = createBody(config, query, options);
693
819
  const extra = {
694
820
  headers: { "Idempotency-Key": key },
695
821
  maxRetries: config.createMaxRetries,
696
822
  budgetMs: CREATE_RETRY_BUDGET_MS
697
823
  };
698
- const data = await request(config, "POST", "/v1/monitors", body, given.signal, "idempotent", extra).catch(
699
- (error) => {
700
- if (error instanceof TimeoutError) {
701
- throw new TimeoutError(
702
- `${error.message}. The monitor may exist: list monitors before you create it again.`,
703
- error.cause
704
- );
824
+ const data = await request(config, "POST", "/v1/monitors", body, options?.signal, "idempotent", extra).catch(
825
+ mayExist(MAY_EXIST)
826
+ );
827
+ return monitorFrom(data);
828
+ },
829
+ /** Create many monitors, ten per call, one call after another. */
830
+ async createMany(items, options = {}) {
831
+ if (!Array.isArray(items)) throw invalidRequest("createMany takes an array of monitors");
832
+ const given = /* @__PURE__ */ new Map();
833
+ const bodies = items.map((item, index) => {
834
+ try {
835
+ if (!isObject(item)) throw invalidRequest("a monitor must be an object of create's options");
836
+ const unknown = Object.keys(item).find((key2) => !ITEM_FIELDS.has(key2));
837
+ if (unknown !== void 0) throw invalidRequest(`unknown option ${JSON.stringify(unknown)}`);
838
+ if (item.query == null) throw invalidRequest("query is required");
839
+ const { body, key } = createBody(config, item.query, item);
840
+ try {
841
+ JSON.stringify(body);
842
+ } catch (cause) {
843
+ throw invalidRequest(`not JSON: ${cause?.message ?? String(cause)}`);
705
844
  }
845
+ return { ...body, idempotency_key: key };
846
+ } catch (error) {
847
+ if (error instanceof TelemError) throw invalidRequest(`monitor ${index}: ${error.message}`);
706
848
  throw error;
707
849
  }
708
- );
709
- return monitorFrom(data);
850
+ });
851
+ items.forEach((item, index) => {
852
+ if (item.idempotencyKey == null) return;
853
+ const first = given.get(item.idempotencyKey) ?? index;
854
+ given.set(item.idempotencyKey, first);
855
+ if (first !== index) throw invalidRequest(`monitors ${first} and ${index} have the same idempotencyKey`);
856
+ });
857
+ const keys = bodies.map((body) => body.idempotency_key);
858
+ const results = Array(bodies.length).fill(void 0);
859
+ let sent = false;
860
+ const fail = (error) => {
861
+ if (!sent) return error;
862
+ if (!(error instanceof TelemError)) {
863
+ if (!options.signal?.aborted) return error;
864
+ return aborted(error, results, keys);
865
+ }
866
+ return failed(error, results, keys);
867
+ };
868
+ for (let offset = 0; offset < bodies.length; offset += BATCH_SIZE) {
869
+ let pending = keys.slice(offset, offset + BATCH_SIZE).map((_, i) => offset + i);
870
+ const started = Date.now();
871
+ for (let attempt = 0; ; attempt++) {
872
+ const extra = {
873
+ maxRetries: config.createMaxRetries,
874
+ budgetMs: CREATE_RETRY_BUDGET_MS - (Date.now() - started),
875
+ lostReplyStatuses: GATEWAY_TIMEOUTS
876
+ };
877
+ const body = { monitors: pending.map((i) => bodies[i]) };
878
+ let data;
879
+ try {
880
+ sent ||= !options.signal?.aborted;
881
+ data = await request(config, "POST", "/v1/monitors:batch", body, options.signal, "idempotent", extra);
882
+ } catch (error) {
883
+ throw fail(error);
884
+ }
885
+ const { answer, problem } = batchAnswer(data, pending, keys);
886
+ for (const [position2, result] of answer) results[position2] = result;
887
+ if (problem) throw fail(problem);
888
+ pending = pending.filter((i) => comesBack(results[i]));
889
+ if (!pending.length || attempt >= config.createMaxRetries) break;
890
+ const known = pending.map((i) => results[i].retryAfter).filter((n) => n !== null && n >= 0);
891
+ const wait = idempotentWait(known.length ? Math.max(...known) : null, attempt);
892
+ if (Date.now() - started + wait > CREATE_RETRY_BUDGET_MS) break;
893
+ try {
894
+ await pause(config, wait, options.signal);
895
+ } catch (error) {
896
+ throw fail(error);
897
+ }
898
+ }
899
+ }
900
+ return results;
710
901
  },
711
902
  /** List your monitors, newest first. `listPage` also gives the next cursor. */
712
903
  async list(options = {}) {
@@ -9,7 +9,7 @@ import {
9
9
  toolMarker,
10
10
  windowAnchor,
11
11
  withTrajectory
12
- } from "../chunk-TST6J3VA.js";
12
+ } from "../chunk-274HRD4N.js";
13
13
 
14
14
  // src/vercel/index.ts
15
15
  import { jsonSchema } from "ai";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telemai/sdk",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Telem web search and fetch for JavaScript and TypeScript.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",