@onyx.dev/onyx-database 1.1.0 → 2.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.
@@ -11,6 +11,8 @@ var process__default = /*#__PURE__*/_interopDefault(process);
11
11
 
12
12
  // src/config/defaults.ts
13
13
  var DEFAULT_BASE_URL = "https://api.onyx.dev";
14
+ var DEFAULT_AI_BASE_URL = "https://ai.onyx.dev";
15
+ var DEFAULT_AI_MODEL = "onyx";
14
16
  var sanitizeBaseUrl = (u) => u.replace(/\/+$/, "");
15
17
 
16
18
  // src/errors/config-error.ts
@@ -69,6 +71,8 @@ function readEnv(targetId) {
69
71
  if (targetId && envId !== targetId) return {};
70
72
  const res = dropUndefined({
71
73
  baseUrl: pick("ONYX_DATABASE_BASE_URL"),
74
+ aiBaseUrl: pick("ONYX_AI_BASE_URL"),
75
+ defaultModel: pick("ONYX_DEFAULT_MODEL"),
72
76
  databaseId: envId,
73
77
  apiKey: pick("ONYX_DATABASE_API_KEY"),
74
78
  apiSecret: pick("ONYX_DATABASE_API_SECRET")
@@ -205,6 +209,8 @@ async function resolveConfig(input) {
205
209
  }
206
210
  const merged = {
207
211
  baseUrl: DEFAULT_BASE_URL,
212
+ aiBaseUrl: DEFAULT_AI_BASE_URL,
213
+ defaultModel: DEFAULT_AI_MODEL,
208
214
  ...dropUndefined(home),
209
215
  ...dropUndefined(project),
210
216
  ...dropUndefined(cfgPath),
@@ -213,6 +219,8 @@ async function resolveConfig(input) {
213
219
  };
214
220
  dbg("merged (pre-validate):", mask(merged));
215
221
  const baseUrl = sanitizeBaseUrl(merged.baseUrl ?? DEFAULT_BASE_URL);
222
+ const aiBaseUrl = sanitizeBaseUrl(merged.aiBaseUrl ?? DEFAULT_AI_BASE_URL);
223
+ const defaultModel = typeof merged.defaultModel === "string" && merged.defaultModel.trim() ? merged.defaultModel.trim() : DEFAULT_AI_MODEL;
216
224
  const databaseId = merged.databaseId ?? "";
217
225
  const apiKey = merged.apiKey ?? "";
218
226
  const apiSecret = merged.apiSecret ?? "";
@@ -248,6 +256,8 @@ async function resolveConfig(input) {
248
256
  }
249
257
  const resolved = {
250
258
  baseUrl,
259
+ aiBaseUrl,
260
+ defaultModel,
251
261
  databaseId,
252
262
  apiKey,
253
263
  apiSecret,
@@ -258,6 +268,8 @@ async function resolveConfig(input) {
258
268
  };
259
269
  const source = {
260
270
  databaseId: input?.databaseId ? "explicit config" : env.databaseId ? "env" : cfgPath.databaseId ? "env ONYX_CONFIG_PATH" : project.databaseId ? "project file" : home.databaseId ? "home profile" : "unknown",
271
+ aiBaseUrl: input?.aiBaseUrl ? "explicit config" : env.aiBaseUrl ? "env" : cfgPath.aiBaseUrl ? "env ONYX_CONFIG_PATH" : project.aiBaseUrl ? "project file" : home.aiBaseUrl ? "home profile" : "default",
272
+ defaultModel: input?.defaultModel ? "explicit config" : env.defaultModel ? "env" : cfgPath.defaultModel ? "env ONYX_CONFIG_PATH" : project.defaultModel ? "project file" : home.defaultModel ? "home profile" : "default",
261
273
  apiKey: input?.apiKey ? "explicit config" : env.apiKey ? "env" : cfgPath.apiKey ? "env ONYX_CONFIG_PATH" : project.apiKey ? "project file" : home.apiKey ? "home profile" : "unknown",
262
274
  apiSecret: input?.apiSecret ? "explicit config" : env.apiSecret ? "env" : cfgPath.apiSecret ? "env ONYX_CONFIG_PATH" : project.apiSecret ? "project file" : home.apiSecret ? "home profile" : "unknown"
263
275
  };
@@ -277,6 +289,8 @@ async function resolveConfigWithSource(input) {
277
289
  const base = await resolveConfig(input);
278
290
  const sources = {
279
291
  baseUrl: input?.baseUrl ? "explicit config" : env.baseUrl ? "env" : cfgPath.baseUrl ? "env ONYX_CONFIG_PATH" : project.baseUrl ? "project file" : home.baseUrl ? "home profile" : "default",
292
+ aiBaseUrl: input?.aiBaseUrl ? "explicit config" : env.aiBaseUrl ? "env" : cfgPath.aiBaseUrl ? "env ONYX_CONFIG_PATH" : project.aiBaseUrl ? "project file" : home.aiBaseUrl ? "home profile" : "default",
293
+ defaultModel: input?.defaultModel ? "explicit config" : env.defaultModel ? "env" : cfgPath.defaultModel ? "env ONYX_CONFIG_PATH" : project.defaultModel ? "project file" : home.defaultModel ? "home profile" : "default",
280
294
  databaseId: input?.databaseId ? "explicit config" : env.databaseId ? "env" : cfgPath.databaseId ? "env ONYX_CONFIG_PATH" : project.databaseId ? "project file" : home.databaseId ? "home profile" : "unknown",
281
295
  apiKey: input?.apiKey ? "explicit config" : env.apiKey ? "env" : cfgPath.apiKey ? "env ONYX_CONFIG_PATH" : project.apiKey ? "project file" : home.apiKey ? "home profile" : "unknown",
282
296
  apiSecret: input?.apiSecret ? "explicit config" : env.apiSecret ? "env" : cfgPath.apiSecret ? "env ONYX_CONFIG_PATH" : project.apiSecret ? "project file" : home.apiSecret ? "home profile" : "unknown",
@@ -1399,38 +1413,69 @@ var OnyxDatabaseImpl = class {
1399
1413
  cfgPromise;
1400
1414
  resolved = null;
1401
1415
  http = null;
1416
+ aiHttp = null;
1402
1417
  streams = /* @__PURE__ */ new Set();
1403
1418
  requestLoggingEnabled;
1404
1419
  responseLoggingEnabled;
1405
1420
  defaultPartition;
1421
+ ai;
1406
1422
  constructor(config, resolveConfigWithCache) {
1407
1423
  this.requestLoggingEnabled = !!config?.requestLoggingEnabled;
1408
1424
  this.responseLoggingEnabled = !!config?.responseLoggingEnabled;
1409
1425
  this.defaultPartition = config?.partition;
1410
1426
  this.cfgPromise = resolveConfigWithCache(config);
1427
+ this.ai = this.createAiFacade();
1411
1428
  }
1412
- async ensureClient() {
1429
+ async resolveConfig() {
1413
1430
  if (!this.resolved) {
1414
1431
  this.resolved = await this.cfgPromise;
1415
1432
  }
1433
+ return this.resolved;
1434
+ }
1435
+ async ensureClient() {
1436
+ const cfg = await this.resolveConfig();
1416
1437
  if (!this.http) {
1417
1438
  this.http = new HttpClient({
1418
- baseUrl: this.resolved.baseUrl,
1419
- apiKey: this.resolved.apiKey,
1420
- apiSecret: this.resolved.apiSecret,
1421
- fetchImpl: this.resolved.fetch,
1439
+ baseUrl: cfg.baseUrl,
1440
+ apiKey: cfg.apiKey,
1441
+ apiSecret: cfg.apiSecret,
1442
+ fetchImpl: cfg.fetch,
1422
1443
  requestLoggingEnabled: this.requestLoggingEnabled,
1423
1444
  responseLoggingEnabled: this.responseLoggingEnabled,
1424
- retryEnabled: this.resolved.retryEnabled,
1425
- maxRetries: this.resolved.maxRetries,
1426
- retryInitialDelayMs: this.resolved.retryInitialDelayMs
1445
+ retryEnabled: cfg.retryEnabled,
1446
+ maxRetries: cfg.maxRetries,
1447
+ retryInitialDelayMs: cfg.retryInitialDelayMs
1427
1448
  });
1428
1449
  }
1429
1450
  return {
1430
1451
  http: this.http,
1431
- fetchImpl: this.resolved.fetch,
1432
- baseUrl: this.resolved.baseUrl,
1433
- databaseId: this.resolved.databaseId
1452
+ fetchImpl: cfg.fetch,
1453
+ baseUrl: cfg.baseUrl,
1454
+ databaseId: cfg.databaseId,
1455
+ defaultModel: cfg.defaultModel ?? DEFAULT_AI_MODEL
1456
+ };
1457
+ }
1458
+ async ensureAiClient() {
1459
+ const cfg = await this.resolveConfig();
1460
+ if (!this.aiHttp) {
1461
+ this.aiHttp = new HttpClient({
1462
+ baseUrl: cfg.aiBaseUrl,
1463
+ apiKey: cfg.apiKey,
1464
+ apiSecret: cfg.apiSecret,
1465
+ fetchImpl: cfg.fetch,
1466
+ requestLoggingEnabled: this.requestLoggingEnabled,
1467
+ responseLoggingEnabled: this.responseLoggingEnabled,
1468
+ retryEnabled: cfg.retryEnabled,
1469
+ maxRetries: cfg.maxRetries,
1470
+ retryInitialDelayMs: cfg.retryInitialDelayMs
1471
+ });
1472
+ }
1473
+ return {
1474
+ http: this.aiHttp,
1475
+ fetchImpl: cfg.fetch,
1476
+ aiBaseUrl: cfg.aiBaseUrl,
1477
+ databaseId: cfg.databaseId,
1478
+ defaultModel: cfg.defaultModel ?? DEFAULT_AI_MODEL
1434
1479
  };
1435
1480
  }
1436
1481
  registerStream(handle) {
@@ -1445,7 +1490,75 @@ var OnyxDatabaseImpl = class {
1445
1490
  }
1446
1491
  };
1447
1492
  }
1493
+ createAiFacade() {
1494
+ const chat = ((contentOrRequest, options) => {
1495
+ if (typeof contentOrRequest === "string") {
1496
+ return this.chatWithContent(contentOrRequest, options);
1497
+ }
1498
+ return this.getAiChatClient().create(contentOrRequest, options);
1499
+ });
1500
+ return {
1501
+ chat,
1502
+ chatClient: () => this.getAiChatClient(),
1503
+ getModels: () => this.getModels(),
1504
+ getModel: (modelId) => this.getModel(modelId),
1505
+ requestScriptApproval: (input) => this.requestScriptApproval(input)
1506
+ };
1507
+ }
1508
+ getRequestLoggingEnabled() {
1509
+ return this.requestLoggingEnabled;
1510
+ }
1511
+ getResponseLoggingEnabled() {
1512
+ return this.responseLoggingEnabled;
1513
+ }
1448
1514
  /** -------- IOnyxDatabase -------- */
1515
+ getAiChatClient() {
1516
+ return new AiChatClientImpl(
1517
+ () => this.ensureAiClient(),
1518
+ (handle) => this.registerStream(handle),
1519
+ () => this.requestLoggingEnabled,
1520
+ () => this.responseLoggingEnabled
1521
+ );
1522
+ }
1523
+ async chatWithContent(content, options) {
1524
+ const { defaultModel } = await this.ensureAiClient();
1525
+ const stream = options?.stream ?? false;
1526
+ const request = {
1527
+ model: options?.model ?? defaultModel,
1528
+ messages: [{ role: options?.role ?? "user", content }],
1529
+ stream
1530
+ };
1531
+ if (options && "temperature" in options) {
1532
+ request.temperature = options.temperature ?? null;
1533
+ }
1534
+ const result = await this.getAiChatClient().create(request, options);
1535
+ if (stream) return result;
1536
+ if (options?.raw) return result;
1537
+ const first = result.choices?.[0]?.message?.content;
1538
+ if (typeof first === "string" && first.trim().length > 0) {
1539
+ return first;
1540
+ }
1541
+ throw new Error("Chat completion response is missing message content");
1542
+ }
1543
+ chat(content, options) {
1544
+ if (typeof content === "string") {
1545
+ return this.chatWithContent(content, options);
1546
+ }
1547
+ return this.getAiChatClient();
1548
+ }
1549
+ async getModels() {
1550
+ const { http } = await this.ensureAiClient();
1551
+ return http.request("GET", "/v1/models");
1552
+ }
1553
+ async getModel(modelId) {
1554
+ const { http } = await this.ensureAiClient();
1555
+ const path2 = `/v1/models/${encodeURIComponent(modelId)}`;
1556
+ return http.request("GET", path2);
1557
+ }
1558
+ async requestScriptApproval(input) {
1559
+ const { http } = await this.ensureAiClient();
1560
+ return http.request("POST", "/api/script-approvals", input);
1561
+ }
1449
1562
  from(table) {
1450
1563
  return new QueryBuilderImpl(this, String(table), this.defaultPartition);
1451
1564
  }
@@ -1995,6 +2108,153 @@ var CascadeBuilderImpl = class {
1995
2108
  return this.db.delete(table, primaryKey, opts);
1996
2109
  }
1997
2110
  };
2111
+ var AiChatClientImpl = class {
2112
+ constructor(resolveAiClient, registerStream, requestLoggingEnabled, responseLoggingEnabled) {
2113
+ this.resolveAiClient = resolveAiClient;
2114
+ this.registerStream = registerStream;
2115
+ this.requestLoggingEnabled = requestLoggingEnabled;
2116
+ this.responseLoggingEnabled = responseLoggingEnabled;
2117
+ }
2118
+ normalizeEventData(rawEvent) {
2119
+ const lines = rawEvent.split("\n");
2120
+ const dataLines = [];
2121
+ for (const line of lines) {
2122
+ const trimmed = line.trim();
2123
+ if (!trimmed || trimmed.startsWith(":")) continue;
2124
+ if (trimmed.startsWith("data:")) {
2125
+ dataLines.push(trimmed.slice(5).trim());
2126
+ } else {
2127
+ dataLines.push(trimmed);
2128
+ }
2129
+ }
2130
+ if (!dataLines.length) return null;
2131
+ const joined = dataLines.join("\n").trim();
2132
+ return joined.length > 0 ? joined : null;
2133
+ }
2134
+ logRequest(url, body, headers) {
2135
+ if (!this.requestLoggingEnabled()) return;
2136
+ console.log(`POST ${url}`);
2137
+ if (body != null) {
2138
+ const serialized = typeof body === "string" ? body : JSON.stringify(body);
2139
+ console.log(serialized);
2140
+ }
2141
+ const headerLog = { ...headers };
2142
+ if (headerLog["x-onyx-secret"]) headerLog["x-onyx-secret"] = "[REDACTED]";
2143
+ console.log("Headers:", headerLog);
2144
+ }
2145
+ logResponse(status, statusText, raw) {
2146
+ if (!this.responseLoggingEnabled()) return;
2147
+ const statusLine = `${status} ${statusText}`.trim();
2148
+ console.log(statusLine);
2149
+ if (raw && raw.trim().length > 0) {
2150
+ console.log(raw);
2151
+ }
2152
+ }
2153
+ toOnyxError(status, statusText, raw) {
2154
+ let parsed = raw;
2155
+ try {
2156
+ parsed = parseJsonAllowNaN(raw);
2157
+ } catch {
2158
+ }
2159
+ const message = typeof parsed === "object" && parsed !== null && "error" in parsed && typeof parsed.error === "object" && typeof parsed.error?.message === "string" ? String(parsed.error.message) : `${status} ${statusText}`;
2160
+ return new OnyxHttpError(message, status, statusText, parsed, raw);
2161
+ }
2162
+ async create(request, options) {
2163
+ const body = { ...request, stream: !!request.stream };
2164
+ const { http, fetchImpl, aiBaseUrl, databaseId } = await this.resolveAiClient();
2165
+ const params = new URLSearchParams();
2166
+ const scopedDb = options?.databaseId ?? databaseId;
2167
+ if (scopedDb) params.append("databaseId", scopedDb);
2168
+ const path2 = `/v1/chat/completions${params.size ? `?${params.toString()}` : ""}`;
2169
+ if (!body.stream) {
2170
+ return http.request("POST", path2, body);
2171
+ }
2172
+ const url = `${aiBaseUrl}${path2}`;
2173
+ const headers = http.headers({ Accept: "text/event-stream" });
2174
+ this.logRequest(url, body, headers);
2175
+ const res = await fetchImpl(url, {
2176
+ method: "POST",
2177
+ headers,
2178
+ body: JSON.stringify(body)
2179
+ });
2180
+ if (!res.ok) {
2181
+ const raw = await res.text();
2182
+ this.logResponse(res.status, res.statusText, raw);
2183
+ throw this.toOnyxError(res.status, res.statusText, raw);
2184
+ }
2185
+ this.logResponse(res.status, res.statusText);
2186
+ const bodyStream = res.body;
2187
+ const reader = bodyStream && typeof bodyStream.getReader === "function" ? bodyStream.getReader() : null;
2188
+ if (!reader) {
2189
+ throw new OnyxHttpError(
2190
+ "Streaming response body is not readable",
2191
+ res.status,
2192
+ res.statusText,
2193
+ null,
2194
+ ""
2195
+ );
2196
+ }
2197
+ let canceled = false;
2198
+ const handle = {
2199
+ cancel: () => {
2200
+ if (canceled) return;
2201
+ canceled = true;
2202
+ try {
2203
+ reader.cancel?.();
2204
+ } catch {
2205
+ }
2206
+ }
2207
+ };
2208
+ const registered = this.registerStream(handle);
2209
+ const normalizeEvent = (rawEvent) => this.normalizeEventData(rawEvent);
2210
+ const stream = {
2211
+ async *[Symbol.asyncIterator]() {
2212
+ const decoder = new TextDecoder("utf-8");
2213
+ let buffer = "";
2214
+ try {
2215
+ while (!canceled) {
2216
+ const { done, value } = await reader.read();
2217
+ if (done) break;
2218
+ if (value) {
2219
+ buffer += decoder.decode(value, { stream: true });
2220
+ }
2221
+ let splitIndex = buffer.indexOf("\n\n");
2222
+ while (splitIndex !== -1) {
2223
+ const rawEvent = buffer.slice(0, splitIndex);
2224
+ buffer = buffer.slice(splitIndex + 2);
2225
+ const data = normalizeEvent(rawEvent);
2226
+ if (data === "[DONE]") return;
2227
+ if (data) {
2228
+ try {
2229
+ yield parseJsonAllowNaN(data);
2230
+ } catch {
2231
+ }
2232
+ }
2233
+ splitIndex = buffer.indexOf("\n\n");
2234
+ }
2235
+ }
2236
+ buffer += decoder.decode();
2237
+ const remaining = buffer.trim();
2238
+ if (remaining && remaining !== "[DONE]") {
2239
+ const data = normalizeEvent(remaining);
2240
+ if (data && data !== "[DONE]") {
2241
+ try {
2242
+ yield parseJsonAllowNaN(data);
2243
+ } catch {
2244
+ }
2245
+ }
2246
+ }
2247
+ } finally {
2248
+ registered.cancel();
2249
+ }
2250
+ },
2251
+ cancel() {
2252
+ registered.cancel();
2253
+ }
2254
+ };
2255
+ return stream;
2256
+ }
2257
+ };
1998
2258
  function createOnyxFacade(resolveConfig2) {
1999
2259
  let cachedCfg = null;
2000
2260
  function resolveConfigWithCache(config) {