@agents24/embed-sdk 1.0.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Talmudpedia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,203 @@
1
+ # `@agents24/embed-sdk`
2
+
3
+ Last Updated: 2026-03-17
4
+
5
+ `@agents24/embed-sdk` is the canonical server-only TypeScript SDK for Talmudpedia embedded-agent runtime.
6
+
7
+ Use it when a customer already has its own application and wants its backend to call a published Talmudpedia agent directly through the embed API.
8
+
9
+ ## Product Split
10
+
11
+ This package is not the published-app runtime SDK.
12
+
13
+ - `@talmudpedia/runtime-sdk`: browser/client SDK for published-app runtime
14
+ - `@agents24/embed-sdk`: Node/server SDK for embedded-agent runtime
15
+
16
+ ## Supported Runtime
17
+
18
+ V1 is server-only.
19
+
20
+ - Node `>=18.17`
21
+ - ESM and CommonJS package exports
22
+ - built on top of native `fetch` and Web Streams
23
+
24
+ Do not use this package in browser bundles. Keep your Talmudpedia tenant API key only on your backend.
25
+
26
+ ## Installation
27
+
28
+ After the first public npm release is cut:
29
+
30
+ ```bash
31
+ npm install @agents24/embed-sdk
32
+ ```
33
+
34
+ Until that release exists, validate the package from this repo with `npm pack` or `npm run smoke:pack`.
35
+
36
+ ## Required Environment Variables
37
+
38
+ - `TALMUDPEDIA_BASE_URL`
39
+ - `TALMUDPEDIA_EMBED_API_KEY`
40
+ - published `agent_id`
41
+
42
+ The API key must have the `agents.embed` scope.
43
+
44
+ ## Quickstart
45
+
46
+ ```ts
47
+ import { EmbeddedAgentClient } from "@agents24/embed-sdk";
48
+
49
+ const client = new EmbeddedAgentClient({
50
+ baseUrl: process.env.TALMUDPEDIA_BASE_URL!,
51
+ apiKey: process.env.TALMUDPEDIA_EMBED_API_KEY!,
52
+ });
53
+
54
+ const result = await client.streamAgent(
55
+ process.env.TALMUDPEDIA_AGENT_ID!,
56
+ {
57
+ input: "Summarize today’s thread.",
58
+ external_user_id: "customer-user-123",
59
+ },
60
+ (event) => {
61
+ console.log(event.event, event.payload);
62
+ },
63
+ );
64
+
65
+ console.log(result.threadId);
66
+ ```
67
+
68
+ ## Architecture
69
+
70
+ Supported v1 architecture:
71
+
72
+ - customer frontend
73
+ - customer backend
74
+ - `@agents24/embed-sdk`
75
+ - Talmudpedia embed API
76
+ - published agent
77
+
78
+ The frontend talks only to the customer backend. The backend talks to Talmudpedia.
79
+
80
+ ## API Reference
81
+
82
+ ### `new EmbeddedAgentClient(options)`
83
+
84
+ ```ts
85
+ const client = new EmbeddedAgentClient({
86
+ baseUrl: "https://api.talmudpedia.example",
87
+ apiKey: "tpk_live_xxx",
88
+ });
89
+ ```
90
+
91
+ Options:
92
+
93
+ - `baseUrl`: base platform URL, for example `https://api.example.com`
94
+ - `apiKey`: tenant API key with `agents.embed`
95
+ - `fetchImpl`: optional custom fetch implementation for tests or custom runtimes
96
+
97
+ ### `streamAgent(agentId, payload, onEvent?)`
98
+
99
+ Wraps:
100
+
101
+ - `POST /public/embed/agents/{agent_id}/chat/stream`
102
+
103
+ Payload keeps backend field names exactly:
104
+
105
+ ```ts
106
+ type EmbeddedAgentStreamRequest = {
107
+ input?: string;
108
+ messages?: Array<Record<string, unknown>>;
109
+ thread_id?: string;
110
+ external_user_id: string;
111
+ external_session_id?: string;
112
+ metadata?: Record<string, unknown>;
113
+ client?: Record<string, unknown>;
114
+ };
115
+ ```
116
+
117
+ Returns:
118
+
119
+ ```ts
120
+ type StreamAgentResult = {
121
+ threadId: string | null;
122
+ };
123
+ ```
124
+
125
+ `onEvent` receives typed `run-stream.v2` envelopes.
126
+
127
+ ### `listAgentThreads(agentId, options)`
128
+
129
+ Wraps:
130
+
131
+ - `GET /public/embed/agents/{agent_id}/threads`
132
+
133
+ Options:
134
+
135
+ - `externalUserId`
136
+ - `externalSessionId?`
137
+ - `skip?`
138
+ - `limit?`
139
+
140
+ ### `getAgentThread(agentId, threadId, options)`
141
+
142
+ Wraps:
143
+
144
+ - `GET /public/embed/agents/{agent_id}/threads/{thread_id}`
145
+
146
+ Options:
147
+
148
+ - `externalUserId`
149
+ - `externalSessionId?`
150
+
151
+ ## Thread And History Usage
152
+
153
+ Pass your own application user identity as `external_user_id` on every call.
154
+
155
+ - `external_user_id` is required
156
+ - `external_session_id` is optional
157
+ - `threadId` returned from `streamAgent(...)` should be persisted by your backend and reused for resume/history
158
+
159
+ Example:
160
+
161
+ ```ts
162
+ const threads = await client.listAgentThreads(agentId, {
163
+ externalUserId: "customer-user-123",
164
+ });
165
+
166
+ const thread = await client.getAgentThread(agentId, "thread-id", {
167
+ externalUserId: "customer-user-123",
168
+ });
169
+ ```
170
+
171
+ ## Error Handling
172
+
173
+ The SDK throws `EmbeddedAgentSDKError` with:
174
+
175
+ - `kind: "http" | "network" | "protocol"`
176
+ - `status` for HTTP failures
177
+ - `details` when the response body includes structured error information
178
+
179
+ ```ts
180
+ import { EmbeddedAgentSDKError } from "@agents24/embed-sdk";
181
+
182
+ try {
183
+ await client.listAgentThreads(agentId, { externalUserId: "customer-user-123" });
184
+ } catch (error) {
185
+ if (error instanceof EmbeddedAgentSDKError) {
186
+ console.error(error.kind, error.status, error.details);
187
+ }
188
+ }
189
+ ```
190
+
191
+ ## Server-Only Warning
192
+
193
+ - Do not put the Talmudpedia API key in frontend code
194
+ - Do not store the API key in localStorage, cookies, or public env vars
195
+ - Do not call the embed API directly from the browser
196
+
197
+ ## Example App
198
+
199
+ See [`examples/express-typescript/`](./examples/express-typescript/) for a minimal customer-backend integration example.
200
+
201
+ ## Release Notes
202
+
203
+ This package is released through GitHub Actions using release-please and npm trusted publishing. Local `npm pack` and `npm run smoke:pack` are the expected pre-release verification commands.
package/dist/index.cjs ADDED
@@ -0,0 +1,348 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var EmbeddedAgentSDKError = class extends Error {
5
+ kind;
6
+ status;
7
+ details;
8
+ constructor(message, options) {
9
+ super(message, "cause" in Error.prototype ? { cause: options.cause } : void 0);
10
+ this.name = "EmbeddedAgentSDKError";
11
+ this.kind = options.kind;
12
+ this.status = options.status;
13
+ this.details = options.details;
14
+ if (!("cause" in this) && options.cause !== void 0) {
15
+ Object.defineProperty(this, "cause", {
16
+ configurable: true,
17
+ enumerable: false,
18
+ value: options.cause,
19
+ writable: true
20
+ });
21
+ }
22
+ }
23
+ };
24
+
25
+ // src/http.ts
26
+ var SERVER_ONLY_MESSAGE = "EmbeddedAgentClient is server-only. Keep your Talmudpedia API key on your backend and call the SDK from Node.";
27
+ function assertServerRuntime() {
28
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
29
+ throw new EmbeddedAgentSDKError(SERVER_ONLY_MESSAGE, { kind: "protocol" });
30
+ }
31
+ }
32
+ function normalizeBaseUrl(baseUrl) {
33
+ const normalized = String(baseUrl || "").trim().replace(/\/+$/, "");
34
+ if (!normalized) {
35
+ throw new EmbeddedAgentSDKError("EmbeddedAgentClient requires a non-empty baseUrl.", {
36
+ kind: "protocol"
37
+ });
38
+ }
39
+ try {
40
+ return new URL(normalized).toString().replace(/\/+$/, "");
41
+ } catch (cause) {
42
+ throw new EmbeddedAgentSDKError("EmbeddedAgentClient received an invalid baseUrl.", {
43
+ kind: "protocol",
44
+ cause,
45
+ details: { baseUrl }
46
+ });
47
+ }
48
+ }
49
+ function resolveFetchImpl(fetchImpl) {
50
+ if (fetchImpl) {
51
+ return fetchImpl;
52
+ }
53
+ if (typeof fetch === "function") {
54
+ return fetch;
55
+ }
56
+ throw new EmbeddedAgentSDKError(
57
+ "No fetch implementation is available. Use Node 18.17+ or pass fetchImpl explicitly.",
58
+ { kind: "protocol" }
59
+ );
60
+ }
61
+ function buildStreamHeaders(apiKey) {
62
+ return {
63
+ Authorization: `Bearer ${apiKey}`,
64
+ Accept: "text/event-stream",
65
+ "Content-Type": "application/json"
66
+ };
67
+ }
68
+ function buildJsonHeaders(apiKey) {
69
+ return {
70
+ Authorization: `Bearer ${apiKey}`,
71
+ Accept: "application/json"
72
+ };
73
+ }
74
+ function extractMessageFromDetails(details) {
75
+ if (!details || typeof details !== "object" || Array.isArray(details)) {
76
+ return void 0;
77
+ }
78
+ const detail = details.detail;
79
+ return typeof detail === "string" && detail.trim() ? detail.trim() : void 0;
80
+ }
81
+ async function parseErrorDetails(response) {
82
+ if (typeof response.text === "function") {
83
+ try {
84
+ const raw = await response.text();
85
+ if (!raw) {
86
+ return null;
87
+ }
88
+ try {
89
+ return JSON.parse(raw);
90
+ } catch {
91
+ return raw;
92
+ }
93
+ } catch {
94
+ return null;
95
+ }
96
+ }
97
+ if (typeof response.json === "function") {
98
+ try {
99
+ return await response.json();
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+ return null;
105
+ }
106
+ async function assertOk(response) {
107
+ if (response.ok) {
108
+ return;
109
+ }
110
+ const details = await parseErrorDetails(response);
111
+ const message = extractMessageFromDetails(details) || typeof details === "string" && details.trim() || response.statusText || "Request failed";
112
+ throw new EmbeddedAgentSDKError(message, {
113
+ kind: "http",
114
+ status: response.status,
115
+ details
116
+ });
117
+ }
118
+ function wrapNetworkError(message, cause) {
119
+ if (cause instanceof EmbeddedAgentSDKError) {
120
+ return cause;
121
+ }
122
+ return new EmbeddedAgentSDKError(message, {
123
+ kind: "network",
124
+ cause,
125
+ details: cause instanceof Error ? { name: cause.name } : void 0
126
+ });
127
+ }
128
+
129
+ // src/sse.ts
130
+ function parseSSEBlock(block) {
131
+ const dataLines = [];
132
+ const lines = block.split("\n");
133
+ for (const line of lines) {
134
+ if (!line || line.startsWith(":")) {
135
+ continue;
136
+ }
137
+ const separatorIndex = line.indexOf(":");
138
+ const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);
139
+ let value = separatorIndex === -1 ? "" : line.slice(separatorIndex + 1);
140
+ if (value.startsWith(" ")) {
141
+ value = value.slice(1);
142
+ }
143
+ if (field === "data") {
144
+ dataLines.push(value);
145
+ }
146
+ }
147
+ if (dataLines.length === 0) {
148
+ return null;
149
+ }
150
+ return dataLines.join("\n");
151
+ }
152
+ function assertDiagnostics(value) {
153
+ if (!Array.isArray(value)) {
154
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: diagnostics must be an array.", {
155
+ kind: "protocol",
156
+ details: value
157
+ });
158
+ }
159
+ return value.map((item) => {
160
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
161
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: diagnostics entries must be objects.", {
162
+ kind: "protocol",
163
+ details: item
164
+ });
165
+ }
166
+ return item;
167
+ });
168
+ }
169
+ function assertPayload(value) {
170
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
171
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: payload must be an object.", {
172
+ kind: "protocol",
173
+ details: value
174
+ });
175
+ }
176
+ return value;
177
+ }
178
+ function parseRuntimeEvent(rawPayload) {
179
+ let parsed;
180
+ try {
181
+ parsed = JSON.parse(rawPayload);
182
+ } catch (cause) {
183
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: invalid JSON payload.", {
184
+ kind: "protocol",
185
+ cause,
186
+ details: rawPayload
187
+ });
188
+ }
189
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
190
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: expected an object envelope.", {
191
+ kind: "protocol",
192
+ details: parsed
193
+ });
194
+ }
195
+ const candidate = parsed;
196
+ if (candidate.version !== "run-stream.v2") {
197
+ throw new EmbeddedAgentSDKError(
198
+ "Embedded-agent SSE protocol mismatch: expected run-stream.v2 event envelopes.",
199
+ {
200
+ kind: "protocol",
201
+ details: candidate
202
+ }
203
+ );
204
+ }
205
+ if (typeof candidate.seq !== "number" || !Number.isFinite(candidate.seq) || typeof candidate.ts !== "string" || typeof candidate.event !== "string" || typeof candidate.run_id !== "string" || typeof candidate.stage !== "string") {
206
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: missing required envelope fields.", {
207
+ kind: "protocol",
208
+ details: candidate
209
+ });
210
+ }
211
+ return {
212
+ version: "run-stream.v2",
213
+ seq: candidate.seq,
214
+ ts: candidate.ts,
215
+ event: candidate.event,
216
+ run_id: candidate.run_id,
217
+ stage: candidate.stage,
218
+ payload: assertPayload(candidate.payload ?? {}),
219
+ diagnostics: assertDiagnostics(candidate.diagnostics ?? [])
220
+ };
221
+ }
222
+ async function consumeEventStream(response, onEvent) {
223
+ if (!response.body) {
224
+ throw new EmbeddedAgentSDKError("Embedded-agent stream response did not include a readable body.", {
225
+ kind: "protocol"
226
+ });
227
+ }
228
+ const reader = response.body.getReader();
229
+ const decoder = new TextDecoder();
230
+ let buffer = "";
231
+ while (true) {
232
+ const { done, value } = await reader.read();
233
+ buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
234
+ let separatorIndex = buffer.indexOf("\n\n");
235
+ while (separatorIndex !== -1) {
236
+ const block = buffer.slice(0, separatorIndex);
237
+ buffer = buffer.slice(separatorIndex + 2);
238
+ const payload = parseSSEBlock(block);
239
+ if (payload) {
240
+ const event = parseRuntimeEvent(payload);
241
+ if (onEvent) {
242
+ await onEvent(event);
243
+ }
244
+ }
245
+ separatorIndex = buffer.indexOf("\n\n");
246
+ }
247
+ if (done) {
248
+ break;
249
+ }
250
+ }
251
+ const trailingPayload = parseSSEBlock(buffer.trim());
252
+ if (trailingPayload) {
253
+ const event = parseRuntimeEvent(trailingPayload);
254
+ if (onEvent) {
255
+ await onEvent(event);
256
+ }
257
+ }
258
+ }
259
+
260
+ // src/client.ts
261
+ var EmbeddedAgentClient = class {
262
+ baseUrl;
263
+ apiKey;
264
+ fetchImpl;
265
+ constructor({ baseUrl, apiKey, fetchImpl }) {
266
+ assertServerRuntime();
267
+ const normalizedApiKey = String(apiKey || "").trim();
268
+ if (!normalizedApiKey) {
269
+ throw new EmbeddedAgentSDKError("EmbeddedAgentClient requires a non-empty apiKey.", {
270
+ kind: "protocol"
271
+ });
272
+ }
273
+ this.baseUrl = normalizeBaseUrl(baseUrl);
274
+ this.apiKey = normalizedApiKey;
275
+ this.fetchImpl = resolveFetchImpl(fetchImpl);
276
+ }
277
+ async streamAgent(agentId, payload, onEvent) {
278
+ const response = await this.fetchOrThrow(
279
+ `${this.baseUrl}/public/embed/agents/${agentId}/chat/stream`,
280
+ {
281
+ method: "POST",
282
+ headers: buildStreamHeaders(this.apiKey),
283
+ body: JSON.stringify(payload)
284
+ },
285
+ "Failed to connect to the embedded-agent stream endpoint."
286
+ );
287
+ await assertOk(response);
288
+ const threadId = response.headers.get("X-Thread-ID");
289
+ await consumeEventStream(response, onEvent);
290
+ return { threadId };
291
+ }
292
+ async listAgentThreads(agentId, {
293
+ externalUserId,
294
+ externalSessionId,
295
+ skip = 0,
296
+ limit = 20
297
+ }) {
298
+ const search = new URLSearchParams({
299
+ external_user_id: externalUserId,
300
+ skip: String(skip),
301
+ limit: String(limit)
302
+ });
303
+ if (externalSessionId) {
304
+ search.set("external_session_id", externalSessionId);
305
+ }
306
+ return this.requestJson(
307
+ `${this.baseUrl}/public/embed/agents/${agentId}/threads?${search.toString()}`
308
+ );
309
+ }
310
+ async getAgentThread(agentId, threadId, {
311
+ externalUserId,
312
+ externalSessionId
313
+ }) {
314
+ const search = new URLSearchParams({
315
+ external_user_id: externalUserId
316
+ });
317
+ if (externalSessionId) {
318
+ search.set("external_session_id", externalSessionId);
319
+ }
320
+ return this.requestJson(
321
+ `${this.baseUrl}/public/embed/agents/${agentId}/threads/${threadId}?${search.toString()}`
322
+ );
323
+ }
324
+ async requestJson(url) {
325
+ const response = await this.fetchOrThrow(
326
+ url,
327
+ {
328
+ method: "GET",
329
+ headers: buildJsonHeaders(this.apiKey)
330
+ },
331
+ "Failed to connect to the embedded-agent API."
332
+ );
333
+ await assertOk(response);
334
+ return await response.json();
335
+ }
336
+ async fetchOrThrow(url, init, networkMessage) {
337
+ try {
338
+ return await this.fetchImpl(url, init);
339
+ } catch (cause) {
340
+ throw wrapNetworkError(networkMessage, cause);
341
+ }
342
+ }
343
+ };
344
+
345
+ exports.EmbeddedAgentClient = EmbeddedAgentClient;
346
+ exports.EmbeddedAgentSDKError = EmbeddedAgentSDKError;
347
+ //# sourceMappingURL=index.cjs.map
348
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/sse.ts","../src/client.ts"],"names":[],"mappings":";;;AASO,IAAM,qBAAA,GAAN,cAAoC,KAAA,CAAM;AAAA,EAC/B,IAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AAAA,EAEhB,WAAA,CAAY,SAAiB,OAAA,EAAuC;AAClE,IAAA,KAAA,CAAM,OAAA,EAAS,WAAW,KAAA,CAAM,SAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,MAAS,CAAA;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AA,EAAmB,cAAA,EAA2C;AACpG,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAI,CAAA;AAAA,IACvC,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,gBAAA,CAAiB,gBAAgB,KAAK,CAAA;AAAA,IAC9C;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["export type EmbeddedAgentSDKErrorKind = \"http\" | \"network\" | \"protocol\";\n\ntype EmbeddedAgentSDKErrorOptions = {\n kind: EmbeddedAgentSDKErrorKind;\n status?: number;\n details?: unknown;\n cause?: unknown;\n};\n\nexport class EmbeddedAgentSDKError extends Error {\n public readonly kind: EmbeddedAgentSDKErrorKind;\n public readonly status?: number;\n public readonly details?: unknown;\n\n constructor(message: string, options: EmbeddedAgentSDKErrorOptions) {\n super(message, \"cause\" in Error.prototype ? { cause: options.cause } : undefined);\n this.name = \"EmbeddedAgentSDKError\";\n this.kind = options.kind;\n this.status = options.status;\n this.details = options.details;\n if (!(\"cause\" in this) && options.cause !== undefined) {\n Object.defineProperty(this, \"cause\", {\n configurable: true,\n enumerable: false,\n value: options.cause,\n writable: true,\n });\n }\n }\n}\n","import { EmbeddedAgentSDKError } from \"./errors\";\n\nconst SERVER_ONLY_MESSAGE =\n \"EmbeddedAgentClient is server-only. Keep your Talmudpedia API key on your backend and call the SDK from Node.\";\n\nexport function assertServerRuntime(): void {\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new EmbeddedAgentSDKError(SERVER_ONLY_MESSAGE, { kind: \"protocol\" });\n }\n}\n\nexport function normalizeBaseUrl(baseUrl: string): string {\n const normalized = String(baseUrl || \"\").trim().replace(/\\/+$/, \"\");\n if (!normalized) {\n throw new EmbeddedAgentSDKError(\"EmbeddedAgentClient requires a non-empty baseUrl.\", {\n kind: \"protocol\",\n });\n }\n try {\n return new URL(normalized).toString().replace(/\\/+$/, \"\");\n } catch (cause) {\n throw new EmbeddedAgentSDKError(\"EmbeddedAgentClient received an invalid baseUrl.\", {\n kind: \"protocol\",\n cause,\n details: { baseUrl },\n });\n }\n}\n\nexport function resolveFetchImpl(fetchImpl?: typeof fetch): typeof fetch {\n if (fetchImpl) {\n return fetchImpl;\n }\n if (typeof fetch === \"function\") {\n return fetch;\n }\n throw new EmbeddedAgentSDKError(\n \"No fetch implementation is available. Use Node 18.17+ or pass fetchImpl explicitly.\",\n { kind: \"protocol\" },\n );\n}\n\nexport function buildStreamHeaders(apiKey: string): HeadersInit {\n return {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"text/event-stream\",\n \"Content-Type\": \"application/json\",\n };\n}\n\nexport function buildJsonHeaders(apiKey: string): HeadersInit {\n return {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n };\n}\n\nfunction extractMessageFromDetails(details: unknown): string | undefined {\n if (!details || typeof details !== \"object\" || Array.isArray(details)) {\n return undefined;\n }\n const detail = (details as { detail?: unknown }).detail;\n return typeof detail === \"string\" && detail.trim() ? detail.trim() : undefined;\n}\n\nasync function parseErrorDetails(response: Response): Promise<unknown> {\n if (typeof response.text === \"function\") {\n try {\n const raw = await response.text();\n if (!raw) {\n return null;\n }\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return raw;\n }\n } catch {\n return null;\n }\n }\n if (typeof response.json === \"function\") {\n try {\n return await response.json();\n } catch {\n return null;\n }\n }\n return null;\n}\n\nexport async function assertOk(response: Response): Promise<void> {\n if (response.ok) {\n return;\n }\n const details = await parseErrorDetails(response);\n const message =\n extractMessageFromDetails(details) ||\n (typeof details === \"string\" && details.trim()) ||\n response.statusText ||\n \"Request failed\";\n throw new EmbeddedAgentSDKError(message, {\n kind: \"http\",\n status: response.status,\n details,\n });\n}\n\nexport function wrapNetworkError(message: string, cause: unknown): EmbeddedAgentSDKError {\n if (cause instanceof EmbeddedAgentSDKError) {\n return cause;\n }\n return new EmbeddedAgentSDKError(message, {\n kind: \"network\",\n cause,\n details: cause instanceof Error ? { name: cause.name } : undefined,\n });\n}\n","import { EmbeddedAgentSDKError } from \"./errors\";\nimport type { EmbeddedAgentRuntimeDiagnostic, EmbeddedAgentRuntimeEvent } from \"./types\";\n\nfunction parseSSEBlock(block: string): string | null {\n const dataLines: string[] = [];\n const lines = block.split(\"\\n\");\n for (const line of lines) {\n if (!line || line.startsWith(\":\")) {\n continue;\n }\n const separatorIndex = line.indexOf(\":\");\n const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);\n let value = separatorIndex === -1 ? \"\" : line.slice(separatorIndex + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n if (field === \"data\") {\n dataLines.push(value);\n }\n }\n if (dataLines.length === 0) {\n return null;\n }\n return dataLines.join(\"\\n\");\n}\n\nfunction assertDiagnostics(value: unknown): EmbeddedAgentRuntimeDiagnostic[] {\n if (!Array.isArray(value)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: diagnostics must be an array.\", {\n kind: \"protocol\",\n details: value,\n });\n }\n return value.map((item) => {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: diagnostics entries must be objects.\", {\n kind: \"protocol\",\n details: item,\n });\n }\n return item as EmbeddedAgentRuntimeDiagnostic;\n });\n}\n\nfunction assertPayload(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: payload must be an object.\", {\n kind: \"protocol\",\n details: value,\n });\n }\n return value as Record<string, unknown>;\n}\n\nexport function parseRuntimeEvent(rawPayload: string): EmbeddedAgentRuntimeEvent {\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawPayload) as unknown;\n } catch (cause) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: invalid JSON payload.\", {\n kind: \"protocol\",\n cause,\n details: rawPayload,\n });\n }\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: expected an object envelope.\", {\n kind: \"protocol\",\n details: parsed,\n });\n }\n\n const candidate = parsed as Record<string, unknown>;\n if (candidate.version !== \"run-stream.v2\") {\n throw new EmbeddedAgentSDKError(\n \"Embedded-agent SSE protocol mismatch: expected run-stream.v2 event envelopes.\",\n {\n kind: \"protocol\",\n details: candidate,\n },\n );\n }\n\n if (\n typeof candidate.seq !== \"number\" ||\n !Number.isFinite(candidate.seq) ||\n typeof candidate.ts !== \"string\" ||\n typeof candidate.event !== \"string\" ||\n typeof candidate.run_id !== \"string\" ||\n typeof candidate.stage !== \"string\"\n ) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: missing required envelope fields.\", {\n kind: \"protocol\",\n details: candidate,\n });\n }\n\n return {\n version: \"run-stream.v2\",\n seq: candidate.seq,\n ts: candidate.ts,\n event: candidate.event,\n run_id: candidate.run_id,\n stage: candidate.stage,\n payload: assertPayload(candidate.payload ?? {}),\n diagnostics: assertDiagnostics(candidate.diagnostics ?? []),\n };\n}\n\nexport async function consumeEventStream(\n response: Response,\n onEvent?: (event: EmbeddedAgentRuntimeEvent) => void | Promise<void>,\n): Promise<void> {\n if (!response.body) {\n throw new EmbeddedAgentSDKError(\"Embedded-agent stream response did not include a readable body.\", {\n kind: \"protocol\",\n });\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done }).replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\n let separatorIndex = buffer.indexOf(\"\\n\\n\");\n while (separatorIndex !== -1) {\n const block = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex + 2);\n const payload = parseSSEBlock(block);\n if (payload) {\n const event = parseRuntimeEvent(payload);\n if (onEvent) {\n await onEvent(event);\n }\n }\n separatorIndex = buffer.indexOf(\"\\n\\n\");\n }\n\n if (done) {\n break;\n }\n }\n\n const trailingPayload = parseSSEBlock(buffer.trim());\n if (trailingPayload) {\n const event = parseRuntimeEvent(trailingPayload);\n if (onEvent) {\n await onEvent(event);\n }\n }\n}\n","import { EmbeddedAgentSDKError } from \"./errors\";\nimport {\n assertOk,\n assertServerRuntime,\n buildJsonHeaders,\n buildStreamHeaders,\n normalizeBaseUrl,\n resolveFetchImpl,\n wrapNetworkError,\n} from \"./http\";\nimport { consumeEventStream } from \"./sse\";\nimport type {\n EmbeddedAgentClientOptions,\n EmbeddedAgentRuntimeEvent,\n EmbeddedAgentStreamRequest,\n EmbeddedAgentThreadDetail,\n EmbeddedAgentThreadDetailOptions,\n EmbeddedAgentThreadListOptions,\n EmbeddedAgentThreadsResponse,\n StreamAgentResult,\n} from \"./types\";\n\nexport class EmbeddedAgentClient {\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor({ baseUrl, apiKey, fetchImpl }: EmbeddedAgentClientOptions) {\n assertServerRuntime();\n const normalizedApiKey = String(apiKey || \"\").trim();\n if (!normalizedApiKey) {\n throw new EmbeddedAgentSDKError(\"EmbeddedAgentClient requires a non-empty apiKey.\", {\n kind: \"protocol\",\n });\n }\n this.baseUrl = normalizeBaseUrl(baseUrl);\n this.apiKey = normalizedApiKey;\n this.fetchImpl = resolveFetchImpl(fetchImpl);\n }\n\n async streamAgent(\n agentId: string,\n payload: EmbeddedAgentStreamRequest,\n onEvent?: (event: EmbeddedAgentRuntimeEvent) => void | Promise<void>,\n ): Promise<StreamAgentResult> {\n const response = await this.fetchOrThrow(\n `${this.baseUrl}/public/embed/agents/${agentId}/chat/stream`,\n {\n method: \"POST\",\n headers: buildStreamHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n \"Failed to connect to the embedded-agent stream endpoint.\",\n );\n\n await assertOk(response);\n const threadId = response.headers.get(\"X-Thread-ID\");\n await consumeEventStream(response, onEvent);\n return { threadId };\n }\n\n async listAgentThreads(\n agentId: string,\n {\n externalUserId,\n externalSessionId,\n skip = 0,\n limit = 20,\n }: EmbeddedAgentThreadListOptions,\n ): Promise<EmbeddedAgentThreadsResponse> {\n const search = new URLSearchParams({\n external_user_id: externalUserId,\n skip: String(skip),\n limit: String(limit),\n });\n if (externalSessionId) {\n search.set(\"external_session_id\", externalSessionId);\n }\n return this.requestJson<EmbeddedAgentThreadsResponse>(\n `${this.baseUrl}/public/embed/agents/${agentId}/threads?${search.toString()}`,\n );\n }\n\n async getAgentThread(\n agentId: string,\n threadId: string,\n {\n externalUserId,\n externalSessionId,\n }: EmbeddedAgentThreadDetailOptions,\n ): Promise<EmbeddedAgentThreadDetail> {\n const search = new URLSearchParams({\n external_user_id: externalUserId,\n });\n if (externalSessionId) {\n search.set(\"external_session_id\", externalSessionId);\n }\n return this.requestJson<EmbeddedAgentThreadDetail>(\n `${this.baseUrl}/public/embed/agents/${agentId}/threads/${threadId}?${search.toString()}`,\n );\n }\n\n private async requestJson<T>(url: string): Promise<T> {\n const response = await this.fetchOrThrow(\n url,\n {\n method: \"GET\",\n headers: buildJsonHeaders(this.apiKey),\n },\n \"Failed to connect to the embedded-agent API.\",\n );\n await assertOk(response);\n return (await response.json()) as T;\n }\n\n private async fetchOrThrow(url: string, init: RequestInit, networkMessage: string): Promise<Response> {\n try {\n return await this.fetchImpl(url, init);\n } catch (cause) {\n throw wrapNetworkError(networkMessage, cause);\n }\n }\n}\n"]}
@@ -0,0 +1,106 @@
1
+ type EmbeddedAgentSDKErrorKind = "http" | "network" | "protocol";
2
+ type EmbeddedAgentSDKErrorOptions = {
3
+ kind: EmbeddedAgentSDKErrorKind;
4
+ status?: number;
5
+ details?: unknown;
6
+ cause?: unknown;
7
+ };
8
+ declare class EmbeddedAgentSDKError extends Error {
9
+ readonly kind: EmbeddedAgentSDKErrorKind;
10
+ readonly status?: number;
11
+ readonly details?: unknown;
12
+ constructor(message: string, options: EmbeddedAgentSDKErrorOptions);
13
+ }
14
+
15
+ type EmbeddedAgentStreamRequest = {
16
+ input?: string;
17
+ messages?: Array<Record<string, unknown>>;
18
+ thread_id?: string;
19
+ external_user_id: string;
20
+ external_session_id?: string;
21
+ metadata?: Record<string, unknown>;
22
+ client?: Record<string, unknown>;
23
+ };
24
+ type EmbeddedAgentThreadSummary = {
25
+ id: string;
26
+ agent_id: string | null;
27
+ external_user_id: string | null;
28
+ external_session_id: string | null;
29
+ title: string | null;
30
+ status: string;
31
+ surface: string;
32
+ last_run_id: string | null;
33
+ last_activity_at: string | null;
34
+ created_at: string;
35
+ updated_at: string;
36
+ };
37
+ type EmbeddedAgentThreadTurn = {
38
+ id: string;
39
+ run_id: string;
40
+ turn_index: number;
41
+ user_input_text: string | null;
42
+ assistant_output_text: string | null;
43
+ status: string;
44
+ usage_tokens: number;
45
+ metadata: Record<string, unknown>;
46
+ created_at: string;
47
+ completed_at: string | null;
48
+ };
49
+ type EmbeddedAgentThreadDetail = EmbeddedAgentThreadSummary & {
50
+ turns: EmbeddedAgentThreadTurn[];
51
+ };
52
+ type EmbeddedAgentThreadsResponse = {
53
+ items: EmbeddedAgentThreadSummary[];
54
+ total: number;
55
+ };
56
+ type EmbeddedAgentRuntimeDiagnostic = {
57
+ message?: string;
58
+ } & Record<string, unknown>;
59
+ type EmbeddedAgentRuntimeEvent = {
60
+ version: "run-stream.v2";
61
+ seq: number;
62
+ ts: string;
63
+ event: string;
64
+ run_id: string;
65
+ stage: string;
66
+ payload: Record<string, unknown>;
67
+ diagnostics: EmbeddedAgentRuntimeDiagnostic[];
68
+ };
69
+ type StreamAgentResult = {
70
+ threadId: string | null;
71
+ };
72
+ type EmbeddedAgentThreadListOptions = {
73
+ externalUserId: string;
74
+ externalSessionId?: string;
75
+ skip?: number;
76
+ limit?: number;
77
+ };
78
+ type EmbeddedAgentThreadDetailOptions = {
79
+ externalUserId: string;
80
+ externalSessionId?: string;
81
+ };
82
+ type EmbeddedAgentClientOptions = {
83
+ baseUrl: string;
84
+ apiKey: string;
85
+ fetchImpl?: typeof fetch;
86
+ };
87
+ type EmbeddedAgentSDKSerializedError = {
88
+ message: string;
89
+ kind: EmbeddedAgentSDKErrorKind;
90
+ status?: number;
91
+ details?: unknown;
92
+ };
93
+
94
+ declare class EmbeddedAgentClient {
95
+ private readonly baseUrl;
96
+ private readonly apiKey;
97
+ private readonly fetchImpl;
98
+ constructor({ baseUrl, apiKey, fetchImpl }: EmbeddedAgentClientOptions);
99
+ streamAgent(agentId: string, payload: EmbeddedAgentStreamRequest, onEvent?: (event: EmbeddedAgentRuntimeEvent) => void | Promise<void>): Promise<StreamAgentResult>;
100
+ listAgentThreads(agentId: string, { externalUserId, externalSessionId, skip, limit, }: EmbeddedAgentThreadListOptions): Promise<EmbeddedAgentThreadsResponse>;
101
+ getAgentThread(agentId: string, threadId: string, { externalUserId, externalSessionId, }: EmbeddedAgentThreadDetailOptions): Promise<EmbeddedAgentThreadDetail>;
102
+ private requestJson;
103
+ private fetchOrThrow;
104
+ }
105
+
106
+ export { EmbeddedAgentClient, type EmbeddedAgentClientOptions, type EmbeddedAgentRuntimeDiagnostic, type EmbeddedAgentRuntimeEvent, EmbeddedAgentSDKError, type EmbeddedAgentSDKErrorKind, type EmbeddedAgentSDKSerializedError, type EmbeddedAgentStreamRequest, type EmbeddedAgentThreadDetail, type EmbeddedAgentThreadDetailOptions, type EmbeddedAgentThreadListOptions, type EmbeddedAgentThreadSummary, type EmbeddedAgentThreadTurn, type EmbeddedAgentThreadsResponse, type StreamAgentResult };
@@ -0,0 +1,106 @@
1
+ type EmbeddedAgentSDKErrorKind = "http" | "network" | "protocol";
2
+ type EmbeddedAgentSDKErrorOptions = {
3
+ kind: EmbeddedAgentSDKErrorKind;
4
+ status?: number;
5
+ details?: unknown;
6
+ cause?: unknown;
7
+ };
8
+ declare class EmbeddedAgentSDKError extends Error {
9
+ readonly kind: EmbeddedAgentSDKErrorKind;
10
+ readonly status?: number;
11
+ readonly details?: unknown;
12
+ constructor(message: string, options: EmbeddedAgentSDKErrorOptions);
13
+ }
14
+
15
+ type EmbeddedAgentStreamRequest = {
16
+ input?: string;
17
+ messages?: Array<Record<string, unknown>>;
18
+ thread_id?: string;
19
+ external_user_id: string;
20
+ external_session_id?: string;
21
+ metadata?: Record<string, unknown>;
22
+ client?: Record<string, unknown>;
23
+ };
24
+ type EmbeddedAgentThreadSummary = {
25
+ id: string;
26
+ agent_id: string | null;
27
+ external_user_id: string | null;
28
+ external_session_id: string | null;
29
+ title: string | null;
30
+ status: string;
31
+ surface: string;
32
+ last_run_id: string | null;
33
+ last_activity_at: string | null;
34
+ created_at: string;
35
+ updated_at: string;
36
+ };
37
+ type EmbeddedAgentThreadTurn = {
38
+ id: string;
39
+ run_id: string;
40
+ turn_index: number;
41
+ user_input_text: string | null;
42
+ assistant_output_text: string | null;
43
+ status: string;
44
+ usage_tokens: number;
45
+ metadata: Record<string, unknown>;
46
+ created_at: string;
47
+ completed_at: string | null;
48
+ };
49
+ type EmbeddedAgentThreadDetail = EmbeddedAgentThreadSummary & {
50
+ turns: EmbeddedAgentThreadTurn[];
51
+ };
52
+ type EmbeddedAgentThreadsResponse = {
53
+ items: EmbeddedAgentThreadSummary[];
54
+ total: number;
55
+ };
56
+ type EmbeddedAgentRuntimeDiagnostic = {
57
+ message?: string;
58
+ } & Record<string, unknown>;
59
+ type EmbeddedAgentRuntimeEvent = {
60
+ version: "run-stream.v2";
61
+ seq: number;
62
+ ts: string;
63
+ event: string;
64
+ run_id: string;
65
+ stage: string;
66
+ payload: Record<string, unknown>;
67
+ diagnostics: EmbeddedAgentRuntimeDiagnostic[];
68
+ };
69
+ type StreamAgentResult = {
70
+ threadId: string | null;
71
+ };
72
+ type EmbeddedAgentThreadListOptions = {
73
+ externalUserId: string;
74
+ externalSessionId?: string;
75
+ skip?: number;
76
+ limit?: number;
77
+ };
78
+ type EmbeddedAgentThreadDetailOptions = {
79
+ externalUserId: string;
80
+ externalSessionId?: string;
81
+ };
82
+ type EmbeddedAgentClientOptions = {
83
+ baseUrl: string;
84
+ apiKey: string;
85
+ fetchImpl?: typeof fetch;
86
+ };
87
+ type EmbeddedAgentSDKSerializedError = {
88
+ message: string;
89
+ kind: EmbeddedAgentSDKErrorKind;
90
+ status?: number;
91
+ details?: unknown;
92
+ };
93
+
94
+ declare class EmbeddedAgentClient {
95
+ private readonly baseUrl;
96
+ private readonly apiKey;
97
+ private readonly fetchImpl;
98
+ constructor({ baseUrl, apiKey, fetchImpl }: EmbeddedAgentClientOptions);
99
+ streamAgent(agentId: string, payload: EmbeddedAgentStreamRequest, onEvent?: (event: EmbeddedAgentRuntimeEvent) => void | Promise<void>): Promise<StreamAgentResult>;
100
+ listAgentThreads(agentId: string, { externalUserId, externalSessionId, skip, limit, }: EmbeddedAgentThreadListOptions): Promise<EmbeddedAgentThreadsResponse>;
101
+ getAgentThread(agentId: string, threadId: string, { externalUserId, externalSessionId, }: EmbeddedAgentThreadDetailOptions): Promise<EmbeddedAgentThreadDetail>;
102
+ private requestJson;
103
+ private fetchOrThrow;
104
+ }
105
+
106
+ export { EmbeddedAgentClient, type EmbeddedAgentClientOptions, type EmbeddedAgentRuntimeDiagnostic, type EmbeddedAgentRuntimeEvent, EmbeddedAgentSDKError, type EmbeddedAgentSDKErrorKind, type EmbeddedAgentSDKSerializedError, type EmbeddedAgentStreamRequest, type EmbeddedAgentThreadDetail, type EmbeddedAgentThreadDetailOptions, type EmbeddedAgentThreadListOptions, type EmbeddedAgentThreadSummary, type EmbeddedAgentThreadTurn, type EmbeddedAgentThreadsResponse, type StreamAgentResult };
package/dist/index.js ADDED
@@ -0,0 +1,345 @@
1
+ // src/errors.ts
2
+ var EmbeddedAgentSDKError = class extends Error {
3
+ kind;
4
+ status;
5
+ details;
6
+ constructor(message, options) {
7
+ super(message, "cause" in Error.prototype ? { cause: options.cause } : void 0);
8
+ this.name = "EmbeddedAgentSDKError";
9
+ this.kind = options.kind;
10
+ this.status = options.status;
11
+ this.details = options.details;
12
+ if (!("cause" in this) && options.cause !== void 0) {
13
+ Object.defineProperty(this, "cause", {
14
+ configurable: true,
15
+ enumerable: false,
16
+ value: options.cause,
17
+ writable: true
18
+ });
19
+ }
20
+ }
21
+ };
22
+
23
+ // src/http.ts
24
+ var SERVER_ONLY_MESSAGE = "EmbeddedAgentClient is server-only. Keep your Talmudpedia API key on your backend and call the SDK from Node.";
25
+ function assertServerRuntime() {
26
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
27
+ throw new EmbeddedAgentSDKError(SERVER_ONLY_MESSAGE, { kind: "protocol" });
28
+ }
29
+ }
30
+ function normalizeBaseUrl(baseUrl) {
31
+ const normalized = String(baseUrl || "").trim().replace(/\/+$/, "");
32
+ if (!normalized) {
33
+ throw new EmbeddedAgentSDKError("EmbeddedAgentClient requires a non-empty baseUrl.", {
34
+ kind: "protocol"
35
+ });
36
+ }
37
+ try {
38
+ return new URL(normalized).toString().replace(/\/+$/, "");
39
+ } catch (cause) {
40
+ throw new EmbeddedAgentSDKError("EmbeddedAgentClient received an invalid baseUrl.", {
41
+ kind: "protocol",
42
+ cause,
43
+ details: { baseUrl }
44
+ });
45
+ }
46
+ }
47
+ function resolveFetchImpl(fetchImpl) {
48
+ if (fetchImpl) {
49
+ return fetchImpl;
50
+ }
51
+ if (typeof fetch === "function") {
52
+ return fetch;
53
+ }
54
+ throw new EmbeddedAgentSDKError(
55
+ "No fetch implementation is available. Use Node 18.17+ or pass fetchImpl explicitly.",
56
+ { kind: "protocol" }
57
+ );
58
+ }
59
+ function buildStreamHeaders(apiKey) {
60
+ return {
61
+ Authorization: `Bearer ${apiKey}`,
62
+ Accept: "text/event-stream",
63
+ "Content-Type": "application/json"
64
+ };
65
+ }
66
+ function buildJsonHeaders(apiKey) {
67
+ return {
68
+ Authorization: `Bearer ${apiKey}`,
69
+ Accept: "application/json"
70
+ };
71
+ }
72
+ function extractMessageFromDetails(details) {
73
+ if (!details || typeof details !== "object" || Array.isArray(details)) {
74
+ return void 0;
75
+ }
76
+ const detail = details.detail;
77
+ return typeof detail === "string" && detail.trim() ? detail.trim() : void 0;
78
+ }
79
+ async function parseErrorDetails(response) {
80
+ if (typeof response.text === "function") {
81
+ try {
82
+ const raw = await response.text();
83
+ if (!raw) {
84
+ return null;
85
+ }
86
+ try {
87
+ return JSON.parse(raw);
88
+ } catch {
89
+ return raw;
90
+ }
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ if (typeof response.json === "function") {
96
+ try {
97
+ return await response.json();
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+ async function assertOk(response) {
105
+ if (response.ok) {
106
+ return;
107
+ }
108
+ const details = await parseErrorDetails(response);
109
+ const message = extractMessageFromDetails(details) || typeof details === "string" && details.trim() || response.statusText || "Request failed";
110
+ throw new EmbeddedAgentSDKError(message, {
111
+ kind: "http",
112
+ status: response.status,
113
+ details
114
+ });
115
+ }
116
+ function wrapNetworkError(message, cause) {
117
+ if (cause instanceof EmbeddedAgentSDKError) {
118
+ return cause;
119
+ }
120
+ return new EmbeddedAgentSDKError(message, {
121
+ kind: "network",
122
+ cause,
123
+ details: cause instanceof Error ? { name: cause.name } : void 0
124
+ });
125
+ }
126
+
127
+ // src/sse.ts
128
+ function parseSSEBlock(block) {
129
+ const dataLines = [];
130
+ const lines = block.split("\n");
131
+ for (const line of lines) {
132
+ if (!line || line.startsWith(":")) {
133
+ continue;
134
+ }
135
+ const separatorIndex = line.indexOf(":");
136
+ const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);
137
+ let value = separatorIndex === -1 ? "" : line.slice(separatorIndex + 1);
138
+ if (value.startsWith(" ")) {
139
+ value = value.slice(1);
140
+ }
141
+ if (field === "data") {
142
+ dataLines.push(value);
143
+ }
144
+ }
145
+ if (dataLines.length === 0) {
146
+ return null;
147
+ }
148
+ return dataLines.join("\n");
149
+ }
150
+ function assertDiagnostics(value) {
151
+ if (!Array.isArray(value)) {
152
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: diagnostics must be an array.", {
153
+ kind: "protocol",
154
+ details: value
155
+ });
156
+ }
157
+ return value.map((item) => {
158
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
159
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: diagnostics entries must be objects.", {
160
+ kind: "protocol",
161
+ details: item
162
+ });
163
+ }
164
+ return item;
165
+ });
166
+ }
167
+ function assertPayload(value) {
168
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
169
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: payload must be an object.", {
170
+ kind: "protocol",
171
+ details: value
172
+ });
173
+ }
174
+ return value;
175
+ }
176
+ function parseRuntimeEvent(rawPayload) {
177
+ let parsed;
178
+ try {
179
+ parsed = JSON.parse(rawPayload);
180
+ } catch (cause) {
181
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: invalid JSON payload.", {
182
+ kind: "protocol",
183
+ cause,
184
+ details: rawPayload
185
+ });
186
+ }
187
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
188
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: expected an object envelope.", {
189
+ kind: "protocol",
190
+ details: parsed
191
+ });
192
+ }
193
+ const candidate = parsed;
194
+ if (candidate.version !== "run-stream.v2") {
195
+ throw new EmbeddedAgentSDKError(
196
+ "Embedded-agent SSE protocol mismatch: expected run-stream.v2 event envelopes.",
197
+ {
198
+ kind: "protocol",
199
+ details: candidate
200
+ }
201
+ );
202
+ }
203
+ if (typeof candidate.seq !== "number" || !Number.isFinite(candidate.seq) || typeof candidate.ts !== "string" || typeof candidate.event !== "string" || typeof candidate.run_id !== "string" || typeof candidate.stage !== "string") {
204
+ throw new EmbeddedAgentSDKError("Malformed embedded-agent SSE event: missing required envelope fields.", {
205
+ kind: "protocol",
206
+ details: candidate
207
+ });
208
+ }
209
+ return {
210
+ version: "run-stream.v2",
211
+ seq: candidate.seq,
212
+ ts: candidate.ts,
213
+ event: candidate.event,
214
+ run_id: candidate.run_id,
215
+ stage: candidate.stage,
216
+ payload: assertPayload(candidate.payload ?? {}),
217
+ diagnostics: assertDiagnostics(candidate.diagnostics ?? [])
218
+ };
219
+ }
220
+ async function consumeEventStream(response, onEvent) {
221
+ if (!response.body) {
222
+ throw new EmbeddedAgentSDKError("Embedded-agent stream response did not include a readable body.", {
223
+ kind: "protocol"
224
+ });
225
+ }
226
+ const reader = response.body.getReader();
227
+ const decoder = new TextDecoder();
228
+ let buffer = "";
229
+ while (true) {
230
+ const { done, value } = await reader.read();
231
+ buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
232
+ let separatorIndex = buffer.indexOf("\n\n");
233
+ while (separatorIndex !== -1) {
234
+ const block = buffer.slice(0, separatorIndex);
235
+ buffer = buffer.slice(separatorIndex + 2);
236
+ const payload = parseSSEBlock(block);
237
+ if (payload) {
238
+ const event = parseRuntimeEvent(payload);
239
+ if (onEvent) {
240
+ await onEvent(event);
241
+ }
242
+ }
243
+ separatorIndex = buffer.indexOf("\n\n");
244
+ }
245
+ if (done) {
246
+ break;
247
+ }
248
+ }
249
+ const trailingPayload = parseSSEBlock(buffer.trim());
250
+ if (trailingPayload) {
251
+ const event = parseRuntimeEvent(trailingPayload);
252
+ if (onEvent) {
253
+ await onEvent(event);
254
+ }
255
+ }
256
+ }
257
+
258
+ // src/client.ts
259
+ var EmbeddedAgentClient = class {
260
+ baseUrl;
261
+ apiKey;
262
+ fetchImpl;
263
+ constructor({ baseUrl, apiKey, fetchImpl }) {
264
+ assertServerRuntime();
265
+ const normalizedApiKey = String(apiKey || "").trim();
266
+ if (!normalizedApiKey) {
267
+ throw new EmbeddedAgentSDKError("EmbeddedAgentClient requires a non-empty apiKey.", {
268
+ kind: "protocol"
269
+ });
270
+ }
271
+ this.baseUrl = normalizeBaseUrl(baseUrl);
272
+ this.apiKey = normalizedApiKey;
273
+ this.fetchImpl = resolveFetchImpl(fetchImpl);
274
+ }
275
+ async streamAgent(agentId, payload, onEvent) {
276
+ const response = await this.fetchOrThrow(
277
+ `${this.baseUrl}/public/embed/agents/${agentId}/chat/stream`,
278
+ {
279
+ method: "POST",
280
+ headers: buildStreamHeaders(this.apiKey),
281
+ body: JSON.stringify(payload)
282
+ },
283
+ "Failed to connect to the embedded-agent stream endpoint."
284
+ );
285
+ await assertOk(response);
286
+ const threadId = response.headers.get("X-Thread-ID");
287
+ await consumeEventStream(response, onEvent);
288
+ return { threadId };
289
+ }
290
+ async listAgentThreads(agentId, {
291
+ externalUserId,
292
+ externalSessionId,
293
+ skip = 0,
294
+ limit = 20
295
+ }) {
296
+ const search = new URLSearchParams({
297
+ external_user_id: externalUserId,
298
+ skip: String(skip),
299
+ limit: String(limit)
300
+ });
301
+ if (externalSessionId) {
302
+ search.set("external_session_id", externalSessionId);
303
+ }
304
+ return this.requestJson(
305
+ `${this.baseUrl}/public/embed/agents/${agentId}/threads?${search.toString()}`
306
+ );
307
+ }
308
+ async getAgentThread(agentId, threadId, {
309
+ externalUserId,
310
+ externalSessionId
311
+ }) {
312
+ const search = new URLSearchParams({
313
+ external_user_id: externalUserId
314
+ });
315
+ if (externalSessionId) {
316
+ search.set("external_session_id", externalSessionId);
317
+ }
318
+ return this.requestJson(
319
+ `${this.baseUrl}/public/embed/agents/${agentId}/threads/${threadId}?${search.toString()}`
320
+ );
321
+ }
322
+ async requestJson(url) {
323
+ const response = await this.fetchOrThrow(
324
+ url,
325
+ {
326
+ method: "GET",
327
+ headers: buildJsonHeaders(this.apiKey)
328
+ },
329
+ "Failed to connect to the embedded-agent API."
330
+ );
331
+ await assertOk(response);
332
+ return await response.json();
333
+ }
334
+ async fetchOrThrow(url, init, networkMessage) {
335
+ try {
336
+ return await this.fetchImpl(url, init);
337
+ } catch (cause) {
338
+ throw wrapNetworkError(networkMessage, cause);
339
+ }
340
+ }
341
+ };
342
+
343
+ export { EmbeddedAgentClient, EmbeddedAgentSDKError };
344
+ //# sourceMappingURL=index.js.map
345
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
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B;AACpD,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,YAAA;AAAA,MAC1B,GAAA;AAAA,MACA;AAAA,QACE,MAAA,EAAQ,KAAA;AAAA,QACR,OAAA,EAAS,gBAAA,CAAiB,IAAA,CAAK,MAAM;AAAA,OACvC;AAAA,MACA;AAAA,KACF;AACA,IAAA,MAAM,SAAS,QAAQ,CAAA;AACvB,IAAA,OAAQ,MAAM,SAAS,IAAA,EAAK;AAAA,EAC9B;AAAA,EAEA,MAAc,YAAA,CAAa,GAAA,EAAa,IAAA,EAAmB,cAAA,EAA2C;AACpG,IAAA,IAAI;AACF,MAAA,OAAO,MAAM,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAI,CAAA;AAAA,IACvC,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,gBAAA,CAAiB,gBAAgB,KAAK,CAAA;AAAA,IAC9C;AAAA,EACF;AACF","file":"index.js","sourcesContent":["export type EmbeddedAgentSDKErrorKind = \"http\" | \"network\" | \"protocol\";\n\ntype EmbeddedAgentSDKErrorOptions = {\n kind: EmbeddedAgentSDKErrorKind;\n status?: number;\n details?: unknown;\n cause?: unknown;\n};\n\nexport class EmbeddedAgentSDKError extends Error {\n public readonly kind: EmbeddedAgentSDKErrorKind;\n public readonly status?: number;\n public readonly details?: unknown;\n\n constructor(message: string, options: EmbeddedAgentSDKErrorOptions) {\n super(message, \"cause\" in Error.prototype ? { cause: options.cause } : undefined);\n this.name = \"EmbeddedAgentSDKError\";\n this.kind = options.kind;\n this.status = options.status;\n this.details = options.details;\n if (!(\"cause\" in this) && options.cause !== undefined) {\n Object.defineProperty(this, \"cause\", {\n configurable: true,\n enumerable: false,\n value: options.cause,\n writable: true,\n });\n }\n }\n}\n","import { EmbeddedAgentSDKError } from \"./errors\";\n\nconst SERVER_ONLY_MESSAGE =\n \"EmbeddedAgentClient is server-only. Keep your Talmudpedia API key on your backend and call the SDK from Node.\";\n\nexport function assertServerRuntime(): void {\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") {\n throw new EmbeddedAgentSDKError(SERVER_ONLY_MESSAGE, { kind: \"protocol\" });\n }\n}\n\nexport function normalizeBaseUrl(baseUrl: string): string {\n const normalized = String(baseUrl || \"\").trim().replace(/\\/+$/, \"\");\n if (!normalized) {\n throw new EmbeddedAgentSDKError(\"EmbeddedAgentClient requires a non-empty baseUrl.\", {\n kind: \"protocol\",\n });\n }\n try {\n return new URL(normalized).toString().replace(/\\/+$/, \"\");\n } catch (cause) {\n throw new EmbeddedAgentSDKError(\"EmbeddedAgentClient received an invalid baseUrl.\", {\n kind: \"protocol\",\n cause,\n details: { baseUrl },\n });\n }\n}\n\nexport function resolveFetchImpl(fetchImpl?: typeof fetch): typeof fetch {\n if (fetchImpl) {\n return fetchImpl;\n }\n if (typeof fetch === \"function\") {\n return fetch;\n }\n throw new EmbeddedAgentSDKError(\n \"No fetch implementation is available. Use Node 18.17+ or pass fetchImpl explicitly.\",\n { kind: \"protocol\" },\n );\n}\n\nexport function buildStreamHeaders(apiKey: string): HeadersInit {\n return {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"text/event-stream\",\n \"Content-Type\": \"application/json\",\n };\n}\n\nexport function buildJsonHeaders(apiKey: string): HeadersInit {\n return {\n Authorization: `Bearer ${apiKey}`,\n Accept: \"application/json\",\n };\n}\n\nfunction extractMessageFromDetails(details: unknown): string | undefined {\n if (!details || typeof details !== \"object\" || Array.isArray(details)) {\n return undefined;\n }\n const detail = (details as { detail?: unknown }).detail;\n return typeof detail === \"string\" && detail.trim() ? detail.trim() : undefined;\n}\n\nasync function parseErrorDetails(response: Response): Promise<unknown> {\n if (typeof response.text === \"function\") {\n try {\n const raw = await response.text();\n if (!raw) {\n return null;\n }\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return raw;\n }\n } catch {\n return null;\n }\n }\n if (typeof response.json === \"function\") {\n try {\n return await response.json();\n } catch {\n return null;\n }\n }\n return null;\n}\n\nexport async function assertOk(response: Response): Promise<void> {\n if (response.ok) {\n return;\n }\n const details = await parseErrorDetails(response);\n const message =\n extractMessageFromDetails(details) ||\n (typeof details === \"string\" && details.trim()) ||\n response.statusText ||\n \"Request failed\";\n throw new EmbeddedAgentSDKError(message, {\n kind: \"http\",\n status: response.status,\n details,\n });\n}\n\nexport function wrapNetworkError(message: string, cause: unknown): EmbeddedAgentSDKError {\n if (cause instanceof EmbeddedAgentSDKError) {\n return cause;\n }\n return new EmbeddedAgentSDKError(message, {\n kind: \"network\",\n cause,\n details: cause instanceof Error ? { name: cause.name } : undefined,\n });\n}\n","import { EmbeddedAgentSDKError } from \"./errors\";\nimport type { EmbeddedAgentRuntimeDiagnostic, EmbeddedAgentRuntimeEvent } from \"./types\";\n\nfunction parseSSEBlock(block: string): string | null {\n const dataLines: string[] = [];\n const lines = block.split(\"\\n\");\n for (const line of lines) {\n if (!line || line.startsWith(\":\")) {\n continue;\n }\n const separatorIndex = line.indexOf(\":\");\n const field = separatorIndex === -1 ? line : line.slice(0, separatorIndex);\n let value = separatorIndex === -1 ? \"\" : line.slice(separatorIndex + 1);\n if (value.startsWith(\" \")) {\n value = value.slice(1);\n }\n if (field === \"data\") {\n dataLines.push(value);\n }\n }\n if (dataLines.length === 0) {\n return null;\n }\n return dataLines.join(\"\\n\");\n}\n\nfunction assertDiagnostics(value: unknown): EmbeddedAgentRuntimeDiagnostic[] {\n if (!Array.isArray(value)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: diagnostics must be an array.\", {\n kind: \"protocol\",\n details: value,\n });\n }\n return value.map((item) => {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: diagnostics entries must be objects.\", {\n kind: \"protocol\",\n details: item,\n });\n }\n return item as EmbeddedAgentRuntimeDiagnostic;\n });\n}\n\nfunction assertPayload(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: payload must be an object.\", {\n kind: \"protocol\",\n details: value,\n });\n }\n return value as Record<string, unknown>;\n}\n\nexport function parseRuntimeEvent(rawPayload: string): EmbeddedAgentRuntimeEvent {\n let parsed: unknown;\n try {\n parsed = JSON.parse(rawPayload) as unknown;\n } catch (cause) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: invalid JSON payload.\", {\n kind: \"protocol\",\n cause,\n details: rawPayload,\n });\n }\n\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: expected an object envelope.\", {\n kind: \"protocol\",\n details: parsed,\n });\n }\n\n const candidate = parsed as Record<string, unknown>;\n if (candidate.version !== \"run-stream.v2\") {\n throw new EmbeddedAgentSDKError(\n \"Embedded-agent SSE protocol mismatch: expected run-stream.v2 event envelopes.\",\n {\n kind: \"protocol\",\n details: candidate,\n },\n );\n }\n\n if (\n typeof candidate.seq !== \"number\" ||\n !Number.isFinite(candidate.seq) ||\n typeof candidate.ts !== \"string\" ||\n typeof candidate.event !== \"string\" ||\n typeof candidate.run_id !== \"string\" ||\n typeof candidate.stage !== \"string\"\n ) {\n throw new EmbeddedAgentSDKError(\"Malformed embedded-agent SSE event: missing required envelope fields.\", {\n kind: \"protocol\",\n details: candidate,\n });\n }\n\n return {\n version: \"run-stream.v2\",\n seq: candidate.seq,\n ts: candidate.ts,\n event: candidate.event,\n run_id: candidate.run_id,\n stage: candidate.stage,\n payload: assertPayload(candidate.payload ?? {}),\n diagnostics: assertDiagnostics(candidate.diagnostics ?? []),\n };\n}\n\nexport async function consumeEventStream(\n response: Response,\n onEvent?: (event: EmbeddedAgentRuntimeEvent) => void | Promise<void>,\n): Promise<void> {\n if (!response.body) {\n throw new EmbeddedAgentSDKError(\"Embedded-agent stream response did not include a readable body.\", {\n kind: \"protocol\",\n });\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (true) {\n const { done, value } = await reader.read();\n buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done }).replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\n let separatorIndex = buffer.indexOf(\"\\n\\n\");\n while (separatorIndex !== -1) {\n const block = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex + 2);\n const payload = parseSSEBlock(block);\n if (payload) {\n const event = parseRuntimeEvent(payload);\n if (onEvent) {\n await onEvent(event);\n }\n }\n separatorIndex = buffer.indexOf(\"\\n\\n\");\n }\n\n if (done) {\n break;\n }\n }\n\n const trailingPayload = parseSSEBlock(buffer.trim());\n if (trailingPayload) {\n const event = parseRuntimeEvent(trailingPayload);\n if (onEvent) {\n await onEvent(event);\n }\n }\n}\n","import { EmbeddedAgentSDKError } from \"./errors\";\nimport {\n assertOk,\n assertServerRuntime,\n buildJsonHeaders,\n buildStreamHeaders,\n normalizeBaseUrl,\n resolveFetchImpl,\n wrapNetworkError,\n} from \"./http\";\nimport { consumeEventStream } from \"./sse\";\nimport type {\n EmbeddedAgentClientOptions,\n EmbeddedAgentRuntimeEvent,\n EmbeddedAgentStreamRequest,\n EmbeddedAgentThreadDetail,\n EmbeddedAgentThreadDetailOptions,\n EmbeddedAgentThreadListOptions,\n EmbeddedAgentThreadsResponse,\n StreamAgentResult,\n} from \"./types\";\n\nexport class EmbeddedAgentClient {\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor({ baseUrl, apiKey, fetchImpl }: EmbeddedAgentClientOptions) {\n assertServerRuntime();\n const normalizedApiKey = String(apiKey || \"\").trim();\n if (!normalizedApiKey) {\n throw new EmbeddedAgentSDKError(\"EmbeddedAgentClient requires a non-empty apiKey.\", {\n kind: \"protocol\",\n });\n }\n this.baseUrl = normalizeBaseUrl(baseUrl);\n this.apiKey = normalizedApiKey;\n this.fetchImpl = resolveFetchImpl(fetchImpl);\n }\n\n async streamAgent(\n agentId: string,\n payload: EmbeddedAgentStreamRequest,\n onEvent?: (event: EmbeddedAgentRuntimeEvent) => void | Promise<void>,\n ): Promise<StreamAgentResult> {\n const response = await this.fetchOrThrow(\n `${this.baseUrl}/public/embed/agents/${agentId}/chat/stream`,\n {\n method: \"POST\",\n headers: buildStreamHeaders(this.apiKey),\n body: JSON.stringify(payload),\n },\n \"Failed to connect to the embedded-agent stream endpoint.\",\n );\n\n await assertOk(response);\n const threadId = response.headers.get(\"X-Thread-ID\");\n await consumeEventStream(response, onEvent);\n return { threadId };\n }\n\n async listAgentThreads(\n agentId: string,\n {\n externalUserId,\n externalSessionId,\n skip = 0,\n limit = 20,\n }: EmbeddedAgentThreadListOptions,\n ): Promise<EmbeddedAgentThreadsResponse> {\n const search = new URLSearchParams({\n external_user_id: externalUserId,\n skip: String(skip),\n limit: String(limit),\n });\n if (externalSessionId) {\n search.set(\"external_session_id\", externalSessionId);\n }\n return this.requestJson<EmbeddedAgentThreadsResponse>(\n `${this.baseUrl}/public/embed/agents/${agentId}/threads?${search.toString()}`,\n );\n }\n\n async getAgentThread(\n agentId: string,\n threadId: string,\n {\n externalUserId,\n externalSessionId,\n }: EmbeddedAgentThreadDetailOptions,\n ): Promise<EmbeddedAgentThreadDetail> {\n const search = new URLSearchParams({\n external_user_id: externalUserId,\n });\n if (externalSessionId) {\n search.set(\"external_session_id\", externalSessionId);\n }\n return this.requestJson<EmbeddedAgentThreadDetail>(\n `${this.baseUrl}/public/embed/agents/${agentId}/threads/${threadId}?${search.toString()}`,\n );\n }\n\n private async requestJson<T>(url: string): Promise<T> {\n const response = await this.fetchOrThrow(\n url,\n {\n method: \"GET\",\n headers: buildJsonHeaders(this.apiKey),\n },\n \"Failed to connect to the embedded-agent API.\",\n );\n await assertOk(response);\n return (await response.json()) as T;\n }\n\n private async fetchOrThrow(url: string, init: RequestInit, networkMessage: string): Promise<Response> {\n try {\n return await this.fetchImpl(url, init);\n } catch (cause) {\n throw wrapNetworkError(networkMessage, cause);\n }\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@agents24/embed-sdk",
3
+ "version": "1.0.0",
4
+ "private": false,
5
+ "description": "Server-only TypeScript SDK for Talmudpedia embedded-agent runtime.",
6
+ "keywords": [
7
+ "talmudpedia",
8
+ "agent",
9
+ "embed",
10
+ "sdk",
11
+ "sse",
12
+ "node"
13
+ ],
14
+ "author": "Talmudpedia",
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/daniel5426/talmudpedia.git",
19
+ "directory": "packages/embed-sdk"
20
+ },
21
+ "homepage": "https://github.com/daniel5426/talmudpedia/tree/main/packages/embed-sdk",
22
+ "bugs": {
23
+ "url": "https://github.com/daniel5426/talmudpedia/issues"
24
+ },
25
+ "type": "module",
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "require": "./dist/index.cjs",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "sideEffects": false,
43
+ "engines": {
44
+ "node": ">=18.17"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "provenance": true
49
+ },
50
+ "scripts": {
51
+ "clean": "rm -rf dist",
52
+ "build": "tsup",
53
+ "prepack": "npm run build",
54
+ "smoke:pack": "node ./scripts/smoke-pack.mjs"
55
+ },
56
+ "devDependencies": {
57
+ "@types/node": "^24.7.2",
58
+ "tsup": "^8.5.0",
59
+ "typescript": "^5.9.3"
60
+ }
61
+ }