@telemai/sdk 0.4.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.4.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) {
@@ -357,6 +369,16 @@ async function search(config, query, options) {
357
369
  }
358
370
 
359
371
  // src/methods/monitors.ts
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}$/;
375
+ var POLL_DEPRECATED = "@telemai/sdk: monitors.poll() is deprecated: read what the monitor agent finds with monitors.iterateChanges() or monitors.changes().";
376
+ var pollWarned = false;
377
+ function warnPollDeprecated() {
378
+ if (pollWarned) return;
379
+ pollWarned = true;
380
+ console.warn(POLL_DEPRECATED);
381
+ }
360
382
  function agentStateFrom(data) {
361
383
  return {
362
384
  engine: String(data.engine ?? ""),
@@ -386,6 +408,8 @@ function monitorFrom(body) {
386
408
  expiresAt: data.expires_at ?? null,
387
409
  webhookUrl: data.webhook_url ?? null,
388
410
  webhookSecret: data.webhook_secret ?? null,
411
+ agentNote: typeof data.agent_note === "string" ? data.agent_note : null,
412
+ tags: asArray(data.tags).map(String),
389
413
  raw: data
390
414
  };
391
415
  if (data.agent_state !== void 0) {
@@ -431,10 +455,116 @@ function changesPageFrom(body) {
431
455
  watermark: Number(data.watermark ?? 0)
432
456
  };
433
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
+ }
434
563
  function listQuery(options) {
435
564
  const params = new URLSearchParams();
436
565
  if (options.limit !== void 0) params.set("limit", String(options.limit));
437
566
  if (options.cursor !== void 0) params.set("cursor", options.cursor);
567
+ if (options.tag !== void 0) params.set("tag", options.tag);
438
568
  const query = params.toString();
439
569
  return query ? `?${query}` : "";
440
570
  }
@@ -446,12 +576,28 @@ function sinceParam(since) {
446
576
  function changesQuery(options) {
447
577
  const params = new URLSearchParams();
448
578
  if (options.cursor !== void 0) params.set("cursor", String(options.cursor));
579
+ return readQuery(params, options);
580
+ }
581
+ function readQuery(params, options) {
449
582
  if (options.since !== void 0) params.set("since", sinceParam(options.since));
450
583
  if (options.kinds !== void 0) params.set("kinds", options.kinds.join(","));
451
584
  if (options.limit !== void 0) params.set("limit", String(options.limit));
452
585
  const query = params.toString();
453
586
  return query ? `?${query}` : "";
454
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
+ }
455
601
  function createMonitors(config) {
456
602
  const path = (monitorId, suffix = "") => {
457
603
  if (!monitorId || /^\.+$/.test(monitorId)) throw invalidRequest("a monitor id is required");
@@ -467,21 +613,51 @@ function createMonitors(config) {
467
613
  const route = `${path(monitorId, "/agent/changes")}${changesQuery(options)}`;
468
614
  return changesPageFrom(await request(config, "GET", route, void 0, options.signal));
469
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");
470
625
  return {
471
- /** Create a monitor. Telem runs `query` on the schedule. */
472
- async create(query, options = {}) {
626
+ /** Create a monitor. Telem runs `query` on the schedule, and its agent keeps what matches. */
627
+ 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
+ }
473
635
  const monitorOptions = {};
474
- if (options.frequency !== void 0) monitorOptions.frequency = options.frequency;
475
- if (options.includeDomains !== void 0) {
476
- monitorOptions.include_domains = options.includeDomains;
636
+ if (given.frequency !== void 0) monitorOptions.frequency = given.frequency;
637
+ if (given.includeDomains !== void 0) {
638
+ monitorOptions.include_domains = given.includeDomains;
477
639
  }
478
- if (options.search !== void 0) monitorOptions.search = searchBlock({}, options.search);
640
+ if (given.search !== void 0) monitorOptions.search = searchBlock({}, given.search);
479
641
  const body = { query, options: monitorOptions };
480
- if (options.metadata !== void 0) body.metadata = options.metadata;
481
- if (options.webhookUrl !== void 0) body.webhook_url = options.webhookUrl;
482
- if (options.ttl !== void 0) body.ttl = options.ttl;
483
- if (options.agent !== void 0) body.agent = options.agent;
484
- const data = await request(config, "POST", "/v1/monitors", body, options.signal, "rate_limit").catch(
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;
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(
485
661
  (error) => {
486
662
  if (error instanceof TimeoutError) {
487
663
  throw new TimeoutError(
@@ -503,17 +679,21 @@ function createMonitors(config) {
503
679
  async get(monitorId, options = {}) {
504
680
  return monitorFrom(await request(config, "GET", path(monitorId), void 0, options.signal));
505
681
  },
506
- /** Pause, resume or change a monitor. Only the fields given are sent. */
682
+ /** Pause, resume, renew or change a monitor. Only the fields given are sent. */
507
683
  async update(monitorId, options) {
508
684
  const body = {};
509
685
  if (options.status !== void 0) body.status = options.status;
510
686
  if (options.frequency !== void 0) body.frequency = options.frequency;
687
+ if (options.ttl !== void 0) body.ttl = options.ttl;
511
688
  if (options.webhookUrl !== void 0) body.webhook_url = options.webhookUrl || null;
689
+ if (options.tags != null) body.tags = options.tags;
512
690
  const route = path(monitorId);
513
691
  return monitorFrom(await request(config, "PATCH", route, body, options.signal));
514
692
  },
515
- /** Get the results that are new since the last poll. */
693
+ /** Get the monitor's own results that are new since the last poll. Deprecated: it
694
+ * warns once per process. */
516
695
  async poll(monitorId, options = {}) {
696
+ warnPollDeprecated();
517
697
  const body = {};
518
698
  if (options.session !== void 0) body.session_id = options.session;
519
699
  if (options.metadata !== void 0) body.metadata = options.metadata;
@@ -541,6 +721,58 @@ function createMonitors(config) {
541
721
  if (!page.changes.length || page.nextCursor <= cursor || page.nextCursor >= page.watermark) return;
542
722
  cursor = page.nextCursor;
543
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));
544
776
  }
545
777
  };
546
778
  }
@@ -643,8 +875,11 @@ var Telem = class {
643
875
  maxRetries;
644
876
  /** The session read surface: `list` and `results(id)`. */
645
877
  sessions;
646
- /** Monitors: `create`, `list`, `listPage`, `get`, `update`, `poll`, `delete`, and the
647
- * agent reads `agent`, `changes` and `iterateChanges`. */
878
+ /** Monitors: `create`, `list`, `listPage`, `get`, `update` and `delete`, the agent reads
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`. */
648
883
  monitors;
649
884
  #config;
650
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.4.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",