@telemai/sdk 0.1.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,332 @@
1
+ # Telem JavaScript SDK
2
+
3
+ Full documentation: [docs.telem.ai](https://docs.telem.ai/sdks/javascript/).
4
+
5
+
6
+
7
+ > **Fastest install: [the one-line curl](https://docs.telem.ai/).** It finds the agent frameworks you have
8
+ > and installs Telem into the ones you select. The steps below are the manual path.
9
+
10
+ `@telemai/sdk` is a typed TypeScript client for the Telem search API. It searches the
11
+ web across providers and returns the results in the same shape for every provider.
12
+ It also reads pages, lists the providers, and carries query lineage for agents.
13
+
14
+ The package has no runtime dependencies. It uses the platform `fetch`, and you can
15
+ supply your own. So the package runs on Node, in an edge worker, inside another CLI,
16
+ and in tests.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @telemai/sdk
22
+ ```
23
+
24
+ The package ships ESM and CommonJS builds with type definitions. Node 20.16 or later
25
+ is necessary to read the credentials file. On other runtimes that have `fetch`, such
26
+ as edge workers and browsers, pass the API key in code.
27
+
28
+ ## Authentication
29
+
30
+ Create an API key under **API keys** in the [Telem console](https://app.telem.ai/).
31
+ The guided installer writes it to `~/.telem/credentials.json`. You can also set it
32
+ as an environment variable, or pass it in code.
33
+
34
+ The client resolves `apiKey` and `baseUrl` in this order. The first value found wins:
35
+
36
+ 1. A constructor argument.
37
+ 2. The `TELEM_API_KEY` and `TELEM_BASE_URL` environment variables.
38
+ 3. `~/.telem/credentials.json`.
39
+ 4. The defaults: no key, and `https://router.telem.ai` for `baseUrl`.
40
+
41
+ See [Authentication](https://docs.telem.ai/authentication/) for the full rules.
42
+
43
+ ```ts
44
+
45
+ const telem = new Telem() // environment, then ~/.telem/credentials.json
46
+ const telem = new Telem("tlm_...") // just a key
47
+ const telem = new Telem({
48
+ apiKey: "tlm_...",
49
+ baseUrl: "https://router.telem.ai",
50
+ timeoutMs: 60_000, // per attempt
51
+ maxRetries: 2, // on 5xx, network errors and 429
52
+ tier: "extended", // client-wide search defaults go here
53
+ })
54
+ ```
55
+
56
+ The credentials file is the only file the client opens. The client never reads
57
+ `.telem/telem.json`, the file the other Telem tools use for
58
+ [search options](https://docs.telem.ai/resources/config-reference/). A library must not let a
59
+ checked-out repository control the spend of a program. Set search defaults as
60
+ constructor options or call arguments. The `TELEM_*` variables apply below them.
61
+
62
+ ## Search
63
+
64
+ One call searches every provider in the default set. The results come back in one
65
+ list, in the same shape for every provider:
66
+
67
+ ```ts
68
+ const response = await telem.search("best typescript http client")
69
+ for (const result of response.results) {
70
+ console.log(result.provider, result.title, result.url)
71
+ }
72
+ ```
73
+
74
+ Every option applies to one call. An option you do not set uses the client default,
75
+ then the server default:
76
+
77
+ ```ts
78
+ const response = await telem.search("climate policy 2026", {
79
+ tier: "extended", // minimalist | default | extended | max
80
+ providersInclude: ["exa"], // allow-list; omit for the default provider set
81
+ numResults: 10, // rows per provider (server default 5, maximum 20)
82
+ includeFullContent: true, // the full page content, not only a summary
83
+ goal: "brief the user", // recorded with the search; shown in the console
84
+ context: "the user wants the 2026 amendments, not the original 2024 text",
85
+ })
86
+ ```
87
+
88
+ The full option set is `tier`, `fields`, `providersInclude`, `providersExclude`,
89
+ `providerOverrides`, `numResults`, `includeRaw`, `includeFullContent` and `rerank`,
90
+ plus `goal`, `context`, `session` and `metadata`. An `undefined` value is unset. `[]`
91
+ and `false` are explicit values. `tier` and `fields` do not go together, and the
92
+ client sends one of them. When you set both provider lists, the client removes the
93
+ excluded names from the allow-list. The client does not validate values. An unknown
94
+ tier, field or provider name comes back as an error from the server. See
95
+ [Errors](#errors).
96
+
97
+ **[Full parameter reference →](https://docs.telem.ai/resources/config-reference/)** lists every key, its
98
+ environment variable and the precedence. `numResults`, `includeRaw`, `rerank` and
99
+ `providerOverrides` are call arguments only. As client defaults they do nothing.
100
+
101
+ ### `goal` and `context`
102
+
103
+ Telem records both with the search and shows them in the trajectory view in the
104
+ console. A reader of the trace then sees why the search happened. For an agent, use
105
+ the reasoning of the model for this step as `context`: two or three sentences.
106
+ `goal` and `context` change the result order only when you also set
107
+ [rerank](#rerank).
108
+
109
+ ### Multi-query batching
110
+
111
+ Pass an array of queries. They run at the same time, as one request. Each provider
112
+ run carries the query it served:
113
+
114
+ ```ts
115
+ const response = await telem.search([
116
+ "EU AI Act obligations for general-purpose models 2026",
117
+ "how the amended EU AI Act timeline changed",
118
+ ])
119
+ for (const run of response.byProvider) {
120
+ console.log(run.batchIndex, run.query, run.provider, run.results.length)
121
+ }
122
+ ```
123
+
124
+ `response.results` is the flat list across every run. An array with one query
125
+ behaves the same as a plain string.
126
+
127
+ ### `SearchResponse` shape
128
+
129
+ ```ts
130
+ response.results // flat SearchResult[]: providers in run order, rows in provider order
131
+ response.byProvider // ProviderRun[]: one entry per provider, failed providers included
132
+ response.sessionId // the session this call belongs to
133
+ response.interactionId // the id of this request
134
+ response.status // "succeeded" | "partially_succeeded" | "failed"
135
+ ```
136
+
137
+ `byProvider` has one run for each provider that ran. A provider that failed is still
138
+ in the list, with `status` and `error` set and `results` empty. Each result has
139
+ `url`, `title`, `summary`, `excerpt`, `fullContent`, `publishDate`, `rank`,
140
+ `thumbnail`, `favicon`, `source`, `enrichments` and `fetchMeta`, plus `provider` and
141
+ `raw`. `raw` is the row exactly as the server sent it.
142
+
143
+ ### Rerank
144
+
145
+ Set `rerank: true` and the server sorts the results by relevance to your `context`.
146
+ If there is no `context`, it uses your `goal`. Rerank is off by default, and it is
147
+ metered. Set it for one call, not as a client default:
148
+
149
+ ```ts
150
+ const response = await telem.search("Nintendo Museum New Year closure dates", {
151
+ context: "planning a late-December visit; need official closure dates, not reviews",
152
+ rerank: true,
153
+ })
154
+ ```
155
+
156
+ ## Fetch a page
157
+
158
+ Read the content of a URL you already have. Pass one URL or a list. The results come
159
+ back in the order you asked for, including the URLs that failed:
160
+
161
+ ```ts
162
+ const page = await telem.fetch("https://example.com/article", {
163
+ inlineContent: true,
164
+ inlineMaxChars: 20_000,
165
+ contentFormat: "markdown",
166
+ })
167
+ const { status, content } = page.results[0]
168
+ ```
169
+
170
+ A URL that failed still returns a result. Check `result.status` and `result.error`.
171
+ Do not expect a shorter list. The options are on the
172
+ [fetch parameters](https://docs.telem.ai/resources/fetch-parameters/) page.
173
+
174
+ ## Providers
175
+
176
+ List the providers the deployment can run:
177
+
178
+ ```ts
179
+ for (const provider of await telem.providers()) {
180
+ console.log(provider.name, provider.activeByDefault, provider.tiers)
181
+ }
182
+ ```
183
+
184
+ ## Sessions
185
+
186
+ Every search belongs to a session. The response carries its id as `sessionId`. Read
187
+ your sessions back to see what an agent searched for. Both methods require an API key:
188
+
189
+ ```ts
190
+ for (const session of await telem.sessions.list()) {
191
+ console.log(session.id, session.interactionCount, session.latestInteractionAt)
192
+ }
193
+
194
+ const summary = await telem.sessions.results(sessionId)
195
+ console.log(summary.query, summary.goal, summary.context)
196
+ ```
197
+
198
+ `results` returns the query, the goal and the context of the session, plus the
199
+ results of each search step.
200
+
201
+ ## Query lineage
202
+
203
+ Every search and fetch from an agent can carry **lineage data**. Lineage data tells
204
+ Telem which conversation made the call, and where in the conversation it happened.
205
+ The console then shows all the calls of one conversation together, in order, and
206
+ shows which turn made each call. When an agent delegates to other agents, the
207
+ console shows their calls under the agent that started them. You build the lineage
208
+ data from four ids you already have. The model never sees them.
209
+
210
+ The example column uses Codex, which has all four ids:
211
+
212
+ | Id | What it is | Example |
213
+ |---|---|---|
214
+ | `conversationId` | One id for one agent conversation. Make it when the conversation starts, and keep it. A subagent gets its own. | Codex: the thread id. One thread is one conversation. |
215
+ | `windowId` | The id of the current context window. It changes when you trim or summarize the start of the history. | Codex: the window id. Codex makes a new one when it compacts the context. |
216
+ | `messageId` | The id of the model turn that makes the call. All the tool calls in one turn share it. | Codex: the turn id. |
217
+ | `toolCallId` | The id of this tool call. | Codex: the id of the tool call in that turn. |
218
+
219
+ In your own code the ids come from your agent loop. This example uses the OpenAI
220
+ Node SDK, where the completion id is the turn and each tool call has its own id:
221
+
222
+ ```ts
223
+
224
+ const telem = new Telem()
225
+ const openai = new OpenAI()
226
+ const messages = [{ role: "user" as const, content: "Is the Nintendo Museum open over New Year?" }]
227
+ const tools = [
228
+ {
229
+ type: "function" as const,
230
+ function: {
231
+ name: "telem_search",
232
+ description: "Search the public web.",
233
+ parameters: {
234
+ type: "object",
235
+ properties: { query: { type: "string" }, goal: { type: "string" }, context: { type: "string" } },
236
+ required: ["query", "goal", "context"],
237
+ },
238
+ },
239
+ },
240
+ ]
241
+
242
+ const conversationId = crypto.randomUUID() // once, when the conversation starts
243
+ const windowId = await windowAnchor(messages) // once, from the first message
244
+
245
+ const completion = await openai.chat.completions.create({ model: "gpt-4o", messages, tools })
246
+ for (const call of completion.choices[0].message.tool_calls ?? []) {
247
+ if (call.type !== "function") continue
248
+ const lineage = await buildMetadata({
249
+ harness: "my-app", // a stable name for your integration
250
+ conversationId,
251
+ windowId,
252
+ messageId: completion.id, // this model turn
253
+ toolCallId: call.id, // this tool call
254
+ history: messages, // [{ role, content }]: the conversation so far
255
+ ancestors: [], // the parent snapshot; [] for the first agent
256
+ })
257
+ const { query, goal, context } = JSON.parse(call.function.arguments)
258
+ const response = await telem.search(query, withTrajectory({ goal, context }, lineage))
259
+ }
260
+ ```
261
+
262
+ `withTrajectory` attaches the lineage data to one call. Use it the same way with
263
+ `telem.fetch`. When lineage data is present, the client ignores a `session` id.
264
+
265
+ When an agent delegates a task, it makes a **snapshot** of itself with
266
+ `buildSnapshot`. The snapshot is a record of the parent at that moment. The subagent
267
+ carries the snapshot in its own `ancestors`. Subagents that start in the same turn
268
+ share the snapshot, and the console shows them side by side under the parent:
269
+
270
+ ```ts
271
+
272
+ const parent = await buildSnapshot({
273
+ harness: "my-app",
274
+ conversationId,
275
+ windowId,
276
+ messageId: completion.id, // the turn that delegates
277
+ context: messages, // the conversation at that moment
278
+ ancestors: [],
279
+ })
280
+ // in the subagent: ancestors: [parent]
281
+ ```
282
+
283
+ **Without lineage data**, pass the `sessionId` from the response back as `session`
284
+ on each later call. The console then shows the calls together, but not which turn
285
+ made each one. Make the first call alone. Until its response returns, there is no
286
+ id to share, and two calls that start together end up in two separate sessions.
287
+
288
+ ## Errors
289
+
290
+ The client throws exactly two error classes. Branch on `status` and `code`. Do not
291
+ branch on the message text:
292
+
293
+ ```ts
294
+
295
+ try {
296
+ await telem.search("climate policy 2026")
297
+ } catch (error) {
298
+ if (error instanceof TimeoutError) {
299
+ // error.code === "timeout": one attempt took longer than timeoutMs
300
+ } else if (error instanceof TelemError) {
301
+ error.status // the HTTP status, or undefined when nothing was sent
302
+ error.code // "invalid_request" | "unsupported_server_version" | "connection_error", or a server code
303
+ error.details // the parsed response body, or the raw text
304
+ }
305
+ }
306
+ ```
307
+
308
+ | Situation | Result |
309
+ |---|---|
310
+ | Bad input (empty query, empty URL list) | `TelemError`, `code: "invalid_request"`, nothing sent |
311
+ | Network failure | `TelemError`, `code: "connection_error"`, after the retries |
312
+ | 5xx or 429 | Retried with backoff (`Retry-After` applies), then `TelemError` with the status |
313
+ | Other 4xx | `TelemError` with the status and the code from the server, not retried |
314
+ | Attempt longer than `timeoutMs` | `TimeoutError`, not retried |
315
+
316
+ See [Resources → Errors](https://docs.telem.ai/resources/errors/) for how the plugins show a failed call.
317
+
318
+ ## Embedding and edge runtimes
319
+
320
+ The client has no HTTP dependency, and it accepts your own `fetch`. This is how it
321
+ runs inside another platform, in an edge worker, and in tests without a network:
322
+
323
+ ```ts
324
+ const telem = new Telem({
325
+ apiKey: env.TELEM_API_KEY,
326
+ fetch: (input, init) => myFetch(input, init), // a worker, a proxy, a recording stub
327
+ })
328
+ ```
329
+
330
+ ## License
331
+
332
+ Apache-2.0. See [LICENSE](LICENSE).