@ekodb/ekodb-client 0.12.0 → 0.14.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
@@ -348,6 +348,76 @@ for complete working examples:
348
348
  - `client_user_functions.ts` - User functions API
349
349
  - And more...
350
350
 
351
+ ### Goals, Tasks, and Agents
352
+
353
+ ```typescript
354
+ import { EkoDBClient } from "@ekodb/ekodb-client";
355
+
356
+ const client = new EkoDBClient("http://localhost:8080", "your-api-key");
357
+ await client.init();
358
+
359
+ // Goals
360
+ const goal = await client.goalCreate({
361
+ title: "Migrate data",
362
+ status: "active",
363
+ });
364
+ const goals = await client.goalList();
365
+ await client.goalComplete("goal-id", { summary: "Done" });
366
+ await client.goalApprove("goal-id");
367
+
368
+ // Tasks
369
+ const task = await client.taskCreate({
370
+ title: "Backup",
371
+ schedule: "0 0 * * *",
372
+ });
373
+ await client.taskStart("task-id");
374
+ await client.taskSucceed("task-id", { records: 1500 });
375
+
376
+ // Agents
377
+ const agent = await client.agentCreate({
378
+ name: "processor",
379
+ model: "gpt-4.1",
380
+ });
381
+ const agents = await client.agentList();
382
+ ```
383
+
384
+ ### Schedules
385
+
386
+ ```typescript
387
+ // Create a schedule
388
+ const sched = await client.createSchedule({
389
+ name: "nightly",
390
+ cron: "0 2 * * *",
391
+ });
392
+
393
+ // Pause a schedule
394
+ await client.pauseSchedule("sched-id");
395
+ ```
396
+
397
+ ### WebSocket Chat Streaming
398
+
399
+ ```typescript
400
+ const ws = client.websocket("ws://localhost:8080");
401
+
402
+ const stream = await ws.chatSend(chatId, "What is the capital of France?");
403
+ stream.on("event", (event) => {
404
+ switch (event.type) {
405
+ case "chunk":
406
+ process.stdout.write(event.content);
407
+ break;
408
+ case "end":
409
+ console.log(`\nDone (context: ${event.contextWindow} tokens)`);
410
+ break;
411
+ case "toolCall":
412
+ ws.sendToolResult(chatId, event.callId, true, result);
413
+ break;
414
+ case "error":
415
+ console.error(event.error);
416
+ break;
417
+ }
418
+ });
419
+ ```
420
+
351
421
  ## License
352
422
 
353
423
  MIT
package/dist/client.d.ts CHANGED
@@ -40,8 +40,6 @@ export interface ClientConfig {
40
40
  shouldRetry?: boolean;
41
41
  /** Maximum number of retry attempts (default: 3) */
42
42
  maxRetries?: number;
43
- /** Request timeout in milliseconds (default: 30000) */
44
- timeout?: number;
45
43
  /** Serialization format (default: MessagePack for best performance, use Json for debugging) */
46
44
  format?: SerializationFormat;
47
45
  }
@@ -110,6 +108,24 @@ export interface BatchDeleteOptions {
110
108
  bypassRipple?: boolean;
111
109
  transactionId?: string;
112
110
  }
111
+ export interface DistinctValuesOptions {
112
+ /** Optional filter expression (same format as find() filter). */
113
+ filter?: any;
114
+ /** Bypass ripple propagation for this query. */
115
+ bypassRipple?: boolean;
116
+ /** Bypass cache for this query. */
117
+ bypassCache?: boolean;
118
+ }
119
+ export interface DistinctValuesResponse {
120
+ /** Collection that was queried. */
121
+ collection: string;
122
+ /** Field whose distinct values were returned. */
123
+ field: string;
124
+ /** Unique values, sorted alphabetically. */
125
+ values: any[];
126
+ /** Number of distinct values. */
127
+ count: number;
128
+ }
113
129
  export interface CollectionConfig {
114
130
  collection_name: string;
115
131
  fields?: string[];
@@ -252,6 +268,22 @@ export interface EmbedResponse {
252
268
  model: string;
253
269
  dimensions: number;
254
270
  }
271
+ /**
272
+ * Request for stateless raw LLM completion — no session, no history, no RAG.
273
+ */
274
+ export interface RawCompletionRequest {
275
+ system_prompt: string;
276
+ message: string;
277
+ provider?: string;
278
+ model?: string;
279
+ max_tokens?: number;
280
+ }
281
+ /**
282
+ * Response from a raw LLM completion request.
283
+ */
284
+ export interface RawCompletionResponse {
285
+ content: string;
286
+ }
255
287
  /**
256
288
  * User function definition - reusable sequence of Functions that can be called by Scripts
257
289
  */
@@ -288,9 +320,9 @@ export declare class EkoDBClient {
288
320
  private baseURL;
289
321
  private apiKey;
290
322
  private token;
323
+ private tokenExpiry;
291
324
  private shouldRetry;
292
325
  private maxRetries;
293
- private timeout;
294
326
  private format;
295
327
  private rateLimitInfo;
296
328
  constructor(config: string | ClientConfig, apiKey?: string);
@@ -309,7 +341,26 @@ export declare class EkoDBClient {
309
341
  /**
310
342
  * Refresh the authentication token
311
343
  */
312
- private refreshToken;
344
+ refreshToken(): Promise<void>;
345
+ /**
346
+ * Get a valid authentication token.
347
+ *
348
+ * Returns a cached token if it has more than 60s of validity remaining.
349
+ * Otherwise fetches a new one via refreshToken(). This means callers
350
+ * never need to handle token refresh themselves — every getToken() call
351
+ * returns a token that's valid for at least 60 more seconds.
352
+ */
353
+ getToken(): Promise<string | null>;
354
+ /**
355
+ * Clear the cached authentication token and expiry.
356
+ * The next request will trigger a fresh token exchange.
357
+ */
358
+ clearTokenCache(): void;
359
+ /**
360
+ * Extract the `exp` claim from a JWT without verifying the signature.
361
+ * Returns the Unix timestamp (seconds) of expiry, or null if parsing fails.
362
+ */
363
+ private extractJWTExpiry;
313
364
  /**
314
365
  * Extract rate limit information from response headers
315
366
  */
@@ -362,6 +413,14 @@ export declare class EkoDBClient {
362
413
  * Find a document by ID
363
414
  */
364
415
  findById(collection: string, id: string): Promise<Record>;
416
+ /**
417
+ * Find a document by ID with field projection
418
+ * @param collection - Collection name
419
+ * @param id - Document ID
420
+ * @param selectFields - Fields to include in the result
421
+ * @param excludeFields - Fields to exclude from the result
422
+ */
423
+ findByIdWithProjection(collection: string, id: string, selectFields?: string[], excludeFields?: string[]): Promise<Record>;
365
424
  /**
366
425
  * Update a document
367
426
  * @param collection - Collection name
@@ -370,6 +429,31 @@ export declare class EkoDBClient {
370
429
  * @param options - Optional parameters (bypassRipple, transactionId, bypassCache, selectFields, excludeFields)
371
430
  */
372
431
  update(collection: string, id: string, record: Record, options?: UpdateOptions): Promise<Record>;
432
+ /**
433
+ * Apply an atomic field action to a single field of a record.
434
+ *
435
+ * Use this instead of `update()` for safe concurrent modifications like
436
+ * incrementing counters, pushing to arrays, or arithmetic operations.
437
+ *
438
+ * @param collection - Collection name
439
+ * @param id - Record ID
440
+ * @param action - The atomic action: increment, decrement, multiply, divide, modulo,
441
+ * push, pop, shift, unshift, remove, append, clear
442
+ * @param field - The field name to apply the action to
443
+ * @param value - The value for the action (omit for pop/shift/clear)
444
+ */
445
+ updateWithAction(collection: string, id: string, action: string, field: string, value?: any): Promise<Record>;
446
+ /**
447
+ * Apply a sequence of atomic field actions to a record in a single request.
448
+ *
449
+ * All actions are applied atomically — the record is fetched once, all actions
450
+ * run in order, and the result is persisted in a single update.
451
+ *
452
+ * @param collection - Collection name
453
+ * @param id - Record ID
454
+ * @param actions - Array of [action, field, value] tuples
455
+ */
456
+ updateWithActionSequence(collection: string, id: string, actions: [string, string, any][]): Promise<Record>;
373
457
  /**
374
458
  * Delete a document
375
459
  * @param collection - Collection name
@@ -657,6 +741,27 @@ export declare class EkoDBClient {
657
741
  * ```
658
742
  */
659
743
  search(collection: string, query: SearchQuery): Promise<SearchResponse>;
744
+ /**
745
+ * Get distinct (unique) values for a field across all records in a collection.
746
+ *
747
+ * Results are deduplicated and sorted alphabetically. Supports an optional filter
748
+ * to restrict which records are examined.
749
+ *
750
+ * @param collection - Collection name
751
+ * @param field - Field to get distinct values for
752
+ * @param options - Optional filter and bypass flags
753
+ *
754
+ * @example
755
+ * // All distinct statuses
756
+ * const resp = await client.distinctValues("orders", "status");
757
+ * console.log(resp.values); // ["active", "cancelled", "shipped"]
758
+ *
759
+ * // Only statuses for US orders
760
+ * const resp = await client.distinctValues("orders", "status", {
761
+ * filter: { type: "Condition", content: { field: "region", operator: "Eq", value: "us" } }
762
+ * });
763
+ */
764
+ distinctValues(collection: string, field: string, options?: DistinctValuesOptions): Promise<DistinctValuesResponse>;
660
765
  /**
661
766
  * Health check - verify the ekoDB server is responding
662
767
  */
@@ -665,10 +770,54 @@ export declare class EkoDBClient {
665
770
  * Create a new chat session
666
771
  */
667
772
  createChatSession(request: CreateChatSessionRequest): Promise<ChatResponse>;
773
+ /**
774
+ * Stateless raw LLM completion — no session, no history, no RAG.
775
+ *
776
+ * Sends a system prompt and user message directly to the LLM via ekoDB
777
+ * and returns the raw text response without any context injection or
778
+ * conversation management. Use this for structured-output tasks such as
779
+ * planning where the response must be parsed programmatically.
780
+ *
781
+ * @example
782
+ * const resp = await client.rawCompletion({
783
+ * system_prompt: "You are a helpful assistant.",
784
+ * message: "Summarize this in JSON.",
785
+ * max_tokens: 2048,
786
+ * });
787
+ * console.log(resp.content);
788
+ */
789
+ rawCompletion(request: RawCompletionRequest): Promise<RawCompletionResponse>;
790
+ /**
791
+ * Stateless raw LLM completion via SSE streaming.
792
+ *
793
+ * Same as rawCompletion() but uses Server-Sent Events to keep the
794
+ * connection alive. Preferred for deployed instances where reverse proxies
795
+ * may kill idle HTTP connections before the LLM responds.
796
+ */
797
+ rawCompletionStream(request: RawCompletionRequest): Promise<RawCompletionResponse>;
798
+ /**
799
+ * Stateless raw LLM completion via SSE streaming with token-level progress.
800
+ *
801
+ * Same as rawCompletionStream() but invokes `onToken` with each token as it
802
+ * arrives, allowing callers to show real-time progress.
803
+ */
804
+ rawCompletionStreamWithProgress(request: RawCompletionRequest, onToken: (token: string) => void): Promise<RawCompletionResponse>;
668
805
  /**
669
806
  * Send a message in an existing chat session
670
807
  */
671
808
  chatMessage(sessionId: string, request: ChatMessageRequest): Promise<ChatResponse>;
809
+ /**
810
+ * Send a message in an existing chat session via SSE streaming.
811
+ *
812
+ * Returns an EventStream that emits ChatStreamEvent objects as they arrive:
813
+ * - `{ type: "chunk", content: "..." }` for each token
814
+ * - `{ type: "end", messageId, executionTimeMs, tokenUsage?, contextWindow? }` when complete
815
+ * - `{ type: "error", error: "..." }` on failure
816
+ *
817
+ * Preferred over chatMessage() for long-running responses where reverse
818
+ * proxies may kill idle HTTP connections before the LLM responds.
819
+ */
820
+ chatMessageStream(chatId: string, request: ChatMessageRequest): EventStream<ChatStreamEvent>;
672
821
  /**
673
822
  * Get a chat session by ID
674
823
  */
@@ -718,6 +867,12 @@ export declare class EkoDBClient {
718
867
  * @returns ChatModels object with models organized by provider
719
868
  */
720
869
  getChatModels(): Promise<ChatModels>;
870
+ /**
871
+ * Get all built-in server-side chat tool definitions.
872
+ * Returns a list of tool objects with name, description, and parameters fields.
873
+ * Used by planning agents to discover available tools dynamically.
874
+ */
875
+ getChatTools(): Promise<object[]>;
721
876
  /**
722
877
  * Get available models for a specific provider
723
878
  * @param provider - Provider name (e.g., "openai", "anthropic", "perplexity")
@@ -786,6 +941,96 @@ export declare class EkoDBClient {
786
941
  * @param label - The user function label
787
942
  */
788
943
  deleteUserFunction(label: string): Promise<void>;
944
+ /** Create a new goal */
945
+ goalCreate(data: Record): Promise<Record>;
946
+ /** List all goals */
947
+ goalList(): Promise<Record>;
948
+ /** Get a goal by ID */
949
+ goalGet(id: string): Promise<Record>;
950
+ /** Update a goal by ID */
951
+ goalUpdate(id: string, data: Record): Promise<Record>;
952
+ /** Delete a goal by ID */
953
+ goalDelete(id: string): Promise<void>;
954
+ /** Create a new goal template */
955
+ goalTemplateCreate(data: Record): Promise<Record>;
956
+ /** List all goal templates */
957
+ goalTemplateList(): Promise<Record>;
958
+ /** Get a goal template by ID */
959
+ goalTemplateGet(id: string): Promise<Record>;
960
+ /** Update a goal template by ID */
961
+ goalTemplateUpdate(id: string, data: Record): Promise<Record>;
962
+ /** Delete a goal template by ID */
963
+ goalTemplateDelete(id: string): Promise<void>;
964
+ /** Search goals */
965
+ goalSearch(query: string): Promise<Record>;
966
+ /** Mark a goal as complete (status -> pending_review) */
967
+ goalComplete(id: string, data: Record): Promise<Record>;
968
+ /** Approve a goal (status -> in_progress) */
969
+ goalApprove(id: string): Promise<Record>;
970
+ /** Reject a goal (status -> failed) */
971
+ goalReject(id: string, data: Record): Promise<Record>;
972
+ /** Start a goal step (status -> in_progress) */
973
+ goalStepStart(id: string, stepIndex: number): Promise<Record>;
974
+ /** Complete a goal step with result */
975
+ goalStepComplete(id: string, stepIndex: number, data: Record): Promise<Record>;
976
+ /** Fail a goal step with error */
977
+ goalStepFail(id: string, stepIndex: number, data: Record): Promise<Record>;
978
+ /** Create a new scheduled task */
979
+ taskCreate(data: Record): Promise<Record>;
980
+ /** List all scheduled tasks */
981
+ taskList(): Promise<Record>;
982
+ /** Get a task by ID */
983
+ taskGet(id: string): Promise<Record>;
984
+ /** Update a task by ID */
985
+ taskUpdate(id: string, data: Record): Promise<Record>;
986
+ /** Delete a task by ID */
987
+ taskDelete(id: string): Promise<void>;
988
+ /** Get tasks that are due at the given time */
989
+ taskDue(now: string): Promise<Record>;
990
+ /** Start a task (status -> running) */
991
+ taskStart(id: string): Promise<Record>;
992
+ /** Mark a task as succeeded */
993
+ taskSucceed(id: string, data: Record): Promise<Record>;
994
+ /** Mark a task as failed */
995
+ taskFail(id: string, data: Record): Promise<Record>;
996
+ /** Pause a task */
997
+ taskPause(id: string): Promise<Record>;
998
+ /** Resume a paused task */
999
+ taskResume(id: string, data: Record): Promise<Record>;
1000
+ /** Create a new agent */
1001
+ agentCreate(data: Record): Promise<Record>;
1002
+ /** List all agents */
1003
+ agentList(): Promise<Record>;
1004
+ /** Get an agent by ID */
1005
+ agentGet(id: string): Promise<Record>;
1006
+ /** Get an agent by name */
1007
+ agentGetByName(name: string): Promise<Record>;
1008
+ /** Update an agent by ID */
1009
+ agentUpdate(id: string, data: Record): Promise<Record>;
1010
+ /** Delete an agent by ID */
1011
+ agentDelete(id: string): Promise<void>;
1012
+ /** Get agents by deployment ID */
1013
+ agentsByDeployment(deploymentId: string): Promise<Record>;
1014
+ /** Get documents linked to a KV key */
1015
+ kvGetLinks(key: string): Promise<Record>;
1016
+ /** Link a document to a KV key */
1017
+ kvLink(key: string, collection: string, documentId: string): Promise<Record>;
1018
+ /** Unlink a document from a KV key */
1019
+ kvUnlink(key: string, collection: string, documentId: string): Promise<Record>;
1020
+ /** Create a new schedule */
1021
+ createSchedule(data: Record): Promise<Record>;
1022
+ /** List all schedules */
1023
+ listSchedules(): Promise<Record>;
1024
+ /** Get a schedule by ID */
1025
+ getSchedule(id: string): Promise<Record>;
1026
+ /** Update a schedule */
1027
+ updateSchedule(id: string, data: Record): Promise<Record>;
1028
+ /** Delete a schedule */
1029
+ deleteSchedule(id: string): Promise<void>;
1030
+ /** Pause a schedule */
1031
+ pauseSchedule(id: string): Promise<Record>;
1032
+ /** Resume a schedule */
1033
+ resumeSchedule(id: string): Promise<Record>;
789
1034
  /**
790
1035
  * Check if a collection exists
791
1036
  * @param collection - Collection name to check
@@ -896,24 +1141,121 @@ export declare class EkoDBClient {
896
1141
  */
897
1142
  findAllWithLimit(collection: string, limit: number): Promise<Record[]>;
898
1143
  }
1144
+ /** Mutation notification from a subscription. */
1145
+ export interface MutationNotification {
1146
+ collection: string;
1147
+ event: string;
1148
+ recordIds: string[];
1149
+ records?: any;
1150
+ timestamp: string;
1151
+ }
1152
+ /** A chunk/event from a streaming chat response. */
1153
+ export type ChatStreamEvent = {
1154
+ type: "chunk";
1155
+ content: string;
1156
+ } | {
1157
+ type: "end";
1158
+ messageId: string;
1159
+ tokenUsage?: any;
1160
+ toolCallHistory?: any;
1161
+ executionTimeMs: number;
1162
+ /** Model's context window size in tokens. */
1163
+ contextWindow?: number;
1164
+ } | {
1165
+ type: "toolCall";
1166
+ chatId: string;
1167
+ callId: string;
1168
+ toolName: string;
1169
+ arguments: any;
1170
+ } | {
1171
+ type: "error";
1172
+ error: string;
1173
+ };
1174
+ /** Definition for a client-side tool the LLM can call. */
1175
+ export interface ClientToolDefinition {
1176
+ name: string;
1177
+ description: string;
1178
+ parameters: any;
1179
+ }
1180
+ /** Options for chatSend. */
1181
+ export interface ChatSendOptions {
1182
+ bypassRipple?: boolean;
1183
+ clientTools?: ClientToolDefinition[];
1184
+ maxIterations?: number;
1185
+ confirmTools?: string[];
1186
+ excludeTools?: string[];
1187
+ }
1188
+ /** Options for subscribe. */
1189
+ export interface SubscribeOptions {
1190
+ filterField?: string;
1191
+ filterValue?: string;
1192
+ }
1193
+ /** EventEmitter-like interface for subscriptions and chat streams. */
1194
+ export declare class EventStream<_T = unknown> {
1195
+ private listeners;
1196
+ private _closed;
1197
+ on(event: string, listener: (data: any) => void): this;
1198
+ /** @internal */
1199
+ emit(event: string, data?: any): void;
1200
+ get closed(): boolean;
1201
+ /** @internal */
1202
+ close(): void;
1203
+ }
899
1204
  /**
900
- * WebSocket client for real-time queries
1205
+ * WebSocket client for real-time queries, subscriptions, and chat streaming.
901
1206
  */
902
1207
  export declare class WebSocketClient {
903
1208
  private wsURL;
904
1209
  private token;
905
1210
  private ws;
1211
+ private dispatcherRunning;
1212
+ private pendingRequests;
1213
+ private subscriptions;
1214
+ private chatStreams;
1215
+ private registerToolsAck;
906
1216
  constructor(wsURL: string, token: string);
1217
+ private messageCounter;
1218
+ private genMessageId;
907
1219
  /**
908
- * Connect to WebSocket
1220
+ * Connect and start the dispatcher.
909
1221
  */
910
- private connect;
1222
+ private ensureConnected;
1223
+ private spawnDispatcher;
1224
+ private routeMessage;
1225
+ private sendRequest;
911
1226
  /**
912
- * Find all records in a collection via WebSocket
1227
+ * Find all records in a collection via WebSocket.
913
1228
  */
914
1229
  findAll(collection: string): Promise<Record[]>;
915
1230
  /**
916
- * Close the WebSocket connection
1231
+ * Subscribe to mutation notifications on a collection.
1232
+ * Returns an EventStream that emits "mutation" events.
1233
+ */
1234
+ subscribe(collection: string, options?: SubscribeOptions): Promise<EventStream<MutationNotification>>;
1235
+ /**
1236
+ * Send a chat message and receive a streaming response.
1237
+ * Returns an EventStream that emits "event" with ChatStreamEvent objects.
1238
+ */
1239
+ chatSend(chatId: string, message: string, options?: ChatSendOptions): Promise<EventStream<ChatStreamEvent>>;
1240
+ /**
1241
+ * Register client-side tools for a chat session.
1242
+ */
1243
+ registerClientTools(chatId: string, tools: ClientToolDefinition[]): Promise<void>;
1244
+ /**
1245
+ * Send a tool result back to the server during a chat stream.
1246
+ */
1247
+ sendToolResult(chatId: string, callId: string, success: boolean, result?: any, error?: string): Promise<void>;
1248
+ /**
1249
+ * Stateless raw LLM completion via WebSocket.
1250
+ *
1251
+ * Sends a RawComplete message and waits for the Success response.
1252
+ * Preferred over HTTP for deployed instances: the persistent WSS
1253
+ * connection is already authenticated and won't be killed by reverse
1254
+ * proxy timeouts.
1255
+ */
1256
+ rawCompletion(request: RawCompletionRequest): Promise<RawCompletionResponse>;
1257
+ /**
1258
+ * Close the WebSocket connection.
917
1259
  */
918
1260
  close(): void;
919
1261
  }