@onyx.dev/onyx-database 1.2.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.
package/README.md CHANGED
@@ -94,6 +94,7 @@ Set the following environment variables for your database:
94
94
  - `ONYX_DATABASE_API_KEY`
95
95
  - `ONYX_DATABASE_API_SECRET`
96
96
  - `ONYX_AI_BASE_URL` (optional; defaults to `https://ai.onyx.dev`)
97
+ - `ONYX_DEFAULT_MODEL` (optional; used by `db.chat('...')`, defaults to `onyx`)
97
98
 
98
99
  ```ts
99
100
  import { onyx } from '@onyx.dev/onyx-database';
@@ -110,6 +111,7 @@ import { onyx } from '@onyx.dev/onyx-database';
110
111
  const db = onyx.init({
111
112
  baseUrl: 'https://api.onyx.dev',
112
113
  aiBaseUrl: 'https://ai.onyx.dev', // optional: override AI base path
114
+ defaultModel: 'onyx', // optional: shorthand `db.chat()` model
113
115
  databaseId: 'YOUR_DATABASE_ID',
114
116
  apiKey: 'YOUR_KEY',
115
117
  apiSecret: 'YOUR_SECRET',
@@ -184,7 +186,7 @@ necessary unless you create many short‑lived clients.
184
186
 
185
187
  ## Onyx AI (chat & models)
186
188
 
187
- AI endpoints are OpenAI-compatible and use the same credentials as database calls. The AI base URL defaults to `https://ai.onyx.dev` and can be overridden with `aiBaseUrl` (or `ONYX_AI_BASE_URL`). The `databaseId` query param is optional; when omitted, the configured databaseId is used for grounding and billing.
189
+ AI endpoints are OpenAI-compatible and use the same credentials as database calls. Use `db.ai` for chat, models, and script approvals; `db.chat()`/`db.chat('...')` remain supported as equivalent entrypoints. A shorthand `db.chat('content')` call is available and uses `config.defaultModel` (defaults to `onyx`). The AI base URL defaults to `https://ai.onyx.dev` and can be overridden with `aiBaseUrl` (or `ONYX_AI_BASE_URL`). The `databaseId` query param is optional; when omitted, the configured databaseId is used for grounding and billing.
188
190
 
189
191
  ### Chat completions
190
192
 
@@ -195,17 +197,27 @@ import { onyx } from '@onyx.dev/onyx-database';
195
197
 
196
198
  const db = onyx.init();
197
199
 
198
- const completion = await db.chat().create({
200
+ const quick = await db.chat('Reply with exactly one short greeting sentence.'); // returns first message content
201
+
202
+ const completion = await db.ai.chat({
199
203
  model: 'onyx-chat',
200
204
  messages: [{ role: 'user', content: 'Summarize last week’s traffic.' }],
201
205
  });
202
206
  console.log(completion.choices[0]?.message?.content);
207
+
208
+ // Override defaults (model/role/temperature/stream) in shorthand form
209
+ const custom = await db.chat('List three colors.', {
210
+ model: 'onyx-chat',
211
+ role: 'user',
212
+ temperature: 0.2,
213
+ stream: false, // set raw: true to receive full completion response instead of the first message content
214
+ });
203
215
  ```
204
216
 
205
217
  Streaming works as an async iterable:
206
218
 
207
219
  ```ts
208
- const stream = await db.chat().create({
220
+ const stream = await db.ai.chat({
209
221
  model: 'onyx-chat',
210
222
  stream: true,
211
223
  messages: [{ role: 'user', content: 'Write a short onboarding checklist.' }],
@@ -242,12 +254,12 @@ const prompt = {
242
254
  ],
243
255
  };
244
256
 
245
- const first = await db.chat().create(prompt);
257
+ const first = await db.ai.chat(prompt);
246
258
  const toolCall = first.choices[0]?.message?.tool_calls?.[0];
247
259
 
248
260
  if (toolCall) {
249
261
  const toolResult = await getRevenue(JSON.parse(toolCall.function.arguments)); // your impl
250
- const followup = await db.chat().create({
262
+ const followup = await db.ai.chat({
251
263
  model: prompt.model,
252
264
  messages: [
253
265
  ...prompt.messages,
@@ -264,14 +276,14 @@ if (toolCall) {
264
276
  Example: `examples/ai/models.ts`.
265
277
 
266
278
  ```ts
267
- const models = await db.getModels();
268
- const chatModel = await db.getModel('onyx-chat');
279
+ const models = await db.ai.getModels();
280
+ const chatModel = await db.ai.getModel('onyx-chat');
269
281
  ```
270
282
 
271
283
  ### Script mutation approvals
272
284
 
273
285
  ```ts
274
- const approval = await db.requestScriptApproval({
286
+ const approval = await db.ai.requestScriptApproval({
275
287
  script: "db.save({ id: 'u1', email: 'a@b.com' })",
276
288
  });
277
289
  if (approval.requiresApproval) {
@@ -822,6 +822,10 @@ interface OnyxConfig {
822
822
  apiKey?: string;
823
823
  apiSecret?: string;
824
824
  fetch?: FetchImpl;
825
+ /**
826
+ * Default AI model when using shorthand chat calls (`db.chat('...')`). Defaults to `onyx`.
827
+ */
828
+ defaultModel?: string;
825
829
  /**
826
830
  * Default partition for queries, `findById`, and deletes when removing by
827
831
  * primary key. Saves rely on the entity's partition field instead.
@@ -934,6 +938,28 @@ interface AiChatCompletionChunk {
934
938
  interface AiChatCompletionStream extends AsyncIterable<AiChatCompletionChunk> {
935
939
  cancel(): void;
936
940
  }
941
+ interface AiChatOptions extends AiRequestOptions {
942
+ /**
943
+ * Model to use for the shorthand `db.chat()` call. Defaults to config.defaultModel or `onyx`.
944
+ */
945
+ model?: string;
946
+ /**
947
+ * Role for the constructed message. Defaults to `user`.
948
+ */
949
+ role?: AiChatRole;
950
+ /**
951
+ * Temperature for the completion. Omit to use the service default.
952
+ */
953
+ temperature?: number | null;
954
+ /**
955
+ * Enable SSE streaming. Defaults to `false`.
956
+ */
957
+ stream?: boolean;
958
+ /**
959
+ * When true, return the raw completion response instead of the first message content.
960
+ */
961
+ raw?: boolean;
962
+ }
937
963
  interface AiChatClient {
938
964
  create(request: AiChatCompletionRequest & {
939
965
  stream?: false;
@@ -968,9 +994,90 @@ interface AiErrorResponse {
968
994
  [key: string]: unknown;
969
995
  } | null;
970
996
  }
997
+ interface AiClient {
998
+ /**
999
+ * Run a chat completion. Accepts shorthand strings or full requests.
1000
+ *
1001
+ * @example
1002
+ * ```ts
1003
+ * const quick = await db.ai.chat('Summarize last week.'); // returns first message content
1004
+ * const completion = await db.ai.chat(
1005
+ * { model: 'onyx-chat', messages: [{ role: 'user', content: 'Summarize last week.' }] },
1006
+ * { databaseId: 'db1', raw: true }, // returns full response
1007
+ * );
1008
+ * ```
1009
+ */
1010
+ chat(content: string, options?: AiChatOptions & {
1011
+ stream?: false;
1012
+ raw?: false | undefined;
1013
+ }): Promise<string>;
1014
+ chat(content: string, options: AiChatOptions & {
1015
+ stream: true;
1016
+ }): Promise<AiChatCompletionStream>;
1017
+ chat(content: string, options: AiChatOptions & {
1018
+ raw: true;
1019
+ }): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
1020
+ chat(request: AiChatCompletionRequest & {
1021
+ stream?: false;
1022
+ }, options?: AiRequestOptions): Promise<AiChatCompletionResponse>;
1023
+ chat(request: AiChatCompletionRequest & {
1024
+ stream: true;
1025
+ }, options?: AiRequestOptions): Promise<AiChatCompletionStream>;
1026
+ chat(request: AiChatCompletionRequest, options?: AiRequestOptions): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
1027
+ /**
1028
+ * Access the chat client for more control over streaming and cancellation.
1029
+ */
1030
+ chatClient(): AiChatClient;
1031
+ /**
1032
+ * List available AI models.
1033
+ *
1034
+ * @example
1035
+ * ```ts
1036
+ * const models = await db.ai.getModels();
1037
+ * ```
1038
+ */
1039
+ getModels(): Promise<AiModelsResponse>;
1040
+ /**
1041
+ * Retrieve a single AI model by ID.
1042
+ *
1043
+ * @example
1044
+ * ```ts
1045
+ * const model = await db.ai.getModel('onyx-chat');
1046
+ * ```
1047
+ */
1048
+ getModel(modelId: string): Promise<AiModel>;
1049
+ /**
1050
+ * Request mutation approval for a script.
1051
+ *
1052
+ * @example
1053
+ * ```ts
1054
+ * const approval = await db.ai.requestScriptApproval({
1055
+ * script: "db.save({ id: 'u1', email: 'a@b.com' })"
1056
+ * });
1057
+ * ```
1058
+ */
1059
+ requestScriptApproval(input: AiScriptApprovalRequest): Promise<AiScriptApprovalResponse>;
1060
+ }
971
1061
  interface IOnyxDatabase<Schema = Record<string, unknown>> {
972
1062
  /**
973
- * Access OpenAI-compatible chat completions.
1063
+ * AI helpers (chat, models, script approvals) grouped under `db.ai`.
1064
+ *
1065
+ * @example
1066
+ * ```ts
1067
+ * const completion = await db.ai.chat({
1068
+ * model: 'onyx-chat',
1069
+ * messages: [{ role: 'user', content: 'Summarize last week.' }],
1070
+ * });
1071
+ * ```
1072
+ */
1073
+ ai: AiClient;
1074
+ /**
1075
+ * Access OpenAI-compatible chat completions via `db.chat('...')` or `db.chat().create(...)`.
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * const completion = await db.chat('Summarize last week.'); // returns first message content
1080
+ * ```
974
1081
  *
975
1082
  * @example
976
1083
  * ```ts
@@ -995,10 +1102,22 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
995
1102
  * }
996
1103
  * ```
997
1104
  */
1105
+ chat(content: string, options?: AiChatOptions & {
1106
+ stream?: false;
1107
+ raw?: false | undefined;
1108
+ }): Promise<string>;
1109
+ chat(content: string, options: AiChatOptions & {
1110
+ stream: true;
1111
+ }): Promise<AiChatCompletionStream>;
1112
+ chat(content: string, options: AiChatOptions & {
1113
+ raw: true;
1114
+ }): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
998
1115
  chat(): AiChatClient;
999
1116
  /**
1000
1117
  * List available AI models.
1001
1118
  *
1119
+ * @deprecated Prefer `db.ai.getModels()`.
1120
+ *
1002
1121
  * @example
1003
1122
  * ```ts
1004
1123
  * const models = await db.getModels();
@@ -1008,6 +1127,8 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1008
1127
  /**
1009
1128
  * Retrieve a single AI model by ID.
1010
1129
  *
1130
+ * @deprecated Prefer `db.ai.getModel(...)`.
1131
+ *
1011
1132
  * @example
1012
1133
  * ```ts
1013
1134
  * const model = await db.getModel('onyx-chat');
@@ -1017,6 +1138,8 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1017
1138
  /**
1018
1139
  * Request mutation approval for a script.
1019
1140
  *
1141
+ * @deprecated Prefer `db.ai.requestScriptApproval(...)`.
1142
+ *
1020
1143
  * @example
1021
1144
  * ```ts
1022
1145
  * const approval = await db.requestScriptApproval({
@@ -1634,4 +1757,4 @@ declare const substring: (attribute: string, from: number, length: number) => st
1634
1757
  declare const replace: (attribute: string, pattern: string, repl: string) => string;
1635
1758
  declare const percentile: (attribute: string, p: number) => string;
1636
1759
 
1637
- export { type SchemaDiff as $, type AiRequestOptions as A, type SchemaDataType as B, type SchemaIdentifierGenerator as C, type SchemaIdentifier as D, type SchemaAttribute as E, type FullTextQuery as F, type SchemaIndexType as G, type SchemaIndex as H, type IOnyxDatabase as I, type SchemaResolver as J, type SchemaTriggerEvent as K, type SchemaTrigger as L, type SchemaEntity as M, type SchemaRevisionMetadata as N, type OnyxFacade as O, type SchemaRevision as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type SchemaHistoryEntry as T, type SchemaUpsertRequest as U, type SchemaValidationResult as V, type SchemaAttributeChange as W, type SchemaIndexChange as X, type SchemaResolverChange as Y, type SchemaTriggerChange as Z, type SchemaTableDiff as _, type QueryResultsPromise as a, type QueryCriteriaOperator as a0, type LogicalOperator as a1, type Sort as a2, type StreamAction as a3, type OnyxDocument as a4, type FetchResponse as a5, type FetchImpl as a6, type QueryCriteria as a7, type QueryCondition as a8, type SelectQuery as a9, containsIgnoreCase as aA, notContains as aB, notContainsIgnoreCase as aC, startsWith as aD, notStartsWith as aE, isNull as aF, notNull as aG, avg as aH, sum as aI, count as aJ, min as aK, max as aL, std as aM, variance as aN, median as aO, upper as aP, lower as aQ, substring as aR, replace as aS, percentile as aT, type UpdateQuery as aa, type QueryPage as ab, type IConditionBuilder as ac, type IQueryBuilder as ad, type ISaveBuilder as ae, type ICascadeBuilder as af, type ICascadeRelationshipBuilder as ag, asc as ah, desc as ai, eq as aj, neq as ak, inOp as al, within as am, notIn as an, notWithin as ao, between as ap, gt as aq, gte as ar, lt as as, lte as at, matches as au, search as av, notMatches as aw, like as ax, notLike as ay, contains as az, type OnyxConfig as b, type AiChatRole as c, type AiToolCallFunction as d, type AiToolCall as e, type AiChatMessage as f, type AiToolFunction as g, type AiTool as h, type AiToolChoice as i, type AiChatCompletionRequest as j, type AiChatCompletionUsage as k, type AiChatCompletionChoice as l, type AiChatCompletionResponse as m, type AiChatCompletionChunkDelta as n, type AiChatCompletionChunkChoice as o, type AiChatCompletionChunk as p, type AiChatCompletionStream as q, type AiChatClient as r, type AiScriptApprovalRequest as s, type AiScriptApprovalResponse as t, type AiModelsResponse as u, type AiModel as v, type AiErrorResponse as w, type SecretRecord as x, type SecretsListResponse as y, type SecretSaveRequest as z };
1760
+ export { type SchemaTriggerChange as $, type AiRequestOptions as A, type SecretsListResponse as B, type SecretSaveRequest as C, type SchemaDataType as D, type SchemaIdentifierGenerator as E, type FullTextQuery as F, type SchemaIdentifier as G, type SchemaAttribute as H, type IOnyxDatabase as I, type SchemaIndexType as J, type SchemaIndex as K, type SchemaResolver as L, type SchemaTriggerEvent as M, type SchemaTrigger as N, type OnyxFacade as O, type SchemaEntity as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type SchemaRevisionMetadata as T, type SchemaRevision as U, type SchemaHistoryEntry as V, type SchemaUpsertRequest as W, type SchemaValidationResult as X, type SchemaAttributeChange as Y, type SchemaIndexChange as Z, type SchemaResolverChange as _, type QueryResultsPromise as a, type SchemaTableDiff as a0, type SchemaDiff as a1, type QueryCriteriaOperator as a2, type LogicalOperator as a3, type Sort as a4, type StreamAction as a5, type OnyxDocument as a6, type FetchResponse as a7, type FetchImpl as a8, type QueryCriteria as a9, notLike as aA, contains as aB, containsIgnoreCase as aC, notContains as aD, notContainsIgnoreCase as aE, startsWith as aF, notStartsWith as aG, isNull as aH, notNull as aI, avg as aJ, sum as aK, count as aL, min as aM, max as aN, std as aO, variance as aP, median as aQ, upper as aR, lower as aS, substring as aT, replace as aU, percentile as aV, type QueryCondition as aa, type SelectQuery as ab, type UpdateQuery as ac, type QueryPage as ad, type IConditionBuilder as ae, type IQueryBuilder as af, type ISaveBuilder as ag, type ICascadeBuilder as ah, type ICascadeRelationshipBuilder as ai, asc as aj, desc as ak, eq as al, neq as am, inOp as an, within as ao, notIn as ap, notWithin as aq, between as ar, gt as as, gte as at, lt as au, lte as av, matches as aw, search as ax, notMatches as ay, like as az, type OnyxConfig as b, type AiChatRole as c, type AiToolCallFunction as d, type AiToolCall as e, type AiChatMessage as f, type AiToolFunction as g, type AiTool as h, type AiToolChoice as i, type AiChatCompletionRequest as j, type AiChatCompletionUsage as k, type AiChatCompletionChoice as l, type AiChatCompletionResponse as m, type AiChatCompletionChunkDelta as n, type AiChatCompletionChunkChoice as o, type AiChatCompletionChunk as p, type AiChatCompletionStream as q, type AiChatOptions as r, type AiChatClient as s, type AiScriptApprovalRequest as t, type AiScriptApprovalResponse as u, type AiModelsResponse as v, type AiModel as w, type AiErrorResponse as x, type AiClient as y, type SecretRecord as z };
@@ -822,6 +822,10 @@ interface OnyxConfig {
822
822
  apiKey?: string;
823
823
  apiSecret?: string;
824
824
  fetch?: FetchImpl;
825
+ /**
826
+ * Default AI model when using shorthand chat calls (`db.chat('...')`). Defaults to `onyx`.
827
+ */
828
+ defaultModel?: string;
825
829
  /**
826
830
  * Default partition for queries, `findById`, and deletes when removing by
827
831
  * primary key. Saves rely on the entity's partition field instead.
@@ -934,6 +938,28 @@ interface AiChatCompletionChunk {
934
938
  interface AiChatCompletionStream extends AsyncIterable<AiChatCompletionChunk> {
935
939
  cancel(): void;
936
940
  }
941
+ interface AiChatOptions extends AiRequestOptions {
942
+ /**
943
+ * Model to use for the shorthand `db.chat()` call. Defaults to config.defaultModel or `onyx`.
944
+ */
945
+ model?: string;
946
+ /**
947
+ * Role for the constructed message. Defaults to `user`.
948
+ */
949
+ role?: AiChatRole;
950
+ /**
951
+ * Temperature for the completion. Omit to use the service default.
952
+ */
953
+ temperature?: number | null;
954
+ /**
955
+ * Enable SSE streaming. Defaults to `false`.
956
+ */
957
+ stream?: boolean;
958
+ /**
959
+ * When true, return the raw completion response instead of the first message content.
960
+ */
961
+ raw?: boolean;
962
+ }
937
963
  interface AiChatClient {
938
964
  create(request: AiChatCompletionRequest & {
939
965
  stream?: false;
@@ -968,9 +994,90 @@ interface AiErrorResponse {
968
994
  [key: string]: unknown;
969
995
  } | null;
970
996
  }
997
+ interface AiClient {
998
+ /**
999
+ * Run a chat completion. Accepts shorthand strings or full requests.
1000
+ *
1001
+ * @example
1002
+ * ```ts
1003
+ * const quick = await db.ai.chat('Summarize last week.'); // returns first message content
1004
+ * const completion = await db.ai.chat(
1005
+ * { model: 'onyx-chat', messages: [{ role: 'user', content: 'Summarize last week.' }] },
1006
+ * { databaseId: 'db1', raw: true }, // returns full response
1007
+ * );
1008
+ * ```
1009
+ */
1010
+ chat(content: string, options?: AiChatOptions & {
1011
+ stream?: false;
1012
+ raw?: false | undefined;
1013
+ }): Promise<string>;
1014
+ chat(content: string, options: AiChatOptions & {
1015
+ stream: true;
1016
+ }): Promise<AiChatCompletionStream>;
1017
+ chat(content: string, options: AiChatOptions & {
1018
+ raw: true;
1019
+ }): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
1020
+ chat(request: AiChatCompletionRequest & {
1021
+ stream?: false;
1022
+ }, options?: AiRequestOptions): Promise<AiChatCompletionResponse>;
1023
+ chat(request: AiChatCompletionRequest & {
1024
+ stream: true;
1025
+ }, options?: AiRequestOptions): Promise<AiChatCompletionStream>;
1026
+ chat(request: AiChatCompletionRequest, options?: AiRequestOptions): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
1027
+ /**
1028
+ * Access the chat client for more control over streaming and cancellation.
1029
+ */
1030
+ chatClient(): AiChatClient;
1031
+ /**
1032
+ * List available AI models.
1033
+ *
1034
+ * @example
1035
+ * ```ts
1036
+ * const models = await db.ai.getModels();
1037
+ * ```
1038
+ */
1039
+ getModels(): Promise<AiModelsResponse>;
1040
+ /**
1041
+ * Retrieve a single AI model by ID.
1042
+ *
1043
+ * @example
1044
+ * ```ts
1045
+ * const model = await db.ai.getModel('onyx-chat');
1046
+ * ```
1047
+ */
1048
+ getModel(modelId: string): Promise<AiModel>;
1049
+ /**
1050
+ * Request mutation approval for a script.
1051
+ *
1052
+ * @example
1053
+ * ```ts
1054
+ * const approval = await db.ai.requestScriptApproval({
1055
+ * script: "db.save({ id: 'u1', email: 'a@b.com' })"
1056
+ * });
1057
+ * ```
1058
+ */
1059
+ requestScriptApproval(input: AiScriptApprovalRequest): Promise<AiScriptApprovalResponse>;
1060
+ }
971
1061
  interface IOnyxDatabase<Schema = Record<string, unknown>> {
972
1062
  /**
973
- * Access OpenAI-compatible chat completions.
1063
+ * AI helpers (chat, models, script approvals) grouped under `db.ai`.
1064
+ *
1065
+ * @example
1066
+ * ```ts
1067
+ * const completion = await db.ai.chat({
1068
+ * model: 'onyx-chat',
1069
+ * messages: [{ role: 'user', content: 'Summarize last week.' }],
1070
+ * });
1071
+ * ```
1072
+ */
1073
+ ai: AiClient;
1074
+ /**
1075
+ * Access OpenAI-compatible chat completions via `db.chat('...')` or `db.chat().create(...)`.
1076
+ *
1077
+ * @example
1078
+ * ```ts
1079
+ * const completion = await db.chat('Summarize last week.'); // returns first message content
1080
+ * ```
974
1081
  *
975
1082
  * @example
976
1083
  * ```ts
@@ -995,10 +1102,22 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
995
1102
  * }
996
1103
  * ```
997
1104
  */
1105
+ chat(content: string, options?: AiChatOptions & {
1106
+ stream?: false;
1107
+ raw?: false | undefined;
1108
+ }): Promise<string>;
1109
+ chat(content: string, options: AiChatOptions & {
1110
+ stream: true;
1111
+ }): Promise<AiChatCompletionStream>;
1112
+ chat(content: string, options: AiChatOptions & {
1113
+ raw: true;
1114
+ }): Promise<AiChatCompletionResponse | AiChatCompletionStream>;
998
1115
  chat(): AiChatClient;
999
1116
  /**
1000
1117
  * List available AI models.
1001
1118
  *
1119
+ * @deprecated Prefer `db.ai.getModels()`.
1120
+ *
1002
1121
  * @example
1003
1122
  * ```ts
1004
1123
  * const models = await db.getModels();
@@ -1008,6 +1127,8 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1008
1127
  /**
1009
1128
  * Retrieve a single AI model by ID.
1010
1129
  *
1130
+ * @deprecated Prefer `db.ai.getModel(...)`.
1131
+ *
1011
1132
  * @example
1012
1133
  * ```ts
1013
1134
  * const model = await db.getModel('onyx-chat');
@@ -1017,6 +1138,8 @@ interface IOnyxDatabase<Schema = Record<string, unknown>> {
1017
1138
  /**
1018
1139
  * Request mutation approval for a script.
1019
1140
  *
1141
+ * @deprecated Prefer `db.ai.requestScriptApproval(...)`.
1142
+ *
1020
1143
  * @example
1021
1144
  * ```ts
1022
1145
  * const approval = await db.requestScriptApproval({
@@ -1634,4 +1757,4 @@ declare const substring: (attribute: string, from: number, length: number) => st
1634
1757
  declare const replace: (attribute: string, pattern: string, repl: string) => string;
1635
1758
  declare const percentile: (attribute: string, p: number) => string;
1636
1759
 
1637
- export { type SchemaDiff as $, type AiRequestOptions as A, type SchemaDataType as B, type SchemaIdentifierGenerator as C, type SchemaIdentifier as D, type SchemaAttribute as E, type FullTextQuery as F, type SchemaIndexType as G, type SchemaIndex as H, type IOnyxDatabase as I, type SchemaResolver as J, type SchemaTriggerEvent as K, type SchemaTrigger as L, type SchemaEntity as M, type SchemaRevisionMetadata as N, type OnyxFacade as O, type SchemaRevision as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type SchemaHistoryEntry as T, type SchemaUpsertRequest as U, type SchemaValidationResult as V, type SchemaAttributeChange as W, type SchemaIndexChange as X, type SchemaResolverChange as Y, type SchemaTriggerChange as Z, type SchemaTableDiff as _, type QueryResultsPromise as a, type QueryCriteriaOperator as a0, type LogicalOperator as a1, type Sort as a2, type StreamAction as a3, type OnyxDocument as a4, type FetchResponse as a5, type FetchImpl as a6, type QueryCriteria as a7, type QueryCondition as a8, type SelectQuery as a9, containsIgnoreCase as aA, notContains as aB, notContainsIgnoreCase as aC, startsWith as aD, notStartsWith as aE, isNull as aF, notNull as aG, avg as aH, sum as aI, count as aJ, min as aK, max as aL, std as aM, variance as aN, median as aO, upper as aP, lower as aQ, substring as aR, replace as aS, percentile as aT, type UpdateQuery as aa, type QueryPage as ab, type IConditionBuilder as ac, type IQueryBuilder as ad, type ISaveBuilder as ae, type ICascadeBuilder as af, type ICascadeRelationshipBuilder as ag, asc as ah, desc as ai, eq as aj, neq as ak, inOp as al, within as am, notIn as an, notWithin as ao, between as ap, gt as aq, gte as ar, lt as as, lte as at, matches as au, search as av, notMatches as aw, like as ax, notLike as ay, contains as az, type OnyxConfig as b, type AiChatRole as c, type AiToolCallFunction as d, type AiToolCall as e, type AiChatMessage as f, type AiToolFunction as g, type AiTool as h, type AiToolChoice as i, type AiChatCompletionRequest as j, type AiChatCompletionUsage as k, type AiChatCompletionChoice as l, type AiChatCompletionResponse as m, type AiChatCompletionChunkDelta as n, type AiChatCompletionChunkChoice as o, type AiChatCompletionChunk as p, type AiChatCompletionStream as q, type AiChatClient as r, type AiScriptApprovalRequest as s, type AiScriptApprovalResponse as t, type AiModelsResponse as u, type AiModel as v, type AiErrorResponse as w, type SecretRecord as x, type SecretsListResponse as y, type SecretSaveRequest as z };
1760
+ export { type SchemaTriggerChange as $, type AiRequestOptions as A, type SecretsListResponse as B, type SecretSaveRequest as C, type SchemaDataType as D, type SchemaIdentifierGenerator as E, type FullTextQuery as F, type SchemaIdentifier as G, type SchemaAttribute as H, type IOnyxDatabase as I, type SchemaIndexType as J, type SchemaIndex as K, type SchemaResolver as L, type SchemaTriggerEvent as M, type SchemaTrigger as N, type OnyxFacade as O, type SchemaEntity as P, QueryResults as Q, type RetryOptions as R, type SecretMetadata as S, type SchemaRevisionMetadata as T, type SchemaRevision as U, type SchemaHistoryEntry as V, type SchemaUpsertRequest as W, type SchemaValidationResult as X, type SchemaAttributeChange as Y, type SchemaIndexChange as Z, type SchemaResolverChange as _, type QueryResultsPromise as a, type SchemaTableDiff as a0, type SchemaDiff as a1, type QueryCriteriaOperator as a2, type LogicalOperator as a3, type Sort as a4, type StreamAction as a5, type OnyxDocument as a6, type FetchResponse as a7, type FetchImpl as a8, type QueryCriteria as a9, notLike as aA, contains as aB, containsIgnoreCase as aC, notContains as aD, notContainsIgnoreCase as aE, startsWith as aF, notStartsWith as aG, isNull as aH, notNull as aI, avg as aJ, sum as aK, count as aL, min as aM, max as aN, std as aO, variance as aP, median as aQ, upper as aR, lower as aS, substring as aT, replace as aU, percentile as aV, type QueryCondition as aa, type SelectQuery as ab, type UpdateQuery as ac, type QueryPage as ad, type IConditionBuilder as ae, type IQueryBuilder as af, type ISaveBuilder as ag, type ICascadeBuilder as ah, type ICascadeRelationshipBuilder as ai, asc as aj, desc as ak, eq as al, neq as am, inOp as an, within as ao, notIn as ap, notWithin as aq, between as ar, gt as as, gte as at, lt as au, lte as av, matches as aw, search as ax, notMatches as ay, like as az, type OnyxConfig as b, type AiChatRole as c, type AiToolCallFunction as d, type AiToolCall as e, type AiChatMessage as f, type AiToolFunction as g, type AiTool as h, type AiToolChoice as i, type AiChatCompletionRequest as j, type AiChatCompletionUsage as k, type AiChatCompletionChoice as l, type AiChatCompletionResponse as m, type AiChatCompletionChunkDelta as n, type AiChatCompletionChunkChoice as o, type AiChatCompletionChunk as p, type AiChatCompletionStream as q, type AiChatOptions as r, type AiChatClient as s, type AiScriptApprovalRequest as t, type AiScriptApprovalResponse as u, type AiModelsResponse as v, type AiModel as w, type AiErrorResponse as x, type AiClient as y, type SecretRecord as z };
package/dist/edge.cjs CHANGED
@@ -3,6 +3,7 @@
3
3
  // src/config/defaults.ts
4
4
  var DEFAULT_BASE_URL = "https://api.onyx.dev";
5
5
  var DEFAULT_AI_BASE_URL = "https://ai.onyx.dev";
6
+ var DEFAULT_AI_MODEL = "onyx";
6
7
  var sanitizeBaseUrl = (u) => u.replace(/\/+$/, "");
7
8
 
8
9
  // src/errors/config-error.ts
@@ -55,6 +56,7 @@ function readEnv(targetId) {
55
56
  const res = dropUndefined({
56
57
  baseUrl: pick("ONYX_DATABASE_BASE_URL"),
57
58
  aiBaseUrl: pick("ONYX_AI_BASE_URL"),
59
+ defaultModel: pick("ONYX_DEFAULT_MODEL"),
58
60
  databaseId: envId,
59
61
  apiKey: pick("ONYX_DATABASE_API_KEY"),
60
62
  apiSecret: pick("ONYX_DATABASE_API_SECRET")
@@ -74,12 +76,14 @@ async function resolveConfig(input) {
74
76
  const merged = {
75
77
  baseUrl: DEFAULT_BASE_URL,
76
78
  aiBaseUrl: DEFAULT_AI_BASE_URL,
79
+ defaultModel: DEFAULT_AI_MODEL,
77
80
  ...dropUndefined(env),
78
81
  ...dropUndefined(input)
79
82
  };
80
83
  dbg("merged (pre-validate):", mask(merged));
81
84
  const baseUrl = sanitizeBaseUrl(merged.baseUrl ?? DEFAULT_BASE_URL);
82
85
  const aiBaseUrl = sanitizeBaseUrl(merged.aiBaseUrl ?? DEFAULT_AI_BASE_URL);
86
+ const defaultModel = typeof merged.defaultModel === "string" && merged.defaultModel.trim() ? merged.defaultModel.trim() : DEFAULT_AI_MODEL;
83
87
  const databaseId = merged.databaseId ?? "";
84
88
  const apiKey = merged.apiKey ?? "";
85
89
  const apiSecret = merged.apiSecret ?? "";
@@ -105,6 +109,7 @@ async function resolveConfig(input) {
105
109
  const resolved = {
106
110
  baseUrl,
107
111
  aiBaseUrl,
112
+ defaultModel,
108
113
  databaseId,
109
114
  apiKey,
110
115
  apiSecret,
@@ -1130,58 +1135,64 @@ var OnyxDatabaseImpl = class {
1130
1135
  requestLoggingEnabled;
1131
1136
  responseLoggingEnabled;
1132
1137
  defaultPartition;
1138
+ ai;
1133
1139
  constructor(config, resolveConfigWithCache) {
1134
1140
  this.requestLoggingEnabled = !!config?.requestLoggingEnabled;
1135
1141
  this.responseLoggingEnabled = !!config?.responseLoggingEnabled;
1136
1142
  this.defaultPartition = config?.partition;
1137
1143
  this.cfgPromise = resolveConfigWithCache(config);
1144
+ this.ai = this.createAiFacade();
1138
1145
  }
1139
- async ensureClient() {
1146
+ async resolveConfig() {
1140
1147
  if (!this.resolved) {
1141
1148
  this.resolved = await this.cfgPromise;
1142
1149
  }
1150
+ return this.resolved;
1151
+ }
1152
+ async ensureClient() {
1153
+ const cfg = await this.resolveConfig();
1143
1154
  if (!this.http) {
1144
1155
  this.http = new HttpClient({
1145
- baseUrl: this.resolved.baseUrl,
1146
- apiKey: this.resolved.apiKey,
1147
- apiSecret: this.resolved.apiSecret,
1148
- fetchImpl: this.resolved.fetch,
1156
+ baseUrl: cfg.baseUrl,
1157
+ apiKey: cfg.apiKey,
1158
+ apiSecret: cfg.apiSecret,
1159
+ fetchImpl: cfg.fetch,
1149
1160
  requestLoggingEnabled: this.requestLoggingEnabled,
1150
1161
  responseLoggingEnabled: this.responseLoggingEnabled,
1151
- retryEnabled: this.resolved.retryEnabled,
1152
- maxRetries: this.resolved.maxRetries,
1153
- retryInitialDelayMs: this.resolved.retryInitialDelayMs
1162
+ retryEnabled: cfg.retryEnabled,
1163
+ maxRetries: cfg.maxRetries,
1164
+ retryInitialDelayMs: cfg.retryInitialDelayMs
1154
1165
  });
1155
1166
  }
1156
1167
  return {
1157
1168
  http: this.http,
1158
- fetchImpl: this.resolved.fetch,
1159
- baseUrl: this.resolved.baseUrl,
1160
- databaseId: this.resolved.databaseId
1169
+ fetchImpl: cfg.fetch,
1170
+ baseUrl: cfg.baseUrl,
1171
+ databaseId: cfg.databaseId,
1172
+ defaultModel: cfg.defaultModel ?? DEFAULT_AI_MODEL
1161
1173
  };
1162
1174
  }
1163
1175
  async ensureAiClient() {
1164
- if (!this.resolved) {
1165
- this.resolved = await this.cfgPromise;
1166
- }
1176
+ const cfg = await this.resolveConfig();
1167
1177
  if (!this.aiHttp) {
1168
1178
  this.aiHttp = new HttpClient({
1169
- baseUrl: this.resolved.aiBaseUrl,
1170
- apiKey: this.resolved.apiKey,
1171
- apiSecret: this.resolved.apiSecret,
1172
- fetchImpl: this.resolved.fetch,
1179
+ baseUrl: cfg.aiBaseUrl,
1180
+ apiKey: cfg.apiKey,
1181
+ apiSecret: cfg.apiSecret,
1182
+ fetchImpl: cfg.fetch,
1173
1183
  requestLoggingEnabled: this.requestLoggingEnabled,
1174
1184
  responseLoggingEnabled: this.responseLoggingEnabled,
1175
- retryEnabled: this.resolved.retryEnabled,
1176
- maxRetries: this.resolved.maxRetries,
1177
- retryInitialDelayMs: this.resolved.retryInitialDelayMs
1185
+ retryEnabled: cfg.retryEnabled,
1186
+ maxRetries: cfg.maxRetries,
1187
+ retryInitialDelayMs: cfg.retryInitialDelayMs
1178
1188
  });
1179
1189
  }
1180
1190
  return {
1181
1191
  http: this.aiHttp,
1182
- fetchImpl: this.resolved.fetch,
1183
- aiBaseUrl: this.resolved.aiBaseUrl,
1184
- databaseId: this.resolved.databaseId
1192
+ fetchImpl: cfg.fetch,
1193
+ aiBaseUrl: cfg.aiBaseUrl,
1194
+ databaseId: cfg.databaseId,
1195
+ defaultModel: cfg.defaultModel ?? DEFAULT_AI_MODEL
1185
1196
  };
1186
1197
  }
1187
1198
  registerStream(handle) {
@@ -1196,6 +1207,21 @@ var OnyxDatabaseImpl = class {
1196
1207
  }
1197
1208
  };
1198
1209
  }
1210
+ createAiFacade() {
1211
+ const chat = ((contentOrRequest, options) => {
1212
+ if (typeof contentOrRequest === "string") {
1213
+ return this.chatWithContent(contentOrRequest, options);
1214
+ }
1215
+ return this.getAiChatClient().create(contentOrRequest, options);
1216
+ });
1217
+ return {
1218
+ chat,
1219
+ chatClient: () => this.getAiChatClient(),
1220
+ getModels: () => this.getModels(),
1221
+ getModel: (modelId) => this.getModel(modelId),
1222
+ requestScriptApproval: (input) => this.requestScriptApproval(input)
1223
+ };
1224
+ }
1199
1225
  getRequestLoggingEnabled() {
1200
1226
  return this.requestLoggingEnabled;
1201
1227
  }
@@ -1203,7 +1229,7 @@ var OnyxDatabaseImpl = class {
1203
1229
  return this.responseLoggingEnabled;
1204
1230
  }
1205
1231
  /** -------- IOnyxDatabase -------- */
1206
- chat() {
1232
+ getAiChatClient() {
1207
1233
  return new AiChatClientImpl(
1208
1234
  () => this.ensureAiClient(),
1209
1235
  (handle) => this.registerStream(handle),
@@ -1211,6 +1237,32 @@ var OnyxDatabaseImpl = class {
1211
1237
  () => this.responseLoggingEnabled
1212
1238
  );
1213
1239
  }
1240
+ async chatWithContent(content, options) {
1241
+ const { defaultModel } = await this.ensureAiClient();
1242
+ const stream = options?.stream ?? false;
1243
+ const request = {
1244
+ model: options?.model ?? defaultModel,
1245
+ messages: [{ role: options?.role ?? "user", content }],
1246
+ stream
1247
+ };
1248
+ if (options && "temperature" in options) {
1249
+ request.temperature = options.temperature ?? null;
1250
+ }
1251
+ const result = await this.getAiChatClient().create(request, options);
1252
+ if (stream) return result;
1253
+ if (options?.raw) return result;
1254
+ const first = result.choices?.[0]?.message?.content;
1255
+ if (typeof first === "string" && first.trim().length > 0) {
1256
+ return first;
1257
+ }
1258
+ throw new Error("Chat completion response is missing message content");
1259
+ }
1260
+ chat(content, options) {
1261
+ if (typeof content === "string") {
1262
+ return this.chatWithContent(content, options);
1263
+ }
1264
+ return this.getAiChatClient();
1265
+ }
1214
1266
  async getModels() {
1215
1267
  const { http } = await this.ensureAiClient();
1216
1268
  return http.request("GET", "/v1/models");