antarya 0.0.0-stage → 0.1.1

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 Humblepaper, Inc.
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 CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # antarya
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript SDK for the Antarya API. Documentation: https://antarya.ai/docs/sdk/typescript
package/dist/index.cjs ADDED
@@ -0,0 +1,543 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ APIConnectionError: () => APIConnectionError,
24
+ APIError: () => APIError,
25
+ APITimeoutError: () => APITimeoutError,
26
+ ARTIFACT_KINDS: () => ARTIFACT_KINDS,
27
+ Antarya: () => Antarya,
28
+ AuthenticationError: () => AuthenticationError,
29
+ BadRequestError: () => BadRequestError,
30
+ ChatStream: () => ChatStream,
31
+ InternalServerError: () => InternalServerError,
32
+ NotFoundError: () => NotFoundError,
33
+ OverloadedError: () => OverloadedError,
34
+ PermissionDeniedError: () => PermissionDeniedError,
35
+ RateLimitError: () => RateLimitError,
36
+ RequestTooLargeError: () => RequestTooLargeError,
37
+ default: () => index_default,
38
+ errorFrom: () => errorFrom
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+
42
+ // src/errors.ts
43
+ var APIError = class extends Error {
44
+ status;
45
+ type;
46
+ requestId;
47
+ retryAfter;
48
+ constructor(message, init = {}) {
49
+ super(message);
50
+ this.name = new.target.name;
51
+ this.status = init.status;
52
+ this.type = init.type ?? "api_error";
53
+ this.requestId = init.requestId;
54
+ this.retryAfter = init.retryAfter;
55
+ }
56
+ };
57
+ var BadRequestError = class extends APIError {
58
+ };
59
+ var AuthenticationError = class extends APIError {
60
+ };
61
+ var PermissionDeniedError = class extends APIError {
62
+ };
63
+ var NotFoundError = class extends APIError {
64
+ };
65
+ var RequestTooLargeError = class extends APIError {
66
+ };
67
+ var RateLimitError = class extends APIError {
68
+ };
69
+ var InternalServerError = class extends APIError {
70
+ };
71
+ var OverloadedError = class extends APIError {
72
+ };
73
+ var APIConnectionError = class extends APIError {
74
+ constructor(message = "Could not reach the API.", init = {}) {
75
+ super(message, { type: "connection_error" });
76
+ if (init.cause !== void 0) this.cause = init.cause;
77
+ }
78
+ };
79
+ var APITimeoutError = class extends APIConnectionError {
80
+ constructor(message = "The request timed out.") {
81
+ super(message);
82
+ }
83
+ };
84
+ var BY_TYPE = {
85
+ invalid_request: BadRequestError,
86
+ authentication_error: AuthenticationError,
87
+ permission_error: PermissionDeniedError,
88
+ not_found: NotFoundError,
89
+ request_too_large: RequestTooLargeError,
90
+ rate_limit_error: RateLimitError,
91
+ api_error: InternalServerError,
92
+ overloaded: OverloadedError
93
+ };
94
+ var BY_STATUS = {
95
+ 400: "invalid_request",
96
+ 401: "authentication_error",
97
+ 403: "permission_error",
98
+ 404: "not_found",
99
+ 413: "request_too_large",
100
+ 429: "rate_limit_error",
101
+ 503: "overloaded"
102
+ };
103
+ function errorFrom(status, body, headers) {
104
+ const err = body && typeof body === "object" ? body.error : void 0;
105
+ const bodyId = body && typeof body === "object" ? body.request_id : void 0;
106
+ const type = typeof err?.type === "string" && err.type in BY_TYPE ? err.type : BY_STATUS[status] ?? "api_error";
107
+ const message = typeof err?.message === "string" && err.message ? err.message : `The API returned an error (${status}).`;
108
+ const requestId = typeof bodyId === "string" ? bodyId : headers.get("request-id") ?? void 0;
109
+ const ra = Number(headers.get("retry-after"));
110
+ const retryAfter = headers.get("retry-after") !== null && Number.isFinite(ra) && ra >= 0 ? ra : void 0;
111
+ return new BY_TYPE[type](message, { status, type, requestId, retryAfter });
112
+ }
113
+
114
+ // src/streaming.ts
115
+ async function* readLines(res, onReader) {
116
+ if (!res.body) return;
117
+ const reader = res.body.getReader();
118
+ onReader?.(reader);
119
+ const dec = new TextDecoder();
120
+ let buf = "";
121
+ try {
122
+ for (; ; ) {
123
+ const { done, value } = await reader.read();
124
+ if (done) break;
125
+ buf += dec.decode(value, { stream: true });
126
+ let m;
127
+ while (m = /\r\n|\n|\r/.exec(buf)) {
128
+ if (m[0] === "\r" && m.index === buf.length - 1) break;
129
+ yield buf.slice(0, m.index);
130
+ buf = buf.slice(m.index + m[0].length);
131
+ }
132
+ }
133
+ buf += dec.decode();
134
+ if (buf) yield buf;
135
+ } finally {
136
+ await reader.cancel().catch(() => {
137
+ });
138
+ }
139
+ }
140
+ var ChatStream = class {
141
+ /** onClose runs once, when the stream ends, fails, is left early or is stopped. */
142
+ constructor(res, controller, onClose) {
143
+ this.res = res;
144
+ this.controller = controller;
145
+ this.onClose = onClose;
146
+ this.requestId = res.headers.get("request-id") ?? void 0;
147
+ this.events = this.run();
148
+ }
149
+ res;
150
+ controller;
151
+ onClose;
152
+ requestId;
153
+ aborted = false;
154
+ reader;
155
+ events;
156
+ id = "";
157
+ model = "";
158
+ parts = [];
159
+ done;
160
+ [Symbol.asyncIterator]() {
161
+ return this.events;
162
+ }
163
+ /** Stops the stream. Iteration ends without an error. */
164
+ abort() {
165
+ this.aborted = true;
166
+ this.controller?.abort();
167
+ void this.reader?.cancel().catch(() => {
168
+ });
169
+ this.close();
170
+ }
171
+ close() {
172
+ const f = this.onClose;
173
+ this.onClose = void 0;
174
+ f?.();
175
+ }
176
+ /** Reads the rest of the stream and returns the assembled reply. */
177
+ async finalReply() {
178
+ for await (const _ of this.events) {
179
+ }
180
+ if (!this.done) throw new APIConnectionError(this.aborted ? "The stream was stopped." : "The stream ended before the reply was complete.");
181
+ return { id: this.id, model: this.model, content: this.parts.filter(Boolean), ...this.done };
182
+ }
183
+ async *run() {
184
+ let name = "";
185
+ let data = [];
186
+ try {
187
+ for await (const line of readLines(this.res, (r) => {
188
+ this.reader = r;
189
+ if (this.aborted) void r.cancel().catch(() => {
190
+ });
191
+ })) {
192
+ if (line === "") {
193
+ if (data.length) {
194
+ const ev = this.shape(name || "message", data.join("\n"));
195
+ name = "";
196
+ data = [];
197
+ if (ev) {
198
+ yield ev;
199
+ if (ev.type === "reply.done") return;
200
+ }
201
+ } else name = "";
202
+ continue;
203
+ }
204
+ if (line.startsWith(":")) continue;
205
+ const i = line.indexOf(":");
206
+ const field = i < 0 ? line : line.slice(0, i);
207
+ let val = i < 0 ? "" : line.slice(i + 1);
208
+ if (val.startsWith(" ")) val = val.slice(1);
209
+ if (field === "event") name = val;
210
+ else if (field === "data") data.push(val);
211
+ }
212
+ } catch (e) {
213
+ if (this.aborted) return;
214
+ if (e instanceof APIError) throw e;
215
+ throw new APIConnectionError("The stream was cut off.", { cause: e });
216
+ } finally {
217
+ this.close();
218
+ }
219
+ if (this.aborted) return;
220
+ if (!this.done) throw new APIConnectionError("The stream ended before the reply was complete.");
221
+ }
222
+ shape(name, raw) {
223
+ let d;
224
+ try {
225
+ d = JSON.parse(raw);
226
+ } catch {
227
+ return void 0;
228
+ }
229
+ if (!d || typeof d !== "object") return void 0;
230
+ switch (name) {
231
+ case "reply.start":
232
+ this.id = String(d.id ?? "");
233
+ this.model = String(d.model ?? "");
234
+ return { ...d, type: "reply.start" };
235
+ case "content.delta": {
236
+ const { index, ...part } = d;
237
+ const ev = { type: "content.delta", index, part };
238
+ if (part.type === "text" && typeof part.text === "string") {
239
+ ev.text = part.text;
240
+ const cur = this.parts[index];
241
+ if (cur && cur.type === "text") cur.text += part.text;
242
+ else this.parts[index] = { type: "text", text: part.text };
243
+ } else this.parts[index] = part;
244
+ return ev;
245
+ }
246
+ case "reply.done":
247
+ this.done = { stop_reason: d.stop_reason, usage: d.usage };
248
+ return { ...d, type: "reply.done" };
249
+ case "error": {
250
+ const err = errorFrom(this.res.status, "error" in d ? d : { error: d }, this.res.headers);
251
+ err.status = void 0;
252
+ throw err;
253
+ }
254
+ default:
255
+ return { ...d, type: name };
256
+ }
257
+ }
258
+ };
259
+
260
+ // src/resources/batches.ts
261
+ var Batches = class {
262
+ constructor(client) {
263
+ this.client = client;
264
+ }
265
+ client;
266
+ async create(p, opts = {}) {
267
+ return await this.client.request("POST", "/batches", { body: p, signal: opts.signal });
268
+ }
269
+ async get(id, opts = {}) {
270
+ return await this.client.request("GET", `/batches/${encodeURIComponent(id)}`, { signal: opts.signal });
271
+ }
272
+ async cancel(id, opts = {}) {
273
+ return await this.client.request("POST", `/batches/${encodeURIComponent(id)}/cancel`, { signal: opts.signal });
274
+ }
275
+ /** The finished results, one parsed line at a time. */
276
+ async *results(id, opts = {}) {
277
+ const res = await this.client.request("GET", `/batches/${encodeURIComponent(id)}/results`, { stream: true, signal: opts.signal });
278
+ for await (const line of readLines(res)) {
279
+ if (line.trim()) yield JSON.parse(line);
280
+ }
281
+ }
282
+ };
283
+
284
+ // src/resources/chat.ts
285
+ var Chat = class {
286
+ constructor(client) {
287
+ this.client = client;
288
+ }
289
+ client;
290
+ async create(p, opts = {}) {
291
+ if (p.stream) return this.stream(p, opts);
292
+ return await this.client.request("POST", "/chat", { body: p, signal: opts.signal });
293
+ }
294
+ /** Starts a streamed reply. Call `abort()` on the result to stop it. */
295
+ async stream(p, opts = {}) {
296
+ const ctl = new AbortController();
297
+ const link = () => ctl.abort();
298
+ const unlink = () => opts.signal?.removeEventListener("abort", link);
299
+ if (opts.signal?.aborted) ctl.abort();
300
+ else opts.signal?.addEventListener("abort", link, { once: true });
301
+ try {
302
+ const res = await this.client.request("POST", "/chat", { body: { ...p, stream: true }, stream: true, signal: ctl.signal });
303
+ return new ChatStream(res, ctl, unlink);
304
+ } catch (e) {
305
+ unlink();
306
+ ctl.abort();
307
+ throw e;
308
+ }
309
+ }
310
+ async countTokens(p, opts = {}) {
311
+ return await this.client.request("POST", "/count-tokens", { body: p, signal: opts.signal });
312
+ }
313
+ };
314
+
315
+ // src/resources/files.ts
316
+ var isPathStream = (f) => !!f && typeof f === "object" && typeof f.path === "string" && Symbol.asyncIterator in f;
317
+ var baseName = (p) => p.split(/[\\/]/).filter(Boolean).pop() ?? "file";
318
+ var Files = class {
319
+ constructor(client) {
320
+ this.client = client;
321
+ }
322
+ client;
323
+ async create(p, opts = {}) {
324
+ const f = p.file;
325
+ let blob;
326
+ let name = p.filename;
327
+ if (f instanceof Blob) {
328
+ blob = f;
329
+ name ??= f.name;
330
+ } else if (f instanceof ArrayBuffer) blob = new Blob([f]);
331
+ else if (f instanceof Uint8Array) blob = new Blob([f]);
332
+ else if (isPathStream(f)) {
333
+ const chunks = [];
334
+ for await (const c of f) chunks.push(typeof c === "string" ? c : c);
335
+ blob = new Blob(chunks);
336
+ name ??= baseName(f.path);
337
+ } else throw new TypeError("file must be a Blob, File, Uint8Array, ArrayBuffer or ReadStream.");
338
+ if (p.media_type) blob = new Blob([blob], { type: p.media_type });
339
+ const form = new FormData();
340
+ form.append("file", blob, name ?? "file");
341
+ return await this.client.request("POST", "/files", { form, signal: opts.signal });
342
+ }
343
+ async list(opts = {}) {
344
+ return await this.client.request("GET", "/files", { signal: opts.signal });
345
+ }
346
+ async get(id, opts = {}) {
347
+ return await this.client.request("GET", `/files/${encodeURIComponent(id)}`, { signal: opts.signal });
348
+ }
349
+ async delete(id, opts = {}) {
350
+ return this.client.request("DELETE", `/files/${encodeURIComponent(id)}`, { signal: opts.signal });
351
+ }
352
+ };
353
+
354
+ // src/resources/models.ts
355
+ var Models = class {
356
+ constructor(client) {
357
+ this.client = client;
358
+ }
359
+ client;
360
+ async list(opts = {}) {
361
+ return await this.client.request("GET", "/models", { signal: opts.signal });
362
+ }
363
+ async get(id, opts = {}) {
364
+ return await this.client.request("GET", `/models/${encodeURIComponent(id)}`, { signal: opts.signal });
365
+ }
366
+ };
367
+
368
+ // src/resources/sessions.ts
369
+ var Sessions = class {
370
+ constructor(client) {
371
+ this.client = client;
372
+ }
373
+ client;
374
+ async create(p = {}, opts = {}) {
375
+ return await this.client.request("POST", "/sessions", { body: p, signal: opts.signal });
376
+ }
377
+ async list(opts = {}) {
378
+ return await this.client.request("GET", "/sessions", { signal: opts.signal });
379
+ }
380
+ async get(id, opts = {}) {
381
+ return await this.client.request("GET", `/sessions/${encodeURIComponent(id)}`, { signal: opts.signal });
382
+ }
383
+ async delete(id, opts = {}) {
384
+ return this.client.request("DELETE", `/sessions/${encodeURIComponent(id)}`, { signal: opts.signal });
385
+ }
386
+ };
387
+
388
+ // src/client.ts
389
+ var DEFAULT_BASE_URL = "https://antarya.ai/v1";
390
+ var RETRY_STATUS = /* @__PURE__ */ new Set([429, 500, 503]);
391
+ var MAX_RETRY_AFTER_S = 60;
392
+ var realSleep = (ms, signal) => new Promise((resolve) => {
393
+ if (signal?.aborted) return resolve();
394
+ const done = () => {
395
+ clearTimeout(t);
396
+ signal?.removeEventListener("abort", done);
397
+ resolve();
398
+ };
399
+ const t = setTimeout(done, ms);
400
+ signal?.addEventListener("abort", done, { once: true });
401
+ });
402
+ var Antarya = class {
403
+ static APIError = APIError;
404
+ static BadRequestError = BadRequestError;
405
+ static AuthenticationError = AuthenticationError;
406
+ static PermissionDeniedError = PermissionDeniedError;
407
+ static NotFoundError = NotFoundError;
408
+ static RequestTooLargeError = RequestTooLargeError;
409
+ static RateLimitError = RateLimitError;
410
+ static InternalServerError = InternalServerError;
411
+ static OverloadedError = OverloadedError;
412
+ static APIConnectionError = APIConnectionError;
413
+ static APITimeoutError = APITimeoutError;
414
+ #apiKey;
415
+ baseURL;
416
+ maxRetries;
417
+ timeout;
418
+ chat = new Chat(this);
419
+ models = new Models(this);
420
+ files = new Files(this);
421
+ batches = new Batches(this);
422
+ sessions = new Sessions(this);
423
+ fetchFn;
424
+ sleep;
425
+ constructor(opts = {}) {
426
+ const env = globalThis.process?.env;
427
+ this.#apiKey = opts.apiKey ?? env?.ANTARYA_API_KEY;
428
+ this.baseURL = (opts.baseURL ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
429
+ this.maxRetries = opts.maxRetries ?? 2;
430
+ this.timeout = opts.timeout ?? 6e5;
431
+ this.sleep = opts.sleep ?? realSleep;
432
+ this.fetchFn = opts.fetch ?? ((...a) => globalThis.fetch(...a));
433
+ }
434
+ /** The key in use. A getter, so it is not listed by JSON.stringify or console.log. */
435
+ get apiKey() {
436
+ return this.#apiKey;
437
+ }
438
+ /** Keeps the key and the circular resource links out of JSON.stringify. */
439
+ toJSON() {
440
+ return { baseURL: this.baseURL };
441
+ }
442
+ async request(method, path, opts = {}) {
443
+ const useAuth = opts.auth !== false;
444
+ if (useAuth && !this.#apiKey) throw new AuthenticationError("No API key. Set ANTARYA_API_KEY or pass apiKey.", { type: "authentication_error" });
445
+ const headers = {};
446
+ if (useAuth) headers.authorization = `Bearer ${this.#apiKey}`;
447
+ let body;
448
+ if (opts.form) body = opts.form;
449
+ else if (opts.body !== void 0) {
450
+ headers["content-type"] = "application/json";
451
+ body = JSON.stringify(opts.body);
452
+ }
453
+ const url = this.baseURL + (path.startsWith("/") ? path : `/${path}`);
454
+ for (let attempt = 0; ; attempt++) {
455
+ let wait;
456
+ let failure;
457
+ const ctl = new AbortController();
458
+ let timedOut = false;
459
+ const timer = setTimeout(() => {
460
+ timedOut = true;
461
+ ctl.abort();
462
+ }, this.timeout);
463
+ let keepLink = false;
464
+ const onAbort = () => ctl.abort();
465
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
466
+ try {
467
+ if (opts.signal?.aborted) ctl.abort();
468
+ const res = await this.fetchFn(url, { method, headers, body, signal: ctl.signal });
469
+ clearTimeout(timer);
470
+ if (res.ok) {
471
+ if (!opts.stream) return await res.json();
472
+ if (!opts.signal) return res;
473
+ keepLink = true;
474
+ return releaseOnEnd(res, () => opts.signal.removeEventListener("abort", onAbort));
475
+ }
476
+ const parsed = await res.json().catch(() => void 0);
477
+ failure = errorFrom(res.status, parsed, res.headers);
478
+ if (!RETRY_STATUS.has(res.status)) throw failure;
479
+ if (failure.retryAfter !== void 0) wait = Math.min(failure.retryAfter, MAX_RETRY_AFTER_S) * 1e3;
480
+ } catch (e) {
481
+ clearTimeout(timer);
482
+ if (e instanceof APIError && !(e instanceof APIConnectionError)) throw e;
483
+ if (opts.signal?.aborted) throw e;
484
+ failure = timedOut ? new APITimeoutError() : new APIConnectionError("Could not reach the API.", { cause: e });
485
+ } finally {
486
+ if (!keepLink) opts.signal?.removeEventListener("abort", onAbort);
487
+ }
488
+ if (attempt >= this.maxRetries) throw failure;
489
+ await this.sleep(wait ?? Math.min(8e3, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5), opts.signal);
490
+ if (opts.signal?.aborted) throw failure;
491
+ }
492
+ }
493
+ };
494
+ function releaseOnEnd(res, release) {
495
+ const reader = res.body?.getReader();
496
+ if (!reader) {
497
+ release();
498
+ return res;
499
+ }
500
+ const body = new ReadableStream({
501
+ async pull(c) {
502
+ try {
503
+ const { done, value } = await reader.read();
504
+ if (done) {
505
+ release();
506
+ c.close();
507
+ } else c.enqueue(value);
508
+ } catch (e) {
509
+ release();
510
+ c.error(e);
511
+ }
512
+ },
513
+ cancel(reason) {
514
+ release();
515
+ return reader.cancel(reason);
516
+ }
517
+ });
518
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers });
519
+ }
520
+
521
+ // src/types.ts
522
+ var ARTIFACT_KINDS = ["workbook", "table", "chart", "report"];
523
+
524
+ // src/index.ts
525
+ var index_default = Antarya;
526
+ // Annotate the CommonJS export names for ESM import in node:
527
+ 0 && (module.exports = {
528
+ APIConnectionError,
529
+ APIError,
530
+ APITimeoutError,
531
+ ARTIFACT_KINDS,
532
+ Antarya,
533
+ AuthenticationError,
534
+ BadRequestError,
535
+ ChatStream,
536
+ InternalServerError,
537
+ NotFoundError,
538
+ OverloadedError,
539
+ PermissionDeniedError,
540
+ RateLimitError,
541
+ RequestTooLargeError,
542
+ errorFrom
543
+ });