@mdxui/do 2.1.1 → 4.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.
Files changed (75) hide show
  1. package/README.md +115 -323
  2. package/dist/{agents-xcIn2dUB.d.ts → agents-2_r9e9i7.d.ts} +213 -2
  3. package/dist/app/index.d.ts +347 -0
  4. package/dist/app/index.js +14 -0
  5. package/dist/app/index.js.map +1 -0
  6. package/dist/breadcrumbs-C9Qn3S7d.d.ts +81 -0
  7. package/dist/capnweb-client-Bq78FtEA.d.ts +229 -0
  8. package/dist/chunk-3XKYQRXY.js +192 -0
  9. package/dist/chunk-3XKYQRXY.js.map +1 -0
  10. package/dist/chunk-4KXVN3EQ.js +56 -0
  11. package/dist/chunk-4KXVN3EQ.js.map +1 -0
  12. package/dist/chunk-5SHZZC7L.js +234 -0
  13. package/dist/chunk-5SHZZC7L.js.map +1 -0
  14. package/dist/chunk-7UFINK3Q.js +1994 -0
  15. package/dist/chunk-7UFINK3Q.js.map +1 -0
  16. package/dist/chunk-JJLAES6W.js +76 -0
  17. package/dist/chunk-JJLAES6W.js.map +1 -0
  18. package/dist/chunk-KT52UU3U.js +985 -0
  19. package/dist/chunk-KT52UU3U.js.map +1 -0
  20. package/dist/chunk-LJIWB7KE.js +95 -0
  21. package/dist/chunk-LJIWB7KE.js.map +1 -0
  22. package/dist/chunk-NA652ART.js +596 -0
  23. package/dist/chunk-NA652ART.js.map +1 -0
  24. package/dist/chunk-OVLO7UOH.js +1071 -0
  25. package/dist/chunk-OVLO7UOH.js.map +1 -0
  26. package/dist/chunk-VRLUXCLD.js +31 -0
  27. package/dist/chunk-VRLUXCLD.js.map +1 -0
  28. package/dist/chunk-WMNT4OIE.js +249 -0
  29. package/dist/chunk-WMNT4OIE.js.map +1 -0
  30. package/dist/chunk-Y52IEYVM.js +131 -0
  31. package/dist/chunk-Y52IEYVM.js.map +1 -0
  32. package/dist/components/index.d.ts +14 -732
  33. package/dist/components/index.js +3 -6
  34. package/dist/config-CxvpD8Y6.d.ts +111 -0
  35. package/dist/{do-CaQVueZw.d.ts → do-D27i5bU0.d.ts} +32 -33
  36. package/dist/errors-DratdVIz.d.ts +346 -0
  37. package/dist/hooks/index.d.ts +450 -691
  38. package/dist/hooks/index.js +6 -4
  39. package/dist/hooks/things/index.d.ts +298 -0
  40. package/dist/hooks/things/index.js +8 -0
  41. package/dist/hooks/things/index.js.map +1 -0
  42. package/dist/index.d.ts +62 -989
  43. package/dist/index.js +12 -839
  44. package/dist/index.js.map +1 -1
  45. package/dist/lib/index.d.ts +798 -0
  46. package/dist/lib/index.js +6 -0
  47. package/dist/lib/index.js.map +1 -0
  48. package/dist/providers/index.d.ts +130 -34
  49. package/dist/providers/index.js +3 -2
  50. package/dist/query-keys-CZNFikIi.d.ts +153 -0
  51. package/dist/schemas/index.d.ts +5 -5
  52. package/dist/schemas/index.js +2 -2
  53. package/dist/schemas/index.js.map +1 -1
  54. package/dist/{thing-DtI25yZh.d.ts → thing-BF25aUtJ.d.ts} +72 -72
  55. package/dist/types/index.d.ts +693 -658
  56. package/dist/types/index.js +1 -2
  57. package/dist/views/index.d.ts +131 -0
  58. package/dist/views/index.js +11 -0
  59. package/dist/views/index.js.map +1 -0
  60. package/package.json +39 -17
  61. package/dist/__test-utils__/index.d.ts +0 -399
  62. package/dist/__test-utils__/index.js +0 -34641
  63. package/dist/__test-utils__/index.js.map +0 -1
  64. package/dist/chunk-EEDMN7UF.js +0 -1351
  65. package/dist/chunk-EEDMN7UF.js.map +0 -1
  66. package/dist/chunk-G3PMV62Z.js +0 -33
  67. package/dist/chunk-G3PMV62Z.js.map +0 -1
  68. package/dist/chunk-NXPXL5NA.js +0 -3789
  69. package/dist/chunk-NXPXL5NA.js.map +0 -1
  70. package/dist/chunk-PC5FJY6M.js +0 -20
  71. package/dist/chunk-PC5FJY6M.js.map +0 -1
  72. package/dist/chunk-XF6LKY2M.js +0 -445
  73. package/dist/chunk-XF6LKY2M.js.map +0 -1
  74. package/dist/magic-string.es-J7BYFTTJ.js +0 -1307
  75. package/dist/magic-string.es-J7BYFTTJ.js.map +0 -1
@@ -1,1351 +0,0 @@
1
- import { ThingFilterSchema, ThingSortSchema, ThingPaginationSchema, ThingQueryResultResponseSchema, ThingResponseSchema, ThingVersionResponseSchema, TypeStatsResponseSchema, ThingCreateInputSchema, ThingUpdateInputSchema, ThingDeleteOptionsSchema, RelationshipFilterSchema, RelationshipResponseSchema, EntityRelationshipsResultResponseSchema, EntityReferenceSchema, GraphPatternSchema, GraphTraversalResultResponseSchema, GraphStatsResponseSchema, RelationshipCreateInputSchema, WorkflowFilterSchema, PaginatedResultResponseSchema, WorkflowResponseSchema, ExecutionFilterSchema, WorkflowExecutionResponseSchema, WorkflowTriggerInputSchema, AgentFilterSchema, AgentResponseSchema, AgentMetricsResponseSchema, AgentExecutionFilterSchema, AgentExecutionResponseSchema, AgentExecuteInputSchema, AgentFeedbackInputSchema } from './chunk-GGO5GW72.js';
2
- import { DEFAULT_REQUEST_TIMEOUT, fetchWithTimeout, useDO, useDataProviderSafe } from './chunk-XF6LKY2M.js';
3
- import { useQuery, useQueryClient, useMutation } from '@tanstack/react-query';
4
- import { useCollection } from '@dotdo/react';
5
- export { use$ } from '@dotdo/react';
6
- import * as React2 from 'react';
7
- import { useMemo, useCallback } from 'react';
8
- import { z } from 'zod';
9
- import { DotdoDataProvider, AdminProvider as AdminProvider$1, useResource } from '@dotdo/react/admin';
10
- export { AdminError, AdminProvider as AdminProvider2, DotdoDataProvider, createCacheKey, createResourceFromSchema, formatAdminError, inferFieldsFromSchema, invalidateCache, isAdminError, useAdminContext, useOptimisticUpdate } from '@dotdo/react/admin';
11
- import { AdminProvider } from '@mdxui/admin/components';
12
- export { AdminProvider } from '@mdxui/admin/components';
13
- import { jsx } from 'react/jsx-runtime';
14
-
15
- // src/lib/errors.ts
16
- var APIError = class _APIError extends Error {
17
- constructor(code, message, status, details) {
18
- super(message);
19
- this.code = code;
20
- this.status = status;
21
- this.details = details;
22
- this.name = "APIError";
23
- Object.setPrototypeOf(this, _APIError.prototype);
24
- }
25
- /**
26
- * Create an APIError from a fetch Response
27
- *
28
- * @param response - The Response object from fetch
29
- * @param body - Optional response body text (if already read)
30
- * @returns An APIError with HTTP status information
31
- *
32
- * @example
33
- * ```typescript
34
- * const response = await fetch('/api/things')
35
- * if (!response.ok) {
36
- * throw APIError.fromResponse(response, await response.text())
37
- * }
38
- * ```
39
- */
40
- static fromResponse(response, body) {
41
- return new _APIError(`HTTP_${response.status}`, body || response.statusText, response.status);
42
- }
43
- /**
44
- * Type guard to check if an error is an APIError
45
- */
46
- static isAPIError(error) {
47
- return error instanceof _APIError;
48
- }
49
- };
50
- var NetworkError = class _NetworkError extends Error {
51
- constructor(message, cause) {
52
- super(message);
53
- this.cause = cause;
54
- this.name = "NetworkError";
55
- Object.setPrototypeOf(this, _NetworkError.prototype);
56
- }
57
- };
58
- var ValidationError = class _ValidationError extends Error {
59
- constructor(message, fields) {
60
- super(message);
61
- this.fields = fields;
62
- this.name = "ValidationError";
63
- Object.setPrototypeOf(this, _ValidationError.prototype);
64
- }
65
- };
66
- var SyncError = class _SyncError extends Error {
67
- constructor(message, operation, recoverable) {
68
- super(message);
69
- this.operation = operation;
70
- this.recoverable = recoverable;
71
- this.name = "SyncError";
72
- Object.setPrototypeOf(this, _SyncError.prototype);
73
- }
74
- };
75
- function isAPIError(error) {
76
- return error instanceof APIError;
77
- }
78
- function isNetworkError(error) {
79
- return error instanceof NetworkError;
80
- }
81
- function isValidationError(error) {
82
- return error instanceof ValidationError;
83
- }
84
- function isSyncError(error) {
85
- return error instanceof SyncError;
86
- }
87
-
88
- // src/lib/rpc-client.ts
89
- function createRPCClient(config) {
90
- const { rpcUrl, authToken, timeout = DEFAULT_REQUEST_TIMEOUT } = config;
91
- return {
92
- async call(method, input, options) {
93
- try {
94
- const response = await fetchWithTimeout(`${rpcUrl}/${method}`, {
95
- method: "POST",
96
- headers: {
97
- "Content-Type": "application/json",
98
- ...authToken ? { Authorization: `Bearer ${authToken}` } : {}
99
- },
100
- body: JSON.stringify(input),
101
- timeout,
102
- signal: options?.signal
103
- });
104
- if (!response.ok) {
105
- const body = await response.text().catch(() => "");
106
- throw APIError.fromResponse(response, body);
107
- }
108
- return response.json();
109
- } catch (error) {
110
- if (error instanceof APIError) throw error;
111
- if (error instanceof TypeError && error.message.includes("fetch")) {
112
- throw new NetworkError("Network request failed", error);
113
- }
114
- throw error;
115
- }
116
- }
117
- };
118
- }
119
- function useRPCClient() {
120
- const { rpcUrl, config } = useDO();
121
- return useMemo(() => {
122
- if (!rpcUrl) return null;
123
- return createRPCClient({
124
- rpcUrl,
125
- authToken: config.authToken,
126
- timeout: config.requestTimeout
127
- });
128
- }, [rpcUrl, config.authToken, config.requestTimeout]);
129
- }
130
-
131
- // src/lib/query-keys.ts
132
- var thingsKeys = {
133
- all: ["things"],
134
- lists: () => [...thingsKeys.all, "list"],
135
- list: (filter, sort, pagination) => [...thingsKeys.lists(), { filter, sort, pagination }],
136
- details: () => [...thingsKeys.all, "detail"],
137
- detail: (ns, type, id) => [...thingsKeys.details(), ns, type, id],
138
- versions: (ns, type, id) => [...thingsKeys.detail(ns, type, id), "versions"],
139
- types: () => [...thingsKeys.all, "types"],
140
- typeStats: (ns, type) => [...thingsKeys.types(), ns, type]
141
- };
142
- var agentsKeys = {
143
- all: ["agents"],
144
- lists: () => [...agentsKeys.all, "list"],
145
- list: (filter) => [...agentsKeys.lists(), filter],
146
- details: () => [...agentsKeys.all, "detail"],
147
- detail: (id) => [...agentsKeys.details(), id],
148
- metrics: (id) => [...agentsKeys.detail(id), "metrics"],
149
- executions: () => [...agentsKeys.all, "executions"],
150
- executionsList: (filter) => [...agentsKeys.executions(), "list", filter],
151
- execution: (id) => [...agentsKeys.executions(), "detail", id]
152
- };
153
- var workflowsKeys = {
154
- all: ["workflows"],
155
- lists: () => [...workflowsKeys.all, "list"],
156
- list: (filter) => [...workflowsKeys.lists(), filter],
157
- details: () => [...workflowsKeys.all, "detail"],
158
- detail: (id) => [...workflowsKeys.details(), id],
159
- executions: () => [...workflowsKeys.all, "executions"],
160
- executionsList: (filter) => [...workflowsKeys.executions(), "list", filter],
161
- execution: (id) => [...workflowsKeys.executions(), "detail", id]
162
- };
163
- var relationshipsKeys = {
164
- all: ["relationships"],
165
- lists: () => [...relationshipsKeys.all, "list"],
166
- list: (filter) => [...relationshipsKeys.lists(), filter],
167
- details: () => [...relationshipsKeys.all, "detail"],
168
- detail: (id) => [...relationshipsKeys.details(), id],
169
- graph: () => [...relationshipsKeys.all, "graph"],
170
- traverse: (entity, pattern) => [...relationshipsKeys.graph(), entity, pattern],
171
- stats: () => [...relationshipsKeys.all, "stats"]
172
- };
173
- var RPCResultSchema = z.object({
174
- type: z.literal("result"),
175
- results: z.array(
176
- z.object({
177
- type: z.enum(["value", "error"]),
178
- value: z.unknown().optional(),
179
- error: z.object({ message: z.string() }).optional()
180
- })
181
- ).min(1, "RPC response must have at least one result")
182
- });
183
- var RPCErrorSchema = z.object({
184
- type: z.literal("error"),
185
- error: z.object({ message: z.string() })
186
- });
187
- var RPCResponseSchema = z.union([RPCResultSchema, RPCErrorSchema]);
188
- function syncedThingToThing(synced) {
189
- return {
190
- ns: synced.ns,
191
- type: synced.type,
192
- id: synced.id,
193
- ts: new Date(synced.ts),
194
- name: synced.name,
195
- createdAt: new Date(synced.createdAt),
196
- updatedAt: new Date(synced.updatedAt),
197
- createdBy: synced.createdBy,
198
- updatedBy: synced.updatedBy,
199
- deletedAt: synced.deletedAt ? new Date(synced.deletedAt) : null,
200
- variant: synced.variant,
201
- data: synced.data
202
- };
203
- }
204
- function matchesFilter(thing, filter, defaultNs) {
205
- const ns = filter.ns ?? defaultNs;
206
- if (ns) {
207
- if (Array.isArray(ns)) {
208
- if (!ns.includes(thing.ns)) return false;
209
- } else {
210
- if (thing.ns !== ns) return false;
211
- }
212
- }
213
- if (filter.type) {
214
- if (Array.isArray(filter.type)) {
215
- if (!filter.type.includes(thing.type)) return false;
216
- } else {
217
- if (thing.type !== filter.type) return false;
218
- }
219
- }
220
- if (filter.nameSearch) {
221
- if (!thing.name.toLowerCase().includes(filter.nameSearch.toLowerCase())) {
222
- return false;
223
- }
224
- }
225
- if (!filter.includeDeleted && thing.deletedAt) {
226
- return false;
227
- }
228
- return true;
229
- }
230
- function sortThings(things, sort) {
231
- if (!sort) return things;
232
- return [...things].sort((a, b) => {
233
- let comparison = 0;
234
- switch (sort.field) {
235
- case "name":
236
- comparison = a.name.localeCompare(b.name);
237
- break;
238
- case "createdAt":
239
- comparison = a.createdAt.getTime() - b.createdAt.getTime();
240
- break;
241
- case "updatedAt":
242
- comparison = a.updatedAt.getTime() - b.updatedAt.getTime();
243
- break;
244
- case "ts":
245
- comparison = a.ts.getTime() - b.ts.getTime();
246
- break;
247
- case "type":
248
- comparison = a.type.localeCompare(b.type);
249
- break;
250
- }
251
- return sort.order === "desc" ? -comparison : comparison;
252
- });
253
- }
254
-
255
- // src/hooks/things/rpc.ts
256
- async function rpcCall(endpoint, method, args = [], options) {
257
- const requestId = crypto.randomUUID();
258
- const response = await fetchWithTimeout(endpoint, {
259
- method: "POST",
260
- headers: {
261
- "Content-Type": "application/json",
262
- ...options?.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}
263
- },
264
- body: JSON.stringify({
265
- id: requestId,
266
- type: "call",
267
- calls: [
268
- {
269
- promiseId: "p-1",
270
- target: { type: "root" },
271
- method,
272
- args: args.map((arg) => ({ type: "value", value: arg }))
273
- }
274
- ]
275
- }),
276
- signal: options?.signal,
277
- timeout: options?.timeout ?? DEFAULT_REQUEST_TIMEOUT
278
- });
279
- if (!response.ok) {
280
- throw new Error(`RPC error: ${response.status}`);
281
- }
282
- const json = await response.json();
283
- const parsed = RPCResponseSchema.parse(json);
284
- if (parsed.type === "error") {
285
- throw new Error(parsed.error.message);
286
- }
287
- const firstResult = parsed.results[0];
288
- if (firstResult.type === "error") {
289
- throw new Error(firstResult.error?.message ?? "Unknown RPC error");
290
- }
291
- if (firstResult.value === void 0) {
292
- throw new Error("RPC result missing value");
293
- }
294
- return firstResult.value;
295
- }
296
-
297
- // src/hooks/things/queries.ts
298
- function useThings(filter = {}, sort, pagination) {
299
- const { config, namespace, rpcUrl, isTanStackDBMode, db } = useDO();
300
- const queryKey = useMemo(
301
- () => thingsKeys.list({ ...filter, ns: filter.ns ?? namespace }, sort, pagination),
302
- [JSON.stringify(filter), namespace, JSON.stringify(sort), JSON.stringify(pagination)]
303
- );
304
- const collectionConfig = useMemo(() => ({
305
- collection: "Thing"
306
- }), []);
307
- const collection = useCollection(collectionConfig);
308
- const collectionResult = useMemo(() => {
309
- if (!isTanStackDBMode || !db) return null;
310
- if (collection.isLoading) return null;
311
- const filteredData = collection.data.filter(
312
- (item) => matchesFilter(item, filter, namespace)
313
- );
314
- const things = filteredData.map(syncedThingToThing);
315
- const sortedThings = sortThings(things, sort);
316
- const page = pagination?.page ?? 1;
317
- const perPage = pagination?.perPage ?? sortedThings.length;
318
- const startIndex = (page - 1) * perPage;
319
- const paginatedData = sortedThings.slice(startIndex, startIndex + perPage);
320
- const totalPages = Math.ceil(sortedThings.length / perPage);
321
- return {
322
- data: paginatedData,
323
- total: sortedThings.length,
324
- page,
325
- perPage,
326
- totalPages
327
- };
328
- }, [isTanStackDBMode, db, collection.data, collection.isLoading, filter, namespace, sort, pagination]);
329
- const collectionRefetch = useCallback(async () => {
330
- collection.refetch();
331
- return {
332
- data: collectionResult,
333
- dataUpdatedAt: Date.now(),
334
- error: collection.error,
335
- errorUpdateCount: 0,
336
- errorUpdatedAt: 0,
337
- failureCount: 0,
338
- failureReason: collection.error,
339
- fetchStatus: collection.isLoading ? "fetching" : "idle",
340
- isError: !!collection.error,
341
- isFetched: true,
342
- isFetchedAfterMount: true,
343
- isFetching: collection.isLoading,
344
- isInitialLoading: false,
345
- isLoading: collection.isLoading,
346
- isLoadingError: false,
347
- isPaused: false,
348
- isPending: collection.isLoading,
349
- isPlaceholderData: false,
350
- isRefetchError: false,
351
- isRefetching: false,
352
- isStale: false,
353
- isSuccess: !collection.error && !collection.isLoading,
354
- refetch: collectionRefetch,
355
- status: collection.isLoading ? "pending" : collection.error ? "error" : "success"
356
- };
357
- }, [collection, collectionResult]);
358
- const query = useQuery({
359
- queryKey,
360
- queryFn: async ({ signal }) => {
361
- const validatedFilter = ThingFilterSchema.parse(filter);
362
- const validatedSort = sort ? ThingSortSchema.parse(sort) : void 0;
363
- const validatedPagination = pagination ? ThingPaginationSchema.parse(pagination) : void 0;
364
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
365
- if (rpcUrl) {
366
- return rpcCall(
367
- rpcUrl,
368
- "Thing.list",
369
- [{ filter: { ...validatedFilter, ns: validatedFilter.ns ?? namespace }, sort: validatedSort, pagination: validatedPagination }],
370
- { authToken: config.authToken, signal, timeout }
371
- );
372
- } else {
373
- const params = new URLSearchParams();
374
- const ns = validatedFilter.ns ?? namespace;
375
- if (ns) params.set("ns", Array.isArray(ns) ? ns.join(",") : ns);
376
- if (validatedFilter.type) params.set("type", Array.isArray(validatedFilter.type) ? validatedFilter.type.join(",") : validatedFilter.type);
377
- if (validatedFilter.nameSearch) params.set("nameSearch", validatedFilter.nameSearch);
378
- if (validatedFilter.includeDeleted) params.set("includeDeleted", "true");
379
- if (validatedSort) {
380
- params.set("sortField", validatedSort.field);
381
- params.set("sortOrder", validatedSort.order);
382
- }
383
- if (validatedPagination) {
384
- params.set("page", validatedPagination.page.toString());
385
- params.set("perPage", validatedPagination.perPage.toString());
386
- }
387
- const response = await fetchWithTimeout(`${config.apiEndpoint}/things?${params}`, {
388
- headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {},
389
- signal,
390
- timeout
391
- });
392
- if (!response.ok) throw new Error("Failed to fetch things");
393
- const data = await response.json();
394
- return ThingQueryResultResponseSchema.parse(data);
395
- }
396
- },
397
- // Disable React Query when using TanStack DB mode
398
- enabled: !isTanStackDBMode
399
- });
400
- if (isTanStackDBMode && db) {
401
- return {
402
- data: collectionResult,
403
- isLoading: collection.isLoading,
404
- error: collection.error,
405
- refetch: collectionRefetch,
406
- queryKey,
407
- isRefetching: false,
408
- // Collection mode doesn't have background refetching
409
- isFetching: collection.isLoading,
410
- status: collection.isLoading ? "pending" : collection.error ? "error" : "success"
411
- };
412
- }
413
- return {
414
- data: query.data ?? null,
415
- isLoading: query.isLoading,
416
- error: query.error,
417
- refetch: query.refetch,
418
- queryKey,
419
- // Additional React Query properties
420
- isRefetching: query.isRefetching,
421
- isFetching: query.isFetching,
422
- status: query.status
423
- };
424
- }
425
- function useThing(ns, type, id) {
426
- const { config, isTanStackDBMode } = useDO();
427
- const rpcClient = useRPCClient();
428
- const queryKey = useMemo(() => thingsKeys.detail(ns, type, id), [ns, type, id]);
429
- const query = useQuery({
430
- queryKey,
431
- queryFn: async ({ signal }) => {
432
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
433
- if (isTanStackDBMode && rpcClient) {
434
- return rpcClient.call(
435
- "Thing.get",
436
- { ns, type, id },
437
- { signal }
438
- );
439
- }
440
- const response = await fetchWithTimeout(
441
- `${config.apiEndpoint}/things/${encodeURIComponent(ns)}/${encodeURIComponent(type)}/${encodeURIComponent(id)}`,
442
- { headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}, signal, timeout }
443
- );
444
- if (!response.ok) throw new Error("Failed to fetch thing");
445
- const data = await response.json();
446
- return ThingResponseSchema.parse(data);
447
- },
448
- enabled: Boolean(ns && type && id)
449
- });
450
- return {
451
- data: query.data ?? null,
452
- isLoading: query.isLoading,
453
- error: query.error,
454
- refetch: query.refetch,
455
- queryKey,
456
- isRefetching: query.isRefetching,
457
- isFetching: query.isFetching,
458
- status: query.status
459
- };
460
- }
461
- function useThingVersions(ns, type, id) {
462
- const { config, rpcUrl, isTanStackDBMode } = useDO();
463
- const queryKey = useMemo(() => thingsKeys.versions(ns, type, id), [ns, type, id]);
464
- const query = useQuery({
465
- queryKey,
466
- queryFn: async ({ signal }) => {
467
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
468
- if (isTanStackDBMode && rpcUrl) {
469
- return rpcCall(
470
- rpcUrl,
471
- "Thing.versions",
472
- [{ ns, type, id }],
473
- { authToken: config.authToken, signal, timeout }
474
- );
475
- } else {
476
- const response = await fetchWithTimeout(
477
- `${config.apiEndpoint}/things/${encodeURIComponent(ns)}/${encodeURIComponent(type)}/${encodeURIComponent(id)}/versions`,
478
- { headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}, signal, timeout }
479
- );
480
- if (!response.ok) throw new Error("Failed to fetch versions");
481
- const data = await response.json();
482
- return z.array(ThingVersionResponseSchema).parse(data);
483
- }
484
- },
485
- enabled: Boolean(ns && type && id)
486
- });
487
- return {
488
- data: query.data ?? null,
489
- isLoading: query.isLoading,
490
- error: query.error,
491
- refetch: query.refetch,
492
- queryKey,
493
- isRefetching: query.isRefetching,
494
- isFetching: query.isFetching,
495
- status: query.status
496
- };
497
- }
498
- function useTypeStats(ns, type) {
499
- const { config, rpcUrl, isTanStackDBMode } = useDO();
500
- const queryKey = useMemo(() => thingsKeys.typeStats(ns, type), [ns, type]);
501
- const query = useQuery({
502
- queryKey,
503
- queryFn: async ({ signal }) => {
504
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
505
- if (isTanStackDBMode && rpcUrl) {
506
- return rpcCall(
507
- rpcUrl,
508
- "Thing.stats",
509
- [{ ns, type }],
510
- { authToken: config.authToken, signal, timeout }
511
- );
512
- } else {
513
- const response = await fetchWithTimeout(
514
- `${config.apiEndpoint}/things/${encodeURIComponent(ns)}/${encodeURIComponent(type)}/stats`,
515
- { headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}, signal, timeout }
516
- );
517
- if (!response.ok) throw new Error("Failed to fetch stats");
518
- const data = await response.json();
519
- return TypeStatsResponseSchema.parse(data);
520
- }
521
- },
522
- enabled: Boolean(ns && type)
523
- });
524
- return {
525
- data: query.data ?? null,
526
- isLoading: query.isLoading,
527
- error: query.error,
528
- refetch: query.refetch,
529
- queryKey,
530
- isRefetching: query.isRefetching,
531
- isFetching: query.isFetching,
532
- status: query.status
533
- };
534
- }
535
- function useCreateThing() {
536
- const { config, rpcUrl, isTanStackDBMode, namespace } = useDO();
537
- const queryClient = useQueryClient();
538
- const dataProvider = useDataProviderSafe();
539
- const mutation = useMutation({
540
- mutationFn: async (input) => {
541
- const validatedInput = ThingCreateInputSchema.parse(input);
542
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
543
- if (dataProvider) {
544
- const result = await dataProvider.create("Thing", {
545
- data: {
546
- type: validatedInput.type,
547
- name: validatedInput.name,
548
- data: validatedInput.data,
549
- ns: validatedInput.ns ?? namespace,
550
- variant: validatedInput.variant
551
- }
552
- });
553
- return result.data;
554
- }
555
- if (isTanStackDBMode && rpcUrl) {
556
- return rpcCall(
557
- rpcUrl,
558
- "Thing.create",
559
- [validatedInput],
560
- { authToken: config.authToken, timeout }
561
- );
562
- }
563
- const response = await fetchWithTimeout(`${config.apiEndpoint}/things`, {
564
- method: "POST",
565
- headers: {
566
- "Content-Type": "application/json",
567
- ...config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}
568
- },
569
- body: JSON.stringify(validatedInput),
570
- timeout
571
- });
572
- if (!response.ok) throw new Error("Failed to create thing");
573
- const data = await response.json();
574
- return ThingResponseSchema.parse(data);
575
- },
576
- onSuccess: () => {
577
- queryClient.invalidateQueries({ queryKey: thingsKeys.all });
578
- }
579
- });
580
- return {
581
- mutate: mutation.mutate,
582
- mutateAsync: mutation.mutateAsync,
583
- isLoading: mutation.isPending,
584
- error: mutation.error,
585
- isSuccess: mutation.isSuccess,
586
- reset: mutation.reset
587
- };
588
- }
589
- function useUpdateThing(ns, type, id) {
590
- const { config, rpcUrl, isTanStackDBMode } = useDO();
591
- const queryClient = useQueryClient();
592
- const dataProvider = useDataProviderSafe();
593
- const mutation = useMutation({
594
- mutationFn: async (input) => {
595
- const validatedInput = ThingUpdateInputSchema.parse(input);
596
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
597
- if (dataProvider) {
598
- const result = await dataProvider.update("Thing", {
599
- id,
600
- data: {
601
- ...validatedInput,
602
- // Include ns and type for proper identification
603
- ns,
604
- type
605
- }
606
- });
607
- return result.data;
608
- }
609
- if (isTanStackDBMode && rpcUrl) {
610
- return rpcCall(
611
- rpcUrl,
612
- "Thing.update",
613
- [{ ns, type, id, ...validatedInput }],
614
- { authToken: config.authToken, timeout }
615
- );
616
- }
617
- const response = await fetchWithTimeout(
618
- `${config.apiEndpoint}/things/${encodeURIComponent(ns)}/${encodeURIComponent(type)}/${encodeURIComponent(id)}`,
619
- {
620
- method: "PATCH",
621
- headers: {
622
- "Content-Type": "application/json",
623
- ...config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {}
624
- },
625
- body: JSON.stringify(validatedInput),
626
- timeout
627
- }
628
- );
629
- if (!response.ok) throw new Error("Failed to update thing");
630
- const data = await response.json();
631
- return ThingResponseSchema.parse(data);
632
- },
633
- onSuccess: (data) => {
634
- queryClient.setQueryData(thingsKeys.detail(ns, type, id), data);
635
- queryClient.invalidateQueries({ queryKey: thingsKeys.lists() });
636
- }
637
- });
638
- return {
639
- mutate: mutation.mutate,
640
- mutateAsync: mutation.mutateAsync,
641
- isLoading: mutation.isPending,
642
- error: mutation.error,
643
- isSuccess: mutation.isSuccess,
644
- reset: mutation.reset
645
- };
646
- }
647
- function useDeleteThing(ns, type, id) {
648
- const { config, rpcUrl, isTanStackDBMode } = useDO();
649
- const queryClient = useQueryClient();
650
- const dataProvider = useDataProviderSafe();
651
- const mutation = useMutation({
652
- mutationFn: async (options) => {
653
- const validatedOptions = options ? ThingDeleteOptionsSchema.parse(options) : {};
654
- const hard = validatedOptions.hard ?? false;
655
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
656
- if (dataProvider && !hard) {
657
- await dataProvider.delete("Thing", { id });
658
- return;
659
- }
660
- if (isTanStackDBMode && rpcUrl) {
661
- await rpcCall(
662
- rpcUrl,
663
- "Thing.delete",
664
- [{ ns, type, id, hard }],
665
- { authToken: config.authToken, timeout }
666
- );
667
- return;
668
- }
669
- const response = await fetchWithTimeout(
670
- `${config.apiEndpoint}/things/${encodeURIComponent(ns)}/${encodeURIComponent(type)}/${encodeURIComponent(id)}?hard=${hard}`,
671
- {
672
- method: "DELETE",
673
- headers: config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {},
674
- timeout
675
- }
676
- );
677
- if (!response.ok) throw new Error("Failed to delete thing");
678
- },
679
- onSuccess: () => {
680
- queryClient.removeQueries({ queryKey: thingsKeys.detail(ns, type, id) });
681
- queryClient.invalidateQueries({ queryKey: thingsKeys.lists() });
682
- }
683
- });
684
- return {
685
- mutate: mutation.mutate,
686
- mutateAsync: mutation.mutateAsync,
687
- isLoading: mutation.isPending,
688
- error: mutation.error,
689
- isSuccess: mutation.isSuccess,
690
- reset: mutation.reset
691
- };
692
- }
693
- function useRelationships(filter = {}) {
694
- const { config } = useDO();
695
- const queryKey = useMemo(
696
- () => relationshipsKeys.list(filter),
697
- [JSON.stringify(filter)]
698
- );
699
- return useQuery({
700
- queryKey,
701
- queryFn: async ({ signal }) => {
702
- const validatedFilter = RelationshipFilterSchema.parse(filter);
703
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
704
- const params = new URLSearchParams();
705
- if (validatedFilter.predicates) params.set("predicates", validatedFilter.predicates.join(","));
706
- if (validatedFilter.from?.ns) params.set("fromNs", validatedFilter.from.ns);
707
- if (validatedFilter.from?.type) params.set("fromType", validatedFilter.from.type);
708
- if (validatedFilter.from?.id) params.set("fromId", validatedFilter.from.id);
709
- if (validatedFilter.to?.ns) params.set("toNs", validatedFilter.to.ns);
710
- if (validatedFilter.to?.type) params.set("toType", validatedFilter.to.type);
711
- if (validatedFilter.to?.id) params.set("toId", validatedFilter.to.id);
712
- if (validatedFilter.includeDeleted) params.set("includeDeleted", "true");
713
- const response = await fetchWithTimeout(`${config.apiEndpoint}/relationships?${params}`, {
714
- signal,
715
- timeout
716
- });
717
- if (!response.ok) throw new Error("Failed to fetch relationships");
718
- const data = await response.json();
719
- return z.array(RelationshipResponseSchema).parse(data);
720
- }
721
- });
722
- }
723
- function useEntityRelationships(entity, direction = "both") {
724
- const { config } = useDO();
725
- const queryKey = useMemo(
726
- () => [...relationshipsKeys.lists(), entity, direction],
727
- [JSON.stringify(entity), direction]
728
- );
729
- return useQuery({
730
- queryKey,
731
- queryFn: async ({ signal }) => {
732
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
733
- const params = new URLSearchParams();
734
- params.set("direction", direction);
735
- const response = await fetchWithTimeout(
736
- `${config.apiEndpoint}/relationships/entity/${encodeURIComponent(entity.ns)}/${encodeURIComponent(entity.type)}/${encodeURIComponent(entity.id)}?${params}`,
737
- { signal, timeout }
738
- );
739
- if (!response.ok) throw new Error("Failed to fetch entity relationships");
740
- const data = await response.json();
741
- return EntityRelationshipsResultResponseSchema.parse(data);
742
- },
743
- enabled: Boolean(entity.ns && entity.type && entity.id)
744
- });
745
- }
746
- function useGraphTraversal(entity, pattern) {
747
- const { config } = useDO();
748
- const queryKey = useMemo(
749
- () => relationshipsKeys.traverse(entity, pattern),
750
- [JSON.stringify(entity), JSON.stringify(pattern)]
751
- );
752
- return useQuery({
753
- queryKey,
754
- queryFn: async ({ signal }) => {
755
- const validatedEntity = EntityReferenceSchema.parse(entity);
756
- const validatedPattern = GraphPatternSchema.parse(pattern);
757
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
758
- const response = await fetchWithTimeout(`${config.apiEndpoint}/relationships/traverse`, {
759
- method: "POST",
760
- headers: { "Content-Type": "application/json" },
761
- body: JSON.stringify({ entity: validatedEntity, pattern: validatedPattern }),
762
- signal,
763
- timeout
764
- });
765
- if (!response.ok) throw new Error("Failed to traverse graph");
766
- const data = await response.json();
767
- return GraphTraversalResultResponseSchema.parse(data);
768
- },
769
- enabled: Boolean(entity.ns && entity.type && entity.id)
770
- });
771
- }
772
- function useGraphStats() {
773
- const { config, namespace } = useDO();
774
- return useQuery({
775
- queryKey: relationshipsKeys.stats(),
776
- queryFn: async ({ signal }) => {
777
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
778
- const response = await fetchWithTimeout(`${config.apiEndpoint}/relationships/stats?ns=${encodeURIComponent(namespace)}`, {
779
- signal,
780
- timeout
781
- });
782
- if (!response.ok) throw new Error("Failed to fetch graph stats");
783
- const data = await response.json();
784
- return GraphStatsResponseSchema.parse(data);
785
- }
786
- });
787
- }
788
- function useCreateRelationship() {
789
- const { config } = useDO();
790
- const queryClient = useQueryClient();
791
- return useMutation({
792
- mutationFn: async (input) => {
793
- const validatedInput = RelationshipCreateInputSchema.parse(input);
794
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
795
- const response = await fetchWithTimeout(`${config.apiEndpoint}/relationships`, {
796
- method: "POST",
797
- headers: { "Content-Type": "application/json" },
798
- body: JSON.stringify(validatedInput),
799
- timeout
800
- });
801
- if (!response.ok) throw new Error("Failed to create relationship");
802
- const data = await response.json();
803
- return RelationshipResponseSchema.parse(data);
804
- },
805
- onSuccess: () => {
806
- queryClient.invalidateQueries({ queryKey: relationshipsKeys.lists() });
807
- queryClient.invalidateQueries({ queryKey: relationshipsKeys.stats() });
808
- }
809
- });
810
- }
811
- function useDeleteRelationship() {
812
- const { config } = useDO();
813
- const queryClient = useQueryClient();
814
- return useMutation({
815
- mutationFn: async (id) => {
816
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
817
- const response = await fetchWithTimeout(`${config.apiEndpoint}/relationships/${encodeURIComponent(id)}`, {
818
- method: "DELETE",
819
- timeout
820
- });
821
- if (!response.ok) throw new Error("Failed to delete relationship");
822
- },
823
- onSuccess: () => {
824
- queryClient.invalidateQueries({ queryKey: relationshipsKeys.lists() });
825
- queryClient.invalidateQueries({ queryKey: relationshipsKeys.stats() });
826
- }
827
- });
828
- }
829
- function useWorkflows(filter = {}) {
830
- const { config, namespace } = useDO();
831
- const queryKey = useMemo(
832
- () => workflowsKeys.list({ ...filter, ns: filter.ns ?? namespace }),
833
- [JSON.stringify(filter), namespace]
834
- );
835
- return useQuery({
836
- queryKey,
837
- queryFn: async ({ signal }) => {
838
- const validatedFilter = WorkflowFilterSchema.parse(filter);
839
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
840
- const params = new URLSearchParams();
841
- if (validatedFilter.status) params.set("status", validatedFilter.status.join(","));
842
- if (validatedFilter.ns) params.set("ns", validatedFilter.ns);
843
- if (validatedFilter.tags) params.set("tags", validatedFilter.tags.join(","));
844
- if (validatedFilter.triggerType) params.set("triggerType", validatedFilter.triggerType.join(","));
845
- if (validatedFilter.nameSearch) params.set("nameSearch", validatedFilter.nameSearch);
846
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows?${params}`, {
847
- signal,
848
- timeout
849
- });
850
- if (!response.ok) throw new Error("Failed to fetch workflows");
851
- const data = await response.json();
852
- return PaginatedResultResponseSchema(WorkflowResponseSchema).parse(data);
853
- }
854
- });
855
- }
856
- function useWorkflow(id) {
857
- const { config } = useDO();
858
- return useQuery({
859
- queryKey: workflowsKeys.detail(id),
860
- queryFn: async ({ signal }) => {
861
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
862
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows/${encodeURIComponent(id)}`, {
863
- signal,
864
- timeout
865
- });
866
- if (!response.ok) throw new Error("Failed to fetch workflow");
867
- const data = await response.json();
868
- return WorkflowResponseSchema.parse(data);
869
- },
870
- enabled: Boolean(id)
871
- });
872
- }
873
- function useWorkflowExecutions(filter = {}) {
874
- const { config, namespace } = useDO();
875
- const queryKey = useMemo(
876
- () => workflowsKeys.executionsList({ ...filter, ns: filter.ns ?? namespace }),
877
- [JSON.stringify(filter), namespace]
878
- );
879
- return useQuery({
880
- queryKey,
881
- queryFn: async ({ signal }) => {
882
- const validatedFilter = ExecutionFilterSchema.parse(filter);
883
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
884
- const params = new URLSearchParams();
885
- if (validatedFilter.workflowId) params.set("workflowId", validatedFilter.workflowId);
886
- if (validatedFilter.status) params.set("status", validatedFilter.status.join(","));
887
- if (validatedFilter.ns) params.set("ns", validatedFilter.ns);
888
- if (validatedFilter.startedAfter) params.set("startedAfter", validatedFilter.startedAfter.toISOString());
889
- if (validatedFilter.startedBefore) params.set("startedBefore", validatedFilter.startedBefore.toISOString());
890
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows/executions?${params}`, {
891
- signal,
892
- timeout
893
- });
894
- if (!response.ok) throw new Error("Failed to fetch executions");
895
- const data = await response.json();
896
- return PaginatedResultResponseSchema(WorkflowExecutionResponseSchema).parse(data);
897
- }
898
- });
899
- }
900
- function useWorkflowExecution(id) {
901
- const { config } = useDO();
902
- return useQuery({
903
- queryKey: workflowsKeys.execution(id),
904
- queryFn: async ({ signal }) => {
905
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
906
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows/executions/${encodeURIComponent(id)}`, {
907
- signal,
908
- timeout
909
- });
910
- if (!response.ok) throw new Error("Failed to fetch execution");
911
- const data = await response.json();
912
- return WorkflowExecutionResponseSchema.parse(data);
913
- },
914
- enabled: Boolean(id),
915
- refetchInterval: (query) => {
916
- const data = query.state.data;
917
- if (data && (data.status === "running" || data.status === "pending")) {
918
- return 2e3;
919
- }
920
- return false;
921
- }
922
- });
923
- }
924
- function useCreateWorkflow() {
925
- const { config } = useDO();
926
- const queryClient = useQueryClient();
927
- return useMutation({
928
- mutationFn: async (workflow) => {
929
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
930
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows`, {
931
- method: "POST",
932
- headers: { "Content-Type": "application/json" },
933
- body: JSON.stringify(workflow),
934
- timeout
935
- });
936
- if (!response.ok) throw new Error("Failed to create workflow");
937
- const data = await response.json();
938
- return WorkflowResponseSchema.parse(data);
939
- },
940
- onSuccess: () => {
941
- queryClient.invalidateQueries({ queryKey: workflowsKeys.lists() });
942
- }
943
- });
944
- }
945
- function useUpdateWorkflow(id) {
946
- const { config } = useDO();
947
- const queryClient = useQueryClient();
948
- return useMutation({
949
- mutationFn: async (updates) => {
950
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
951
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows/${encodeURIComponent(id)}`, {
952
- method: "PATCH",
953
- headers: { "Content-Type": "application/json" },
954
- body: JSON.stringify(updates),
955
- timeout
956
- });
957
- if (!response.ok) throw new Error("Failed to update workflow");
958
- const data = await response.json();
959
- return WorkflowResponseSchema.parse(data);
960
- },
961
- onSuccess: () => {
962
- queryClient.invalidateQueries({ queryKey: workflowsKeys.detail(id) });
963
- queryClient.invalidateQueries({ queryKey: workflowsKeys.lists() });
964
- }
965
- });
966
- }
967
- function useTriggerWorkflow(id) {
968
- const { config } = useDO();
969
- const queryClient = useQueryClient();
970
- return useMutation({
971
- mutationFn: async (input) => {
972
- const validatedInput = WorkflowTriggerInputSchema.parse(input);
973
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
974
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows/${encodeURIComponent(id)}/trigger`, {
975
- method: "POST",
976
- headers: { "Content-Type": "application/json" },
977
- body: JSON.stringify({ input: validatedInput }),
978
- timeout
979
- });
980
- if (!response.ok) throw new Error("Failed to trigger workflow");
981
- const data = await response.json();
982
- return WorkflowExecutionResponseSchema.parse(data);
983
- },
984
- onSuccess: () => {
985
- queryClient.invalidateQueries({ queryKey: workflowsKeys.executions() });
986
- }
987
- });
988
- }
989
- function useCancelExecution() {
990
- const { config } = useDO();
991
- const queryClient = useQueryClient();
992
- return useMutation({
993
- mutationFn: async (executionId) => {
994
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
995
- const response = await fetchWithTimeout(
996
- `${config.apiEndpoint}/workflows/executions/${encodeURIComponent(executionId)}/cancel`,
997
- { method: "POST", timeout }
998
- );
999
- if (!response.ok) throw new Error("Failed to cancel execution");
1000
- },
1001
- onSuccess: (_, executionId) => {
1002
- queryClient.invalidateQueries({ queryKey: workflowsKeys.execution(executionId) });
1003
- queryClient.invalidateQueries({ queryKey: workflowsKeys.executions() });
1004
- }
1005
- });
1006
- }
1007
- function useDeleteWorkflow() {
1008
- const { config } = useDO();
1009
- const queryClient = useQueryClient();
1010
- return useMutation({
1011
- mutationFn: async (id) => {
1012
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1013
- const response = await fetchWithTimeout(`${config.apiEndpoint}/workflows/${encodeURIComponent(id)}`, {
1014
- method: "DELETE",
1015
- timeout
1016
- });
1017
- if (!response.ok) throw new Error("Failed to delete workflow");
1018
- },
1019
- onSuccess: () => {
1020
- queryClient.invalidateQueries({ queryKey: workflowsKeys.lists() });
1021
- }
1022
- });
1023
- }
1024
- function useAgents(filter = {}) {
1025
- const { config, namespace } = useDO();
1026
- const queryKey = useMemo(
1027
- () => agentsKeys.list({ ...filter, ns: filter.ns ?? namespace }),
1028
- [JSON.stringify(filter), namespace]
1029
- );
1030
- return useQuery({
1031
- queryKey,
1032
- queryFn: async ({ signal }) => {
1033
- const validatedFilter = AgentFilterSchema.parse(filter);
1034
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1035
- const params = new URLSearchParams();
1036
- if (validatedFilter.status) params.set("status", validatedFilter.status.join(","));
1037
- if (validatedFilter.roleCategory) params.set("roleCategory", validatedFilter.roleCategory.join(","));
1038
- if (validatedFilter.workMode) params.set("workMode", validatedFilter.workMode.join(","));
1039
- if (validatedFilter.ns) params.set("ns", validatedFilter.ns);
1040
- if (validatedFilter.nameSearch) params.set("nameSearch", validatedFilter.nameSearch);
1041
- if (validatedFilter.tools) params.set("tools", validatedFilter.tools.join(","));
1042
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents?${params}`, {
1043
- signal,
1044
- timeout
1045
- });
1046
- if (!response.ok) throw new Error("Failed to fetch agents");
1047
- const data = await response.json();
1048
- return PaginatedResultResponseSchema(AgentResponseSchema).parse(data);
1049
- }
1050
- });
1051
- }
1052
- function useAgent(id) {
1053
- const { config } = useDO();
1054
- return useQuery({
1055
- queryKey: agentsKeys.detail(id),
1056
- queryFn: async ({ signal }) => {
1057
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1058
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents/${encodeURIComponent(id)}`, {
1059
- signal,
1060
- timeout
1061
- });
1062
- if (!response.ok) throw new Error("Failed to fetch agent");
1063
- const data = await response.json();
1064
- return AgentResponseSchema.parse(data);
1065
- },
1066
- enabled: Boolean(id)
1067
- });
1068
- }
1069
- function useAgentMetrics(id, periodDays = 30) {
1070
- const { config } = useDO();
1071
- return useQuery({
1072
- queryKey: agentsKeys.metrics(id),
1073
- queryFn: async ({ signal }) => {
1074
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1075
- const response = await fetchWithTimeout(
1076
- `${config.apiEndpoint}/agents/${encodeURIComponent(id)}/metrics?periodDays=${periodDays}`,
1077
- { signal, timeout }
1078
- );
1079
- if (!response.ok) throw new Error("Failed to fetch agent metrics");
1080
- const data = await response.json();
1081
- return AgentMetricsResponseSchema.parse(data);
1082
- },
1083
- enabled: Boolean(id)
1084
- });
1085
- }
1086
- function useAgentExecutions(filter = {}) {
1087
- const { config, namespace } = useDO();
1088
- const queryKey = useMemo(
1089
- () => agentsKeys.executionsList({ ...filter, ns: filter.ns ?? namespace }),
1090
- [JSON.stringify(filter), namespace]
1091
- );
1092
- return useQuery({
1093
- queryKey,
1094
- queryFn: async ({ signal }) => {
1095
- const validatedFilter = AgentExecutionFilterSchema.parse(filter);
1096
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1097
- const params = new URLSearchParams();
1098
- if (validatedFilter.agentId) params.set("agentId", validatedFilter.agentId);
1099
- if (validatedFilter.status) params.set("status", validatedFilter.status.join(","));
1100
- if (validatedFilter.ns) params.set("ns", validatedFilter.ns);
1101
- if (validatedFilter.startedAfter) params.set("startedAfter", validatedFilter.startedAfter.toISOString());
1102
- if (validatedFilter.startedBefore) params.set("startedBefore", validatedFilter.startedBefore.toISOString());
1103
- if (validatedFilter.hasFeedback !== void 0) params.set("hasFeedback", String(validatedFilter.hasFeedback));
1104
- if (validatedFilter.minRating) params.set("minRating", validatedFilter.minRating.toString());
1105
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents/executions?${params}`, {
1106
- signal,
1107
- timeout
1108
- });
1109
- if (!response.ok) throw new Error("Failed to fetch executions");
1110
- const data = await response.json();
1111
- return PaginatedResultResponseSchema(AgentExecutionResponseSchema).parse(data);
1112
- }
1113
- });
1114
- }
1115
- function useAgentExecution(id) {
1116
- const { config } = useDO();
1117
- return useQuery({
1118
- queryKey: agentsKeys.execution(id),
1119
- queryFn: async ({ signal }) => {
1120
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1121
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents/executions/${encodeURIComponent(id)}`, {
1122
- signal,
1123
- timeout
1124
- });
1125
- if (!response.ok) throw new Error("Failed to fetch execution");
1126
- const data = await response.json();
1127
- return AgentExecutionResponseSchema.parse(data);
1128
- },
1129
- enabled: Boolean(id),
1130
- refetchInterval: (query) => {
1131
- const data = query.state.data;
1132
- if (data && (data.status === "running" || data.status === "pending")) {
1133
- return 2e3;
1134
- }
1135
- return false;
1136
- }
1137
- });
1138
- }
1139
- function useCreateAgent() {
1140
- const { config } = useDO();
1141
- const queryClient = useQueryClient();
1142
- return useMutation({
1143
- mutationFn: async (agent) => {
1144
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1145
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents`, {
1146
- method: "POST",
1147
- headers: { "Content-Type": "application/json" },
1148
- body: JSON.stringify(agent),
1149
- timeout
1150
- });
1151
- if (!response.ok) throw new Error("Failed to create agent");
1152
- const data = await response.json();
1153
- return AgentResponseSchema.parse(data);
1154
- },
1155
- onSuccess: () => {
1156
- queryClient.invalidateQueries({ queryKey: agentsKeys.lists() });
1157
- }
1158
- });
1159
- }
1160
- function useUpdateAgent(id) {
1161
- const { config } = useDO();
1162
- const queryClient = useQueryClient();
1163
- return useMutation({
1164
- mutationFn: async (updates) => {
1165
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1166
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents/${encodeURIComponent(id)}`, {
1167
- method: "PATCH",
1168
- headers: { "Content-Type": "application/json" },
1169
- body: JSON.stringify(updates),
1170
- timeout
1171
- });
1172
- if (!response.ok) throw new Error("Failed to update agent");
1173
- const data = await response.json();
1174
- return AgentResponseSchema.parse(data);
1175
- },
1176
- onSuccess: () => {
1177
- queryClient.invalidateQueries({ queryKey: agentsKeys.detail(id) });
1178
- queryClient.invalidateQueries({ queryKey: agentsKeys.lists() });
1179
- }
1180
- });
1181
- }
1182
- function useExecuteAgent(id) {
1183
- const { config } = useDO();
1184
- const queryClient = useQueryClient();
1185
- return useMutation({
1186
- mutationFn: async (input) => {
1187
- const validatedInput = AgentExecuteInputSchema.parse(input);
1188
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1189
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents/${encodeURIComponent(id)}/execute`, {
1190
- method: "POST",
1191
- headers: { "Content-Type": "application/json" },
1192
- body: JSON.stringify(validatedInput),
1193
- timeout
1194
- });
1195
- if (!response.ok) throw new Error("Failed to execute agent");
1196
- const data = await response.json();
1197
- return AgentExecutionResponseSchema.parse(data);
1198
- },
1199
- onSuccess: () => {
1200
- queryClient.invalidateQueries({ queryKey: agentsKeys.executions() });
1201
- }
1202
- });
1203
- }
1204
- function useSubmitAgentFeedback(executionId) {
1205
- const { config } = useDO();
1206
- const queryClient = useQueryClient();
1207
- return useMutation({
1208
- mutationFn: async (feedback) => {
1209
- const validatedFeedback = AgentFeedbackInputSchema.parse(feedback);
1210
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1211
- const response = await fetchWithTimeout(
1212
- `${config.apiEndpoint}/agents/executions/${encodeURIComponent(executionId)}/feedback`,
1213
- {
1214
- method: "POST",
1215
- headers: { "Content-Type": "application/json" },
1216
- body: JSON.stringify(validatedFeedback),
1217
- timeout
1218
- }
1219
- );
1220
- if (!response.ok) throw new Error("Failed to submit feedback");
1221
- },
1222
- onSuccess: () => {
1223
- queryClient.invalidateQueries({ queryKey: agentsKeys.execution(executionId) });
1224
- }
1225
- });
1226
- }
1227
- function useDeleteAgent() {
1228
- const { config } = useDO();
1229
- const queryClient = useQueryClient();
1230
- return useMutation({
1231
- mutationFn: async (id) => {
1232
- const timeout = config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT;
1233
- const response = await fetchWithTimeout(`${config.apiEndpoint}/agents/${encodeURIComponent(id)}`, {
1234
- method: "DELETE",
1235
- timeout
1236
- });
1237
- if (!response.ok) throw new Error("Failed to delete agent");
1238
- },
1239
- onSuccess: () => {
1240
- queryClient.invalidateQueries({ queryKey: agentsKeys.lists() });
1241
- }
1242
- });
1243
- }
1244
- var DOContext = React2.createContext({
1245
- dataProvider: null,
1246
- isDOEnabled: false,
1247
- ns: null
1248
- });
1249
- DOContext.displayName = "DOContext";
1250
- function DO({
1251
- children,
1252
- ns,
1253
- dataProvider: providedDataProvider,
1254
- dotdoConfig,
1255
- adminConfig,
1256
- theme = "system",
1257
- basename = "",
1258
- title = "Admin",
1259
- logo
1260
- }) {
1261
- const dataProvider = React2.useMemo(() => {
1262
- if (providedDataProvider) {
1263
- return providedDataProvider;
1264
- }
1265
- if (ns) {
1266
- return DotdoDataProvider({
1267
- ns,
1268
- ...dotdoConfig
1269
- });
1270
- }
1271
- return null;
1272
- }, [ns, providedDataProvider, dotdoConfig]);
1273
- const doContextValue = React2.useMemo(
1274
- () => ({
1275
- dataProvider,
1276
- isDOEnabled: !!dataProvider,
1277
- ns: ns ?? null
1278
- }),
1279
- [dataProvider, ns]
1280
- );
1281
- const content = /* @__PURE__ */ jsx(
1282
- AdminProvider,
1283
- {
1284
- theme,
1285
- basename,
1286
- title,
1287
- logo,
1288
- ...adminConfig,
1289
- children
1290
- }
1291
- );
1292
- if (dataProvider) {
1293
- return /* @__PURE__ */ jsx(DOContext.Provider, { value: doContextValue, children: /* @__PURE__ */ jsx(AdminProvider$1, { dataProvider, children: content }) });
1294
- }
1295
- return /* @__PURE__ */ jsx(DOContext.Provider, { value: doContextValue, children: content });
1296
- }
1297
- DO.displayName = "DO";
1298
- function useDOContext() {
1299
- return React2.useContext(DOContext);
1300
- }
1301
- function useIsDOEnabled() {
1302
- const { isDOEnabled } = useDOContext();
1303
- return isDOEnabled;
1304
- }
1305
- function useDOResource(config) {
1306
- const {
1307
- showToasts = true,
1308
- transform,
1309
- emptyMessage = "No items found",
1310
- ...baseConfig
1311
- } = config;
1312
- const baseResult = useResource(baseConfig);
1313
- const [lastFetchTime, setLastFetchTime] = React2.useState(null);
1314
- const staleThreshold = 3e4;
1315
- React2.useEffect(() => {
1316
- if (!baseResult.isLoading && baseResult.data.length > 0) {
1317
- setLastFetchTime(Date.now());
1318
- }
1319
- }, [baseResult.isLoading, baseResult.data]);
1320
- const transformedData = React2.useMemo(() => {
1321
- if (!transform) return baseResult.data;
1322
- return transform(baseResult.data);
1323
- }, [baseResult.data, transform]);
1324
- const isEmpty = !baseResult.isLoading && transformedData.length === 0;
1325
- const isStale = React2.useMemo(() => {
1326
- if (!lastFetchTime) return false;
1327
- return Date.now() - lastFetchTime > staleThreshold;
1328
- }, [lastFetchTime]);
1329
- const getByIndex = React2.useCallback(
1330
- (index) => {
1331
- return transformedData[index];
1332
- },
1333
- [transformedData]
1334
- );
1335
- return React2.useMemo(
1336
- () => ({
1337
- ...baseResult,
1338
- data: transformedData,
1339
- isEmpty,
1340
- emptyMessage,
1341
- isStale,
1342
- getByIndex
1343
- }),
1344
- [baseResult, transformedData, isEmpty, emptyMessage, isStale, getByIndex]
1345
- );
1346
- }
1347
- var useDOAdmin = useDOResource;
1348
-
1349
- export { APIError, DO, NetworkError, SyncError, ValidationError, agentsKeys, createRPCClient, isAPIError, isNetworkError, isSyncError, isValidationError, relationshipsKeys, thingsKeys, useAgent, useAgentExecution, useAgentExecutions, useAgentMetrics, useAgents, useCancelExecution, useCreateAgent, useCreateRelationship, useCreateThing, useCreateWorkflow, useDOAdmin, useDOContext, useDOResource, useDeleteAgent, useDeleteRelationship, useDeleteThing, useDeleteWorkflow, useEntityRelationships, useExecuteAgent, useGraphStats, useGraphTraversal, useIsDOEnabled, useRPCClient, useRelationships, useSubmitAgentFeedback, useThing, useThingVersions, useThings, useTriggerWorkflow, useTypeStats, useUpdateAgent, useUpdateThing, useUpdateWorkflow, useWorkflow, useWorkflowExecution, useWorkflowExecutions, useWorkflows, workflowsKeys };
1350
- //# sourceMappingURL=chunk-EEDMN7UF.js.map
1351
- //# sourceMappingURL=chunk-EEDMN7UF.js.map