@telemai/sdk 0.5.0 → 0.6.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
@@ -19,15 +19,17 @@ import {
19
19
  windowAnchor,
20
20
  wireMetadata,
21
21
  withTrajectory
22
- } from "./chunk-SQ3ZZA72.js";
22
+ } from "./chunk-TST6J3VA.js";
23
23
 
24
24
  // src/version.ts
25
- var VERSION = "0.5.0";
25
+ var VERSION = "0.6.0";
26
26
 
27
27
  // src/config.ts
28
28
  var DEFAULT_BASE_URL = "https://router.telem.ai";
29
29
  var DEFAULT_TIMEOUT_MS = 6e4;
30
30
  var DEFAULT_MAX_RETRIES = 2;
31
+ var CREATE_RETRY_BUDGET_MS = 12e4;
32
+ var DEFAULT_CREATE_MAX_RETRIES = 60;
31
33
  var BLANK = /^[ \t\n\r\v\f\u00a0\ufeff\u3000]+|[ \t\n\r\v\f\u00a0\ufeff\u3000]+$/g;
32
34
  function trimBlank(value) {
33
35
  return value.replace(BLANK, "");
@@ -90,6 +92,12 @@ function resolveConfig(options) {
90
92
  apiKey = apiKey ?? credentials.apiKey;
91
93
  baseUrl = baseUrl ?? credentials.baseUrl;
92
94
  }
95
+ if (opts.defaultVertical !== void 0 && opts.vertical !== void 0 && opts.defaultVertical !== opts.vertical) {
96
+ throw invalidOption(
97
+ `vertical ${JSON.stringify(opts.vertical)} and defaultVertical ${JSON.stringify(opts.defaultVertical)} are the same option; pass one of them`
98
+ );
99
+ }
100
+ const vertical = opts.defaultVertical ?? opts.vertical ?? (trimBlank(env.TELEM_VERTICAL ?? "") || void 0);
93
101
  const resolvedBaseUrl = (baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, "");
94
102
  let scheme;
95
103
  try {
@@ -105,6 +113,7 @@ function resolveConfig(options) {
105
113
  baseUrl: resolvedBaseUrl,
106
114
  timeoutMs,
107
115
  maxRetries,
116
+ createMaxRetries: opts.maxRetries ?? DEFAULT_CREATE_MAX_RETRIES,
108
117
  userAgent: opts.userAgent || `telem-sdk-js/${VERSION}`,
109
118
  fetch: send,
110
119
  sleep: opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
@@ -120,7 +129,8 @@ function resolveConfig(options) {
120
129
  includeFullContent: opts.includeFullContent ?? (env.TELEM_FULL_CONTENT === "1" || void 0),
121
130
  autoRouting: opts.autoRouting ?? (trimBlank(env.TELEM_AUTO_ROUTING ?? "") || void 0),
122
131
  maxRoutingProviders: opts.maxRoutingProviders ?? intEnv(env.TELEM_MAX_ROUTING_PROVIDERS),
123
- topic: opts.topic ?? (trimBlank(env.TELEM_TOPIC ?? "") || void 0)
132
+ topic: opts.topic ?? (trimBlank(env.TELEM_TOPIC ?? "") || void 0),
133
+ vertical
124
134
  },
125
135
  // Fetch defaults: env var only, parsed as the shared option table parses it (CSV,
126
136
  // a trimmed name, a "1"-only flag); the tier is lowercased, as the agent plugins
@@ -247,6 +257,8 @@ function searchBlock(defaults, options) {
247
257
  if (options.publishedAfter !== void 0) block.published_after = isoDate(options.publishedAfter);
248
258
  if (options.publishedBefore !== void 0) block.published_before = isoDate(options.publishedBefore);
249
259
  if (options.includeDomains !== void 0) block.include_domains = options.includeDomains;
260
+ const vertical = options.vertical ?? defaults.vertical;
261
+ if (vertical !== void 0) block.vertical = vertical;
250
262
  return block;
251
263
  }
252
264
  function isoDate(value) {
@@ -358,6 +370,8 @@ async function search(config, query, options) {
358
370
 
359
371
  // src/methods/monitors.ts
360
372
  var NEEDS_TTL = 'A monitor with an agent must end: pass ttl, such as ttl: "30d" (at most 30 days), or agent: false for a monitor without an agent.';
373
+ var NEEDS_TTL_INPUTS = 'A monitor with inputs must end: pass ttl, such as ttl: "30d" (at most 365 days).';
374
+ var IDEMPOTENCY_KEY = /^[\x21-\x7e]{1,255}$/;
361
375
  var POLL_DEPRECATED = "@telemai/sdk: monitors.poll() is deprecated: read what the monitor agent finds with monitors.iterateChanges() or monitors.changes().";
362
376
  var pollWarned = false;
363
377
  function warnPollDeprecated() {
@@ -395,6 +409,7 @@ function monitorFrom(body) {
395
409
  webhookUrl: data.webhook_url ?? null,
396
410
  webhookSecret: data.webhook_secret ?? null,
397
411
  agentNote: typeof data.agent_note === "string" ? data.agent_note : null,
412
+ tags: asArray(data.tags).map(String),
398
413
  raw: data
399
414
  };
400
415
  if (data.agent_state !== void 0) {
@@ -440,10 +455,116 @@ function changesPageFrom(body) {
440
455
  watermark: Number(data.watermark ?? 0)
441
456
  };
442
457
  }
458
+ function monitorsChangesPageFrom(body) {
459
+ const data = asObject(body);
460
+ return {
461
+ changes: asArray(data.changes).filter(isObject).map(changeRecordFrom),
462
+ nextCursor: typeof data.next_cursor === "string" ? data.next_cursor : "",
463
+ more: data.more === true,
464
+ monitors: asArray(data.monitors).map(String),
465
+ pending: asArray(data.pending).map(String),
466
+ skipped: asArray(data.skipped).map(String)
467
+ };
468
+ }
469
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
470
+ var countOf = (value) => Array.isArray(value) ? value.length : typeof value === "number" ? value : 0;
471
+ function setFields(fields) {
472
+ return Object.fromEntries(Object.entries(fields).filter(([key, value]) => key !== "signal" && value != null));
473
+ }
474
+ function exampleFrom(data) {
475
+ if (!isObject(data)) return null;
476
+ return { name: stringOrNull(data.name), quote: stringOrNull(data.quote), url: stringOrNull(data.url) };
477
+ }
478
+ function candidateFrom(entry) {
479
+ return {
480
+ id: String(entry.id ?? ""),
481
+ what: stringOrNull(entry.what),
482
+ label: String(entry.label ?? ""),
483
+ mappedTo: stringOrNull(entry.mapped_to),
484
+ isNew: entry.is_new === true,
485
+ count: countOf(entry.count),
486
+ origins: countOf(entry.origins),
487
+ example: exampleFrom(entry.example),
488
+ raw: entry
489
+ };
490
+ }
491
+ function companySheetFrom(data) {
492
+ return {
493
+ companyId: stringOrNull(data.company_id),
494
+ pages: countOf(data.pages),
495
+ candidates: asArray(data.candidates).filter(isObject).map(candidateFrom),
496
+ note: stringOrNull(data.note),
497
+ raw: data
498
+ };
499
+ }
500
+ function onboardingCompanyFrom(entry) {
501
+ return {
502
+ companyId: String(entry.company_id ?? ""),
503
+ status: String(entry.status ?? ""),
504
+ runId: stringOrNull(entry.run_id),
505
+ sheet: isObject(entry.sheet) ? companySheetFrom(entry.sheet) : null,
506
+ marks: isObject(entry.marks) ? entry.marks : null,
507
+ at: stringOrNull(entry.at),
508
+ appliedAt: stringOrNull(entry.applied_at),
509
+ raw: entry
510
+ };
511
+ }
512
+ function onboardingSheetFrom(body) {
513
+ const data = asObject(body);
514
+ return {
515
+ monitorId: stringOrNull(data.monitor_id),
516
+ companies: asArray(data.companies).filter(isObject).map(onboardingCompanyFrom),
517
+ raw: data
518
+ };
519
+ }
520
+ function applyResultFrom(body) {
521
+ const data = asObject(body);
522
+ return { jobId: String(data.job_id ?? ""), raw: data };
523
+ }
524
+ function expansionFrom(entry) {
525
+ return {
526
+ id: String(entry.id ?? ""),
527
+ kind: String(entry.kind ?? ""),
528
+ target: String(entry.target ?? ""),
529
+ status: String(entry.status ?? ""),
530
+ reason: asObject(entry.reason),
531
+ delta: asObject(entry.delta),
532
+ counts: asObject(entry.counts),
533
+ note: stringOrNull(entry.note),
534
+ runId: stringOrNull(entry.run_id),
535
+ createdAt: stringOrNull(entry.created_at),
536
+ updatedAt: stringOrNull(entry.updated_at),
537
+ raw: entry
538
+ };
539
+ }
540
+ function expansionsPageFrom(body) {
541
+ const data = asObject(body);
542
+ return {
543
+ expansions: asArray(data.expansions).filter(isObject).map(expansionFrom),
544
+ nextCursor: stringOrNull(data.next_cursor)
545
+ };
546
+ }
547
+ function feedbackResultFrom(body) {
548
+ const data = asObject(body);
549
+ return { status: String(data.status ?? ""), jobId: stringOrNull(data.job_id), raw: data };
550
+ }
551
+ function dataMapFrom(body) {
552
+ const data = asObject(body);
553
+ return {
554
+ // A kind named bare, as a monitor created without inputs may have it.
555
+ kinds: asArray(data.kinds).map((kind) => typeof kind === "string" ? { kind } : kind).filter(isObject),
556
+ categories: asArray(data.categories).filter(isObject),
557
+ inducedCategories: asArray(data.induced_categories).filter(isObject),
558
+ people: asObject(data.people),
559
+ note: stringOrNull(data.note),
560
+ raw: data
561
+ };
562
+ }
443
563
  function listQuery(options) {
444
564
  const params = new URLSearchParams();
445
565
  if (options.limit !== void 0) params.set("limit", String(options.limit));
446
566
  if (options.cursor !== void 0) params.set("cursor", options.cursor);
567
+ if (options.tag !== void 0) params.set("tag", options.tag);
447
568
  const query = params.toString();
448
569
  return query ? `?${query}` : "";
449
570
  }
@@ -455,12 +576,28 @@ function sinceParam(since) {
455
576
  function changesQuery(options) {
456
577
  const params = new URLSearchParams();
457
578
  if (options.cursor !== void 0) params.set("cursor", String(options.cursor));
579
+ return readQuery(params, options);
580
+ }
581
+ function readQuery(params, options) {
458
582
  if (options.since !== void 0) params.set("since", sinceParam(options.since));
459
583
  if (options.kinds !== void 0) params.set("kinds", options.kinds.join(","));
460
584
  if (options.limit !== void 0) params.set("limit", String(options.limit));
461
585
  const query = params.toString();
462
586
  return query ? `?${query}` : "";
463
587
  }
588
+ function acrossQuery(scope, options) {
589
+ const { tag, ids } = asObject(scope);
590
+ if (tag == null === (ids == null)) throw invalidRequest("send tag or ids, one of them");
591
+ const params = new URLSearchParams();
592
+ if (tag != null) params.set("tag", String(tag));
593
+ else {
594
+ const named = typeof ids === "string" ? ids : asArray(ids).join(",");
595
+ if (!named) throw invalidRequest("ids needs at least one monitor id");
596
+ params.set("ids", named);
597
+ }
598
+ if (options.cursor !== void 0) params.set("cursor", options.cursor);
599
+ return readQuery(params, options);
600
+ }
464
601
  function createMonitors(config) {
465
602
  const path = (monitorId, suffix = "") => {
466
603
  if (!monitorId || /^\.+$/.test(monitorId)) throw invalidRequest("a monitor id is required");
@@ -476,12 +613,25 @@ function createMonitors(config) {
476
613
  const route = `${path(monitorId, "/agent/changes")}${changesQuery(options)}`;
477
614
  return changesPageFrom(await request(config, "GET", route, void 0, options.signal));
478
615
  };
616
+ const changesAcross = async (scope, options = {}) => {
617
+ const route = `/v1/monitors/changes${acrossQuery(scope, options)}`;
618
+ return monitorsChangesPageFrom(await request(config, "GET", route, void 0, options.signal));
619
+ };
620
+ const expansionPath = (monitorId, expansionId, action) => {
621
+ if (!expansionId || /^\.+$/.test(expansionId)) throw invalidRequest("an expansion id is required");
622
+ return path(monitorId, `/agent/expansions/${encodeURIComponent(expansionId)}:${action}`);
623
+ };
624
+ const write = async (route, body, signal) => request(config, "POST", route, body, signal, "rate_limit");
479
625
  return {
480
626
  /** Create a monitor. Telem runs `query` on the schedule, and its agent keeps what matches. */
481
627
  async create(query, options) {
482
628
  const given = options ?? {};
483
629
  const agent = given.agent == null ? true : Boolean(given.agent);
484
- if (agent && !given.ttl) throw invalidRequest(NEEDS_TTL);
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
+ }
485
635
  const monitorOptions = {};
486
636
  if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
487
637
  if (given.includeDomains !== void 0) {
@@ -492,8 +642,22 @@ function createMonitors(config) {
492
642
  if (given.metadata !== void 0) body.metadata = given.metadata;
493
643
  if (given.webhookUrl !== void 0) body.webhook_url = given.webhookUrl;
494
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
+ }
495
652
  body.agent = agent;
496
- const data = await request(config, "POST", "/v1/monitors", body, given.signal, "rate_limit").catch(
653
+ if (given.preset != null) body.preset = given.preset;
654
+ if (given.tags != null) body.tags = given.tags;
655
+ const extra = {
656
+ headers: { "Idempotency-Key": key },
657
+ maxRetries: config.createMaxRetries,
658
+ budgetMs: CREATE_RETRY_BUDGET_MS
659
+ };
660
+ const data = await request(config, "POST", "/v1/monitors", body, given.signal, "idempotent", extra).catch(
497
661
  (error) => {
498
662
  if (error instanceof TimeoutError) {
499
663
  throw new TimeoutError(
@@ -522,6 +686,7 @@ function createMonitors(config) {
522
686
  if (options.frequency !== void 0) body.frequency = options.frequency;
523
687
  if (options.ttl !== void 0) body.ttl = options.ttl;
524
688
  if (options.webhookUrl !== void 0) body.webhook_url = options.webhookUrl || null;
689
+ if (options.tags != null) body.tags = options.tags;
525
690
  const route = path(monitorId);
526
691
  return monitorFrom(await request(config, "PATCH", route, body, options.signal));
527
692
  },
@@ -556,6 +721,58 @@ function createMonitors(config) {
556
721
  if (!page.changes.length || page.nextCursor <= cursor || page.nextCursor >= page.watermark) return;
557
722
  cursor = page.nextCursor;
558
723
  }
724
+ },
725
+ /** One page of the changes of up to 100 monitors. Keep `nextCursor` and pass it back as `cursor`. */
726
+ changesAcross,
727
+ /** The changes of up to 100 monitors, page by page while `more` is true. `since` goes
728
+ * with the first page only; the scope, `kinds` and `limit` with every page. */
729
+ async *iterateChangesAcross(scope, options = {}) {
730
+ let { cursor, since } = options;
731
+ for (; ; ) {
732
+ const page = await changesAcross(scope, { ...options, cursor, since });
733
+ for (const change of page.changes) yield change;
734
+ if (!page.more || !page.changes.length || page.nextCursor === cursor) return;
735
+ cursor = page.nextCursor;
736
+ since = void 0;
737
+ }
738
+ },
739
+ /** Label one fact of the monitor; with `category`, file a refuted fact there. */
740
+ async feedback(monitorId, options) {
741
+ const body = { fact_id: options.factId, verdict: options.verdict };
742
+ if (options.category != null) body.category = options.category;
743
+ return feedbackResultFrom(await write(path(monitorId, "/agent/feedback"), body, options.signal));
744
+ },
745
+ /** The onboarding sheet of each company of a monitor created with `inputs`. */
746
+ async onboarding(monitorId, options = {}) {
747
+ const route = path(monitorId, "/agent/onboarding");
748
+ return onboardingSheetFrom(await request(config, "GET", route, void 0, options.signal));
749
+ },
750
+ /** Apply your review of one company's sheet: `companyId` goes as `company_id`. */
751
+ async applyOnboarding(monitorId, marks) {
752
+ const { companyId, ...rest } = marks;
753
+ const body = setFields({ company_id: companyId, ...rest });
754
+ return applyResultFrom(await write(path(monitorId, "/agent/onboarding:apply"), body, marks.signal));
755
+ },
756
+ /** What the monitor proposes to add, or added; `status` filters. */
757
+ async expansions(monitorId, options = {}) {
758
+ const query = options.status !== void 0 ? `?${new URLSearchParams({ status: options.status })}` : "";
759
+ const route = `${path(monitorId, "/agent/expansions")}${query}`;
760
+ return expansionsPageFrom(await request(config, "GET", route, void 0, options.signal));
761
+ },
762
+ /** Use a proposed addition. */
763
+ async confirmExpansion(monitorId, expansionId, fields = {}) {
764
+ const route = expansionPath(monitorId, expansionId, "confirm");
765
+ return applyResultFrom(await write(route, setFields(fields), fields.signal));
766
+ },
767
+ /** Remove an addition. */
768
+ async revertExpansion(monitorId, expansionId, options = {}) {
769
+ const route = expansionPath(monitorId, expansionId, "revert");
770
+ return applyResultFrom(await write(route, {}, options.signal));
771
+ },
772
+ /** Every kind and category the monitor collects. */
773
+ async dataMap(monitorId, options = {}) {
774
+ const route = path(monitorId, "/agent/data-map");
775
+ return dataMapFrom(await request(config, "GET", route, void 0, options.signal));
559
776
  }
560
777
  };
561
778
  }
@@ -659,7 +876,10 @@ var Telem = class {
659
876
  /** The session read surface: `list` and `results(id)`. */
660
877
  sessions;
661
878
  /** Monitors: `create`, `list`, `listPage`, `get`, `update` and `delete`, the agent reads
662
- * `agent`, `changes` and `iterateChanges`, and the deprecated `poll`. */
879
+ * `agent`, `changes` and `iterateChanges`, the read across monitors `changesAcross` and
880
+ * `iterateChangesAcross`, `feedback`, what a monitor created with
881
+ * `inputs` collects (`onboarding`, `applyOnboarding`, `expansions`, `confirmExpansion`,
882
+ * `revertExpansion`, `dataMap`), and the deprecated `poll`. */
663
883
  monitors;
664
884
  #config;
665
885
  /**
@@ -9,7 +9,7 @@ import {
9
9
  toolMarker,
10
10
  windowAnchor,
11
11
  withTrajectory
12
- } from "../chunk-SQ3ZZA72.js";
12
+ } from "../chunk-TST6J3VA.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.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Telem web search and fetch for JavaScript and TypeScript.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",