@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/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.6.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,18 +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,
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),
320
330
  provider,
321
331
  raw: row
322
332
  }));
@@ -363,7 +373,7 @@ function buildSearchResponse(interaction) {
363
373
  }
364
374
  async function search(config, query, options) {
365
375
  const body = searchBody(config, query, options);
366
- const data = await request(config, "POST", "/v1/interactions", body, options.signal);
376
+ const data = await request(config, "POST", "/v1/interactions", body, options.signal, "metered");
367
377
  assertV2(data);
368
378
  return buildSearchResponse(data);
369
379
  }
@@ -386,7 +396,7 @@ function agentStateFrom(data) {
386
396
  needsAttention: data.needs_attention === true,
387
397
  planVersion: typeof data.plan_version === "number" ? data.plan_version : null,
388
398
  nextRunAt: typeof data.next_run_at === "string" ? data.next_run_at : null,
389
- watermark: Number(data.watermark ?? 0),
399
+ watermark: finite(data.watermark),
390
400
  // No compile job yet is null, not an object of empty strings.
391
401
  compile: isObject(data.compile) ? {
392
402
  jobId: String(data.compile.job_id ?? ""),
@@ -428,10 +438,17 @@ function agentDocumentFrom(body) {
428
438
  if (typeof data.spend_usd === "number") document.spendUsd = data.spend_usd;
429
439
  return document;
430
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
+ }
431
448
  function changeRecordFrom(entry) {
432
449
  const subject = asObject(entry.subject);
433
450
  return {
434
- seq: Number(entry.seq ?? 0),
451
+ seq: position(entry.seq, "change seq"),
435
452
  type: String(entry.type ?? ""),
436
453
  kind: String(entry.kind ?? ""),
437
454
  monitorId: String(entry.monitor_id ?? ""),
@@ -451,8 +468,8 @@ function changesPageFrom(body) {
451
468
  const data = asObject(body);
452
469
  return {
453
470
  changes: asArray(data.changes).filter(isObject).map(changeRecordFrom),
454
- nextCursor: Number(data.next_cursor ?? 0),
455
- watermark: Number(data.watermark ?? 0)
471
+ nextCursor: position(data.next_cursor, "changes page next_cursor"),
472
+ watermark: position(data.watermark, "changes page watermark")
456
473
  };
457
474
  }
458
475
  function monitorsChangesPageFrom(body) {
@@ -560,6 +577,45 @@ function dataMapFrom(body) {
560
577
  raw: data
561
578
  };
562
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
+ }
584
+ function companyFrom(entry) {
585
+ return {
586
+ companyId: String(entry.company_id ?? ""),
587
+ name: String(entry.name ?? ""),
588
+ domain: String(entry.domain ?? ""),
589
+ priority: entry.priority === true,
590
+ aliases: asArray(entry.aliases).map(String),
591
+ ticker: String(entry.ticker ?? ""),
592
+ xHandle: String(entry.x_handle ?? ""),
593
+ newsroomUrl: String(entry.newsroom_url ?? ""),
594
+ teamPage: String(entry.team_page ?? ""),
595
+ tier: String(entry.tier ?? ""),
596
+ rank: finite(entry.rank),
597
+ raw: entry
598
+ };
599
+ }
600
+ function companyListFrom(body) {
601
+ const data = asObject(body);
602
+ return {
603
+ total: finite(data.total),
604
+ priorityCount: finite(data.priority_count),
605
+ offset: finite(data.offset),
606
+ limit: finite(data.limit),
607
+ nextOffset: typeof data.next_offset === "number" ? data.next_offset : null,
608
+ companies: asArray(data.companies).filter(isObject).map(companyFrom),
609
+ raw: data
610
+ };
611
+ }
612
+ function companiesQuery(options) {
613
+ const params = new URLSearchParams();
614
+ if (options.offset !== void 0) params.set("offset", String(options.offset));
615
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
616
+ const query = params.toString();
617
+ return query ? `?${query}` : "";
618
+ }
563
619
  function listQuery(options) {
564
620
  const params = new URLSearchParams();
565
621
  if (options.limit !== void 0) params.set("limit", String(options.limit));
@@ -598,6 +654,140 @@ function acrossQuery(scope, options) {
598
654
  if (options.cursor !== void 0) params.set("cursor", options.cursor);
599
655
  return readQuery(params, options);
600
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
+ }
601
791
  function createMonitors(config) {
602
792
  const path = (monitorId, suffix = "") => {
603
793
  if (!monitorId || /^\.+$/.test(monitorId)) throw invalidRequest("a monitor id is required");
@@ -625,50 +815,89 @@ function createMonitors(config) {
625
815
  return {
626
816
  /** Create a monitor. Telem runs `query` on the schedule, and its agent keeps what matches. */
627
817
  async create(query, options) {
628
- const given = options ?? {};
629
- const agent = given.agent == null ? true : Boolean(given.agent);
630
- if (agent && !given.ttl) throw invalidRequest(given.inputs == null ? NEEDS_TTL : NEEDS_TTL_INPUTS);
631
- const key = given.idempotencyKey ?? globalThis.crypto.randomUUID();
632
- if (typeof key !== "string" || !IDEMPOTENCY_KEY.test(key)) {
633
- throw invalidRequest("idempotencyKey must be 1 to 255 visible ASCII characters");
634
- }
635
- const monitorOptions = {};
636
- if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
637
- if (given.includeDomains !== void 0) {
638
- monitorOptions.include_domains = given.includeDomains;
639
- }
640
- if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
641
- const body = { query, options: monitorOptions };
642
- if (given.metadata !== void 0) body.metadata = given.metadata;
643
- if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
644
- if (given.ttl !== void 0) body.ttl = given.ttl;
645
- if (given.inputs != null) {
646
- body.inputs = given.inputs;
647
- const vertical = config.defaults.vertical;
648
- if (vertical !== void 0 && !("vertical" in given.inputs)) {
649
- body.inputs = { ...given.inputs, vertical };
650
- }
651
- }
652
- body.agent = agent;
653
- if (given.preset != null) body.preset = given.preset;
654
- if (given.tags != null) body.tags = given.tags;
818
+ const { body, key } = createBody(config, query, options);
655
819
  const extra = {
656
820
  headers: { "Idempotency-Key": key },
657
821
  maxRetries: config.createMaxRetries,
658
822
  budgetMs: CREATE_RETRY_BUDGET_MS
659
823
  };
660
- const data = await request(config, "POST", "/v1/monitors", body, given.signal, "idempotent", extra).catch(
661
- (error) => {
662
- if (error instanceof TimeoutError) {
663
- throw new TimeoutError(
664
- `${error.message}. The monitor may exist: list monitors before you create it again.`,
665
- error.cause
666
- );
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)}`);
667
844
  }
845
+ return { ...body, idempotency_key: key };
846
+ } catch (error) {
847
+ if (error instanceof TelemError) throw invalidRequest(`monitor ${index}: ${error.message}`);
668
848
  throw error;
669
849
  }
670
- );
671
- 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;
672
901
  },
673
902
  /** List your monitors, newest first. `listPage` also gives the next cursor. */
674
903
  async list(options = {}) {
@@ -773,25 +1002,36 @@ function createMonitors(config) {
773
1002
  async dataMap(monitorId, options = {}) {
774
1003
  const route = path(monitorId, "/agent/data-map");
775
1004
  return dataMapFrom(await request(config, "GET", route, void 0, options.signal));
1005
+ },
1006
+ /** One page of the monitor's companies, in rank order. */
1007
+ async companies(monitorId, options = {}) {
1008
+ const route = `${path(monitorId, "/agent/companies")}${companiesQuery(options)}`;
1009
+ return companyListFrom(await request(config, "GET", route, void 0, options.signal));
776
1010
  }
777
1011
  };
778
1012
  }
779
1013
  async function verifyWebhook(body, header, secret, toleranceSeconds = 300) {
780
- const parts = Object.fromEntries(
781
- header.split(",").map((item) => [item.slice(0, item.indexOf("=")), item.slice(item.indexOf("=") + 1)])
782
- );
783
- const t = parts.t ?? "";
784
- const v1 = parts.v1 ?? "";
1014
+ const parts = header.split(",").map((item) => item.trim()).filter((item) => item.includes("=")).map((item) => [item.slice(0, item.indexOf("=")), item.slice(item.indexOf("=") + 1)]);
1015
+ const timestamps = parts.filter(([name]) => name === "t").map(([, value]) => value);
1016
+ const signatures = parts.filter(([name, value]) => name === "v1" && /^[0-9a-f]{64}$/.test(value)).map(([, value]) => value);
1017
+ if (timestamps.length !== 1 || signatures.length === 0) return false;
1018
+ const t = timestamps[0];
785
1019
  if (!/^\d+$/.test(t) || Math.abs(Date.now() / 1e3 - Number(t)) > toleranceSeconds) return false;
786
- if (!/^([0-9a-f]{2})+$/.test(v1)) return false;
787
1020
  const encoder = new TextEncoder();
788
1021
  const raw = typeof body === "string" ? encoder.encode(body) : body;
789
1022
  const signed = new Uint8Array([...encoder.encode(`${t}.`), ...raw]);
790
1023
  const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
791
- "verify"
1024
+ "sign"
792
1025
  ]);
793
- const signature = new Uint8Array(v1.match(/../g).map((byte) => parseInt(byte, 16)));
794
- return crypto.subtle.verify("HMAC", key, signature, signed);
1026
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, signed));
1027
+ const expected = Array.from(mac, (byte) => byte.toString(16).padStart(2, "0")).join("");
1028
+ return signatures.some((signature) => sameText(signature, expected));
1029
+ }
1030
+ function sameText(a, b) {
1031
+ if (a.length !== b.length) return false;
1032
+ let diff = 0;
1033
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
1034
+ return diff === 0;
795
1035
  }
796
1036
 
797
1037
  // src/methods/providers.ts
@@ -879,7 +1119,7 @@ var Telem = class {
879
1119
  * `agent`, `changes` and `iterateChanges`, the read across monitors `changesAcross` and
880
1120
  * `iterateChangesAcross`, `feedback`, what a monitor created with
881
1121
  * `inputs` collects (`onboarding`, `applyOnboarding`, `expansions`, `confirmExpansion`,
882
- * `revertExpansion`, `dataMap`), and the deprecated `poll`. */
1122
+ * `revertExpansion`, `dataMap`, `companies`), and the deprecated `poll`. */
883
1123
  monitors;
884
1124
  #config;
885
1125
  /**
@@ -452,9 +452,15 @@ async function turnAnchor(messages, windowId) {
452
452
  return await contentAnchor(String(messages.length), windowId, text);
453
453
  }
454
454
  function compact(response) {
455
- return response.results.slice(0, RESULT_CAP).map(({ provider, title, url, summary, publishDate }) => {
455
+ return response.results.slice(0, RESULT_CAP).map(({ provider, title, url, summary, publishDate, imageUrl, imageWidth, imageHeight }) => {
456
456
  const published = publishDate?.trim();
457
- return published ? { provider, title, url, summary, published } : { provider, title, url, summary };
457
+ const row = published ? { provider, title, url, summary, published } : { provider, title, url, summary };
458
+ const image = typeof imageUrl === "string" ? imageUrl.trim() : "";
459
+ if (image) {
460
+ const whole = (n) => Number.isInteger(n) && n > 0;
461
+ row.image = whole(imageWidth) && whole(imageHeight) ? { url: image, width: imageWidth, height: imageHeight } : { url: image };
462
+ }
463
+ return row;
458
464
  });
459
465
  }
460
466
  function page(response) {
@@ -479,7 +485,7 @@ var SEARCH_SCHEMA = (0, import_ai.jsonSchema)({
479
485
  },
480
486
  topic: {
481
487
  type: "string",
482
- description: "Optional. Set it only when the answer must come from one site: linkedin, reddit, or x (twitter is also accepted). Leave it unset otherwise."
488
+ description: "Optional. Set it to linkedin, reddit or x (twitter is also accepted) only when the answer must come from that site, or to images for an image search: at most 20 results, no published_after or published_before, and each result adds the image URL and its size. Leave it unset otherwise."
483
489
  },
484
490
  published_after: {
485
491
  type: "string",
@@ -642,7 +648,7 @@ function createTelemVercelAgent(options) {
642
648
  }
643
649
  const tools = {
644
650
  telem_search: {
645
- description: "Search the public web. One query per call; returns the top results with provider, title, url, summary and, when known, publication date. Use telem_fetch to read a page in full.",
651
+ description: "Search the public web. One query per call; returns the top results with provider, title, url, summary and, when known, publication date (and an image search's image). Use telem_fetch to read a page in full.",
646
652
  inputSchema: SEARCH_SCHEMA,
647
653
  execute: async (input, execution) => {
648
654
  const topic = input.topic?.trim() || void 0;
@@ -150,13 +150,18 @@ type TelemVercelFetchInput = {
150
150
  goal?: string;
151
151
  };
152
152
  /** The default `render.search`: the top results, compact. `published` is there only
153
- * when the result has a publication date. */
153
+ * when the result has a publication date, `image` only on an image search's row. */
154
154
  type TelemVercelSearchOutput = Array<{
155
155
  provider: string;
156
156
  title: string;
157
157
  url: string;
158
158
  summary: string | null;
159
159
  published?: string;
160
+ image?: {
161
+ url: string;
162
+ width?: number;
163
+ height?: number;
164
+ };
160
165
  }>;
161
166
  /** The default `render.fetch`: one page's status, error and text. */
162
167
  type TelemVercelFetchOutput = {
@@ -150,13 +150,18 @@ type TelemVercelFetchInput = {
150
150
  goal?: string;
151
151
  };
152
152
  /** The default `render.search`: the top results, compact. `published` is there only
153
- * when the result has a publication date. */
153
+ * when the result has a publication date, `image` only on an image search's row. */
154
154
  type TelemVercelSearchOutput = Array<{
155
155
  provider: string;
156
156
  title: string;
157
157
  url: string;
158
158
  summary: string | null;
159
159
  published?: string;
160
+ image?: {
161
+ url: string;
162
+ width?: number;
163
+ height?: number;
164
+ };
160
165
  }>;
161
166
  /** The default `render.fetch`: one page's status, error and text. */
162
167
  type TelemVercelFetchOutput = {
@@ -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";
@@ -290,9 +290,15 @@ async function turnAnchor(messages, windowId) {
290
290
  return await contentAnchor(String(messages.length), windowId, text);
291
291
  }
292
292
  function compact(response) {
293
- return response.results.slice(0, RESULT_CAP).map(({ provider, title, url, summary, publishDate }) => {
293
+ return response.results.slice(0, RESULT_CAP).map(({ provider, title, url, summary, publishDate, imageUrl, imageWidth, imageHeight }) => {
294
294
  const published = publishDate?.trim();
295
- return published ? { provider, title, url, summary, published } : { provider, title, url, summary };
295
+ const row = published ? { provider, title, url, summary, published } : { provider, title, url, summary };
296
+ const image = typeof imageUrl === "string" ? imageUrl.trim() : "";
297
+ if (image) {
298
+ const whole = (n) => Number.isInteger(n) && n > 0;
299
+ row.image = whole(imageWidth) && whole(imageHeight) ? { url: image, width: imageWidth, height: imageHeight } : { url: image };
300
+ }
301
+ return row;
296
302
  });
297
303
  }
298
304
  function page(response) {
@@ -317,7 +323,7 @@ var SEARCH_SCHEMA = jsonSchema({
317
323
  },
318
324
  topic: {
319
325
  type: "string",
320
- description: "Optional. Set it only when the answer must come from one site: linkedin, reddit, or x (twitter is also accepted). Leave it unset otherwise."
326
+ description: "Optional. Set it to linkedin, reddit or x (twitter is also accepted) only when the answer must come from that site, or to images for an image search: at most 20 results, no published_after or published_before, and each result adds the image URL and its size. Leave it unset otherwise."
321
327
  },
322
328
  published_after: {
323
329
  type: "string",
@@ -480,7 +486,7 @@ function createTelemVercelAgent(options) {
480
486
  }
481
487
  const tools = {
482
488
  telem_search: {
483
- description: "Search the public web. One query per call; returns the top results with provider, title, url, summary and, when known, publication date. Use telem_fetch to read a page in full.",
489
+ description: "Search the public web. One query per call; returns the top results with provider, title, url, summary and, when known, publication date (and an image search's image). Use telem_fetch to read a page in full.",
484
490
  inputSchema: SEARCH_SCHEMA,
485
491
  execute: async (input, execution) => {
486
492
  const topic = input.topic?.trim() || void 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@telemai/sdk",
3
- "version": "0.6.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",