@dxos/functions 0.8.4-main.b97322e → 0.8.4-main.c4373fc

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 (145) hide show
  1. package/dist/lib/browser/bundler/index.mjs +61 -39
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/chunk-J5LGTIGS.mjs +10 -0
  4. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +7 -0
  5. package/dist/lib/browser/chunk-LKYT2SAL.mjs +665 -0
  6. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +7 -0
  7. package/dist/lib/browser/edge/index.mjs +22 -8
  8. package/dist/lib/browser/edge/index.mjs.map +3 -3
  9. package/dist/lib/browser/index.mjs +1035 -143
  10. package/dist/lib/browser/index.mjs.map +4 -4
  11. package/dist/lib/browser/meta.json +1 -1
  12. package/dist/lib/browser/testing/index.mjs +81 -41
  13. package/dist/lib/browser/testing/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/bundler/index.mjs +60 -39
  15. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  16. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +11 -0
  17. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +667 -0
  19. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +7 -0
  20. package/dist/lib/node-esm/edge/index.mjs +21 -8
  21. package/dist/lib/node-esm/edge/index.mjs.map +3 -3
  22. package/dist/lib/node-esm/index.mjs +1035 -143
  23. package/dist/lib/node-esm/index.mjs.map +4 -4
  24. package/dist/lib/node-esm/meta.json +1 -1
  25. package/dist/lib/node-esm/testing/index.mjs +81 -41
  26. package/dist/lib/node-esm/testing/index.mjs.map +3 -3
  27. package/dist/types/src/bundler/bundler.d.ts +11 -12
  28. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  29. package/dist/types/src/edge/functions.d.ts +3 -2
  30. package/dist/types/src/edge/functions.d.ts.map +1 -1
  31. package/dist/types/src/errors.d.ts +89 -20
  32. package/dist/types/src/errors.d.ts.map +1 -1
  33. package/dist/types/src/examples/fib.d.ts +7 -0
  34. package/dist/types/src/examples/fib.d.ts.map +1 -0
  35. package/dist/types/src/examples/index.d.ts +4 -0
  36. package/dist/types/src/examples/index.d.ts.map +1 -0
  37. package/dist/types/src/examples/reply.d.ts +3 -0
  38. package/dist/types/src/examples/reply.d.ts.map +1 -0
  39. package/dist/types/src/examples/sleep.d.ts +5 -0
  40. package/dist/types/src/examples/sleep.d.ts.map +1 -0
  41. package/dist/types/src/executor/executor.d.ts +7 -1
  42. package/dist/types/src/executor/executor.d.ts.map +1 -1
  43. package/dist/types/src/handler.d.ts +56 -9
  44. package/dist/types/src/handler.d.ts.map +1 -1
  45. package/dist/types/src/index.d.ts +3 -1
  46. package/dist/types/src/index.d.ts.map +1 -1
  47. package/dist/types/src/schema.d.ts +11 -6
  48. package/dist/types/src/schema.d.ts.map +1 -1
  49. package/dist/types/src/services/credentials.d.ts +20 -3
  50. package/dist/types/src/services/credentials.d.ts.map +1 -1
  51. package/dist/types/src/services/database.d.ts +44 -6
  52. package/dist/types/src/services/database.d.ts.map +1 -1
  53. package/dist/types/src/services/event-logger.d.ts +68 -30
  54. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  55. package/dist/types/src/services/function-invocation-service.d.ts +28 -0
  56. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  57. package/dist/types/src/services/function-invocation-service.test.d.ts +2 -0
  58. package/dist/types/src/services/function-invocation-service.test.d.ts.map +1 -0
  59. package/dist/types/src/services/index.d.ts +5 -3
  60. package/dist/types/src/services/index.d.ts.map +1 -1
  61. package/dist/types/src/services/local-function-execution.d.ts +34 -0
  62. package/dist/types/src/services/local-function-execution.d.ts.map +1 -0
  63. package/dist/types/src/services/queues.d.ts +23 -6
  64. package/dist/types/src/services/queues.d.ts.map +1 -1
  65. package/dist/types/src/services/remote-function-execution-service.d.ts +22 -0
  66. package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -0
  67. package/dist/types/src/services/service-container.d.ts +7 -6
  68. package/dist/types/src/services/service-container.d.ts.map +1 -1
  69. package/dist/types/src/services/service-registry.d.ts +4 -2
  70. package/dist/types/src/services/service-registry.d.ts.map +1 -1
  71. package/dist/types/src/services/tracing.d.ts +39 -5
  72. package/dist/types/src/services/tracing.d.ts.map +1 -1
  73. package/dist/types/src/testing/layer.d.ts +11 -3
  74. package/dist/types/src/testing/layer.d.ts.map +1 -1
  75. package/dist/types/src/testing/logger.d.ts +4 -4
  76. package/dist/types/src/testing/logger.d.ts.map +1 -1
  77. package/dist/types/src/testing/persist-database.test.d.ts +2 -0
  78. package/dist/types/src/testing/persist-database.test.d.ts.map +1 -0
  79. package/dist/types/src/testing/services.d.ts +7 -18
  80. package/dist/types/src/testing/services.d.ts.map +1 -1
  81. package/dist/types/src/trace.d.ts +21 -23
  82. package/dist/types/src/trace.d.ts.map +1 -1
  83. package/dist/types/src/triggers/index.d.ts +4 -0
  84. package/dist/types/src/triggers/index.d.ts.map +1 -0
  85. package/dist/types/src/triggers/input-builder.d.ts +3 -0
  86. package/dist/types/src/triggers/input-builder.d.ts.map +1 -0
  87. package/dist/types/src/triggers/invocation-tracer.d.ts +37 -0
  88. package/dist/types/src/triggers/invocation-tracer.d.ts.map +1 -0
  89. package/dist/types/src/triggers/trigger-dispatcher.d.ts +78 -0
  90. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +1 -0
  91. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +2 -0
  92. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +1 -0
  93. package/dist/types/src/triggers/trigger-state-store.d.ts +28 -0
  94. package/dist/types/src/triggers/trigger-state-store.d.ts.map +1 -0
  95. package/dist/types/src/types.d.ts +71 -252
  96. package/dist/types/src/types.d.ts.map +1 -1
  97. package/dist/types/src/url.d.ts +11 -7
  98. package/dist/types/src/url.d.ts.map +1 -1
  99. package/dist/types/tsconfig.tsbuildinfo +1 -1
  100. package/package.json +38 -42
  101. package/src/bundler/bundler.test.ts +8 -9
  102. package/src/bundler/bundler.ts +38 -35
  103. package/src/edge/functions.ts +8 -5
  104. package/src/errors.ts +13 -5
  105. package/src/examples/fib.ts +32 -0
  106. package/src/examples/index.ts +7 -0
  107. package/src/examples/reply.ts +21 -0
  108. package/src/examples/sleep.ts +24 -0
  109. package/src/executor/executor.ts +14 -10
  110. package/src/handler.ts +125 -20
  111. package/src/index.ts +3 -3
  112. package/src/schema.ts +16 -2
  113. package/src/services/credentials.ts +86 -3
  114. package/src/services/database.ts +123 -18
  115. package/src/services/event-logger.ts +71 -37
  116. package/src/services/function-invocation-service.test.ts +81 -0
  117. package/src/services/function-invocation-service.ts +84 -0
  118. package/src/services/index.ts +5 -3
  119. package/src/services/local-function-execution.ts +153 -0
  120. package/src/services/queues.ts +39 -10
  121. package/src/services/remote-function-execution-service.ts +63 -0
  122. package/src/services/service-container.ts +13 -11
  123. package/src/services/service-registry.test.ts +4 -1
  124. package/src/services/service-registry.ts +11 -4
  125. package/src/services/tracing.ts +112 -11
  126. package/src/testing/layer.ts +87 -4
  127. package/src/testing/logger.ts +5 -4
  128. package/src/testing/persist-database.test.ts +87 -0
  129. package/src/testing/services.ts +11 -64
  130. package/src/trace.ts +19 -21
  131. package/src/triggers/index.ts +7 -0
  132. package/src/triggers/input-builder.ts +35 -0
  133. package/src/triggers/invocation-tracer.ts +101 -0
  134. package/src/triggers/trigger-dispatcher.test.ts +665 -0
  135. package/src/triggers/trigger-dispatcher.ts +533 -0
  136. package/src/triggers/trigger-state-store.ts +61 -0
  137. package/src/types.ts +44 -37
  138. package/src/url.ts +14 -11
  139. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  140. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  141. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  142. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  143. package/dist/types/src/services/function-call-service.d.ts +0 -16
  144. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  145. package/src/services/function-call-service.ts +0 -64
@@ -2,41 +2,142 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Effect } from 'effect';
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
6
8
 
7
9
  import { AgentStatus } from '@dxos/ai';
8
10
  import { Obj } from '@dxos/echo';
9
- import type { AnyEchoObject } from '@dxos/echo-schema';
11
+ import type { ObjectId } from '@dxos/echo/internal';
12
+ import type { Queue } from '@dxos/echo-db';
13
+ import { log } from '@dxos/log';
14
+ import { DataType } from '@dxos/schema';
10
15
 
11
16
  /**
12
17
  * Provides a way for compute primitives (functions, workflows, tools)
13
18
  * to emit an execution trace as a series of structured ECHO objects.
14
19
  */
15
- export class TracingService extends Context.Tag('TracingService')<
20
+ export class TracingService extends Context.Tag('@dxos/functions/TracingService')<
16
21
  TracingService,
17
22
  {
23
+ /**
24
+ * Gets the parent message ID.
25
+ */
26
+ getTraceContext: () => TracingService.TraceContext;
27
+
18
28
  /**
19
29
  * Write an event to the tracing queue.
20
30
  * @param event - The event to write. Must be an a typed object.
21
31
  */
22
- write(event: AnyEchoObject): void;
32
+ write: (event: Obj.Any) => void;
23
33
  }
24
34
  >() {
25
- static noop: Context.Tag.Service<TracingService> = { write: () => {} };
35
+ static noop: Context.Tag.Service<TracingService> = { write: () => {}, getTraceContext: () => ({}) };
36
+
37
+ static layerNoop = Layer.succeed(TracingService, TracingService.noop);
26
38
 
27
39
  static console: Context.Tag.Service<TracingService> = {
28
40
  write: (event) => {
29
- // eslint-disable-next-line no-console
30
41
  console.log(event);
31
42
  },
43
+ getTraceContext: () => ({}),
32
44
  };
33
45
 
46
+ static layerConsole = Layer.succeed(TracingService, TracingService.console);
47
+
48
+ static layerLogInfo = () =>
49
+ Layer.succeed(TracingService, {
50
+ write: (event) => {
51
+ if (Obj.instanceOf(AgentStatus, event)) {
52
+ log.info('status', { message: event.message });
53
+ }
54
+ },
55
+ getTraceContext: () => ({}),
56
+ });
57
+
58
+ /**
59
+ * Creates a TracingService layer that emits events to the parent tracing service.
60
+ */
61
+ static layerSubframe = (mapContext: (currentContext: TracingService.TraceContext) => TracingService.TraceContext) =>
62
+ Layer.effect(
63
+ TracingService,
64
+ Effect.gen(function* () {
65
+ const tracing = yield* TracingService;
66
+ const context = mapContext(tracing.getTraceContext());
67
+ return {
68
+ write: (event) => tracing.write(event),
69
+ getTraceContext: () => context,
70
+ };
71
+ }),
72
+ );
73
+
74
+ static layerQueue = (queue: Queue) =>
75
+ Layer.effect(
76
+ TracingService,
77
+ Effect.gen(function* () {
78
+ // TODO(dmaretskyi): Batching.
79
+ return {
80
+ write: (event) => queue.append([event]),
81
+ getTraceContext: () => ({
82
+ debugInfo: {
83
+ queue: queue.dxn.toString(),
84
+ },
85
+ }),
86
+ };
87
+ }),
88
+ );
89
+
34
90
  /**
35
91
  * Emit the current human-readable execution status.
36
92
  */
37
- static emitStatus: (data: Obj.MakeProps<typeof AgentStatus>) => Effect.Effect<unknown, never, void> =
38
- Effect.fnUntraced(function* (data) {
39
- const tracing = yield* TracingService;
40
- tracing.write(Obj.make(AgentStatus, data));
41
- });
93
+ static emitStatus: (
94
+ data: Omit<Obj.MakeProps<typeof AgentStatus>, 'created'>,
95
+ ) => Effect.Effect<void, never, TracingService> = Effect.fnUntraced(function* (data) {
96
+ const tracing = yield* TracingService;
97
+ tracing.write(
98
+ Obj.make(AgentStatus, {
99
+ parentMessage: tracing.getTraceContext().parentMessage,
100
+ toolCallId: tracing.getTraceContext().toolCallId,
101
+ created: new Date().toISOString(),
102
+ ...data,
103
+ }),
104
+ );
105
+ });
106
+
107
+ static emitConverationMessage: (
108
+ data: Obj.MakeProps<typeof DataType.Message>,
109
+ ) => Effect.Effect<void, never, TracingService> = Effect.fnUntraced(function* (data) {
110
+ const tracing = yield* TracingService;
111
+ tracing.write(
112
+ Obj.make(DataType.Message, {
113
+ parentMessage: tracing.getTraceContext().parentMessage,
114
+ ...data,
115
+ properties: {
116
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
117
+ ...data.properties,
118
+ },
119
+ }),
120
+ );
121
+ });
42
122
  }
123
+
124
+ export namespace TracingService {
125
+ export interface TraceContext {
126
+ /**
127
+ * If this thread sprung from a tool call, this is the ID of the message containing the tool call.
128
+ */
129
+ parentMessage?: ObjectId;
130
+
131
+ /**
132
+ * If the current thread is a byproduct of a tool call, this is the ID of the tool call.
133
+ */
134
+ toolCallId?: string;
135
+
136
+ debugInfo?: unknown;
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Goes into {@link DataType.Message['properties']}
142
+ */
143
+ export const MESSAGE_PROPERTY_TOOL_CALL_ID = 'toolCallId' as const;
@@ -2,27 +2,110 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context, Effect, Layer } from 'effect';
6
- import type { Schema } from 'effect';
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
8
+ import type * as Schema from 'effect/Schema';
7
9
 
10
+ import type { EchoDatabaseImpl, QueueFactory } from '@dxos/echo-db';
8
11
  import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
12
  import type { EchoHostIndexingConfig } from '@dxos/echo-pipeline';
10
13
  import { accuireReleaseResource } from '@dxos/effect';
14
+ import { PublicKey } from '@dxos/keys';
15
+ import type { LevelDB } from '@dxos/kv-store';
16
+ import { createTestLevel } from '@dxos/kv-store/testing';
17
+ import { log } from '@dxos/log';
11
18
 
12
19
  import { DatabaseService, QueueService } from '../services';
13
20
 
14
21
  const testBuilder = accuireReleaseResource(() => new EchoTestBuilder());
15
22
 
23
+ export const testStoragePath = ({ name = PublicKey.random().toHex() }: { name?: string }) => {
24
+ return `/tmp/dxos-${name}`;
25
+ };
26
+
16
27
  export type TestDatabaseOptions = {
17
28
  indexing?: Partial<EchoHostIndexingConfig>;
18
29
  types?: Schema.Schema.AnyNoContext[];
30
+ spaceKey?: PublicKey;
31
+ storagePath?: string;
32
+ onInit?: () => Effect.Effect<void, never, DatabaseService | QueueService>;
19
33
  };
20
34
 
21
- export const TestDatabaseLayer = ({ indexing, types }: TestDatabaseOptions = {}) =>
35
+ export const TestDatabaseLayer = ({ indexing, types, spaceKey, storagePath, onInit }: TestDatabaseOptions = {}) =>
22
36
  Layer.scopedContext(
23
37
  Effect.gen(function* () {
24
38
  const builder = yield* testBuilder;
25
- const { db, queues } = yield* Effect.promise(() => builder.createDatabase({ indexing, types }));
39
+
40
+ let kv: LevelDB | undefined;
41
+ if (storagePath) {
42
+ kv = createTestLevel(storagePath);
43
+ yield* Effect.promise(() => kv!.open());
44
+ // const keyCount = yield* Effect.promise(async () => (await kv!.iterator({ values: false }).all()).length);
45
+ // log.info('opened test db', { storagePath, keyCount });
46
+ }
47
+ const peer = yield* Effect.promise(() => builder.createPeer({ indexing, types, kv }));
48
+
49
+ let db: EchoDatabaseImpl | undefined;
50
+ let queues: QueueFactory | undefined;
51
+
52
+ if (storagePath) {
53
+ const testMetadata = yield* Effect.promise(async () => {
54
+ try {
55
+ return await kv!.get('test-metadata', { valueEncoding: 'json' });
56
+ } catch (e) {
57
+ if ((e as any).code === 'LEVEL_NOT_FOUND') {
58
+ return undefined;
59
+ }
60
+ throw e;
61
+ }
62
+ });
63
+ log('starting persistant test db', { storagePath, testMetadata });
64
+ if (!testMetadata) {
65
+ const key = spaceKey ?? PublicKey.random();
66
+ db = yield* Effect.promise(() => peer.createDatabase(key));
67
+ queues = peer.client.constructQueueFactory(db.spaceId);
68
+
69
+ yield* Effect.promise(() =>
70
+ kv!.put('test-metadata', { key: key.toHex(), rootUrl: db!.rootUrl }, { valueEncoding: 'json' }),
71
+ );
72
+
73
+ if (onInit) {
74
+ yield* onInit().pipe(
75
+ Effect.provideService(DatabaseService, DatabaseService.make(db)),
76
+ Effect.provideService(QueueService, QueueService.make(queues, undefined)),
77
+ );
78
+ }
79
+ } else {
80
+ const key = PublicKey.from((testMetadata as any).key);
81
+ const rootUrl = (testMetadata as any).rootUrl;
82
+ db = yield* Effect.promise(() => peer.openDatabase(key, rootUrl));
83
+ queues = peer.client.constructQueueFactory(db.spaceId);
84
+ }
85
+ } else {
86
+ db = yield* Effect.promise(() => peer.createDatabase(spaceKey));
87
+ queues = peer.client.constructQueueFactory(db.spaceId);
88
+ if (onInit) {
89
+ yield* onInit().pipe(
90
+ Effect.provideService(DatabaseService, DatabaseService.make(db)),
91
+ Effect.provideService(QueueService, QueueService.make(queues, undefined)),
92
+ );
93
+ }
94
+ }
95
+
96
+ yield* Effect.addFinalizer(() =>
97
+ Effect.promise(async () => {
98
+ if (kv) {
99
+ // {
100
+ // const keyCount = (await kv.iterator({ values: false }).all()).length;
101
+ // log.info('closing persistant test db', { storagePath, keyCount });
102
+ // }
103
+
104
+ await kv.close();
105
+ }
106
+ }),
107
+ );
108
+
26
109
  return Context.mergeAll(
27
110
  Context.make(DatabaseService, DatabaseService.make(db)),
28
111
  Context.make(QueueService, QueueService.make(queues, undefined)),
@@ -2,15 +2,16 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Effect, type Context } from 'effect';
5
+ import type * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
6
7
 
7
8
  import { LogLevel } from '@dxos/log';
8
9
 
9
- import { type EventLogger, createEventLogger } from '../services';
10
+ import { type ComputeEventLogger, createEventLogger } from '../services';
10
11
 
11
- export const noopLogger: Context.Tag.Service<EventLogger> = {
12
+ export const noopLogger: Context.Tag.Service<ComputeEventLogger> = {
12
13
  log: () => Effect.succeed(undefined),
13
14
  nodeId: undefined,
14
15
  };
15
16
 
16
- export const consoleLogger: Context.Tag.Service<EventLogger> = createEventLogger(LogLevel.INFO);
17
+ export const consoleLogger: Context.Tag.Service<ComputeEventLogger> = createEventLogger(LogLevel.INFO);
@@ -0,0 +1,87 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { describe, expect, it } from '@effect/vitest';
6
+ import * as Effect from 'effect/Effect';
7
+
8
+ import { Filter, Obj, Query, Type } from '@dxos/echo';
9
+ import { DataType } from '@dxos/schema';
10
+
11
+ import { DatabaseService } from '../services';
12
+
13
+ import { TestDatabaseLayer, testStoragePath } from './layer';
14
+
15
+ describe('TestDatabaseLayer', { timeout: 600_000 }, () => {
16
+ it.effect(
17
+ 'persist database to disk',
18
+ Effect.fnUntraced(function* (_) {
19
+ const DbLayer = TestDatabaseLayer({
20
+ storagePath: testStoragePath({ name: `feed-test-${Date.now()}` }),
21
+ });
22
+
23
+ yield* Effect.gen(function* () {
24
+ yield* DatabaseService.add(Obj.make(Type.Expando, { label: 'test' }));
25
+ yield* DatabaseService.flush({ indexes: true });
26
+ }).pipe(Effect.provide(DbLayer));
27
+
28
+ yield* Effect.gen(function* () {
29
+ const { objects } = yield* DatabaseService.runQuery(Query.select(Filter.everything()));
30
+ expect(objects[0]?.label).toEqual('test');
31
+ }).pipe(Effect.provide(DbLayer));
32
+ }),
33
+ );
34
+
35
+ it.effect(
36
+ 'reload database -- save index before restart',
37
+ Effect.fnUntraced(function* (_) {
38
+ const NUM_OBJECTS = 500;
39
+ const DbLayer = TestDatabaseLayer({
40
+ types: [DataType.Person],
41
+ storagePath: testStoragePath({ name: `reload-test-${Date.now()}` }),
42
+ });
43
+
44
+ yield* Effect.gen(function* () {
45
+ for (let i = 0; i < NUM_OBJECTS; i++) {
46
+ yield* DatabaseService.add(Obj.make(DataType.Person, { nickname: `Person ${i}` }));
47
+ }
48
+ yield* DatabaseService.flush({ indexes: true });
49
+ }).pipe(Effect.provide(DbLayer));
50
+
51
+ yield* Effect.gen(function* () {
52
+ const { objects } = yield* DatabaseService.runQuery(Query.select(Filter.type(DataType.Person)));
53
+ expect(objects.length).toEqual(NUM_OBJECTS);
54
+ }).pipe(Effect.provide(DbLayer));
55
+ }),
56
+ );
57
+
58
+ it.effect.skip(
59
+ 'reload database -- save index before restart [manual]',
60
+ Effect.fnUntraced(
61
+ function* (_) {
62
+ const NUM_OBJECTS = 500;
63
+
64
+ {
65
+ const { objects } = yield* DatabaseService.runQuery(Query.select(Filter.type(DataType.Person)));
66
+ console.log({ count: objects.length });
67
+ }
68
+
69
+ for (let i = 0; i < NUM_OBJECTS; i++) {
70
+ yield* DatabaseService.add(Obj.make(DataType.Person, { nickname: `Person ${i}` }));
71
+ }
72
+ yield* DatabaseService.flush({ indexes: true });
73
+
74
+ {
75
+ const { objects } = yield* DatabaseService.runQuery(Query.select(Filter.type(DataType.Person)));
76
+ console.log({ count: objects.length });
77
+ }
78
+ },
79
+ Effect.provide(
80
+ TestDatabaseLayer({
81
+ types: [DataType.Person],
82
+ storagePath: testStoragePath({ name: `reload-test` }),
83
+ }),
84
+ ),
85
+ ),
86
+ );
87
+ });
@@ -2,26 +2,25 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type Context } from 'effect';
5
+ import type * as Context from 'effect/Context';
6
6
 
7
- import { AiService, type AiServiceClient, type AiServiceEdgeClientOptions, EdgeAiServiceClient } from '@dxos/ai';
8
- import { AI_SERVICE_ENDPOINT, createTestAiServiceClient } from '@dxos/ai/testing';
9
7
  import type { Space } from '@dxos/client/echo';
10
8
  import type { EchoDatabase, QueueFactory } from '@dxos/echo-db';
11
9
  import { assertArgument } from '@dxos/invariant';
12
10
 
13
- import { consoleLogger, noopLogger } from './logger';
14
11
  import {
12
+ type ComputeEventLogger,
15
13
  ConfiguredCredentialsService,
16
14
  type CredentialsService,
17
15
  DatabaseService,
18
- type EventLogger,
19
16
  QueueService,
20
17
  ServiceContainer,
21
18
  type ServiceCredential,
22
19
  type TracingService,
23
20
  } from '../services';
24
21
 
22
+ import { consoleLogger, noopLogger } from './logger';
23
+
25
24
  // TODO(burdon): Factor out.
26
25
  export type OneOf<T> = {
27
26
  [K in keyof T]: { [P in K]: T[P] } & { [P in Exclude<keyof T, K>]?: never };
@@ -33,23 +32,7 @@ export type TestServiceOptions = {
33
32
  /**
34
33
  * AI service configuration.
35
34
  */
36
- ai?: OneOf<{
37
- /**
38
- * Custom AI service client.
39
- */
40
- client?: AiServiceClient;
41
-
42
- /**
43
- * Edge AI service at specified endpoint.
44
- */
45
- endpoint?: AiServiceEdgeClientOptions['endpoint'];
46
-
47
- /**
48
- * Predefined AI service configuration.
49
- */
50
- // TODO(burdon): 'dev' and 'edge' are redundant with providing an endpoint.
51
- provider?: AiServiceProvider;
52
- }>;
35
+ ai?: any;
53
36
 
54
37
  /**
55
38
  * Credentials service configuration.
@@ -82,7 +65,7 @@ export type TestServiceOptions = {
82
65
  */
83
66
  logging?: {
84
67
  enabled?: boolean;
85
- logger?: Context.Tag.Service<EventLogger>;
68
+ logger?: Context.Tag.Service<ComputeEventLogger>;
86
69
  };
87
70
 
88
71
  /**
@@ -95,6 +78,9 @@ export type TestServiceOptions = {
95
78
  };
96
79
  };
97
80
 
81
+ /**
82
+ * @deprecated
83
+ */
98
84
  export const createTestServices = ({
99
85
  ai,
100
86
  credentials,
@@ -104,10 +90,10 @@ export const createTestServices = ({
104
90
  space,
105
91
  tracing,
106
92
  }: TestServiceOptions = {}): ServiceContainer => {
107
- assertArgument(!(!!space && (!!db || !!queues)), 'space can be provided only if db and queues are not');
93
+ assertArgument(!(!!space && (!!db || !!queues)), 'space', 'space can be provided only if db and queues are not');
108
94
 
109
95
  return new ServiceContainer().setServices({
110
- ai: createAiService(ai),
96
+ // ai: createAiService(ai),
111
97
  credentials: createCredentialsService(credentials),
112
98
  database: space || db ? DatabaseService.make(space?.db || db!) : undefined,
113
99
  eventLogger: (logging?.logger ?? logging?.enabled) ? consoleLogger : noopLogger,
@@ -116,45 +102,6 @@ export const createTestServices = ({
116
102
  });
117
103
  };
118
104
 
119
- // TODO(burdon): Enable model configuration.
120
- const createAiService = (ai: TestServiceOptions['ai']): Context.Tag.Service<AiService> | undefined => {
121
- if (ai?.client != null) {
122
- return AiService.make(ai.client);
123
- }
124
-
125
- if (ai?.endpoint != null) {
126
- return AiService.make(new EdgeAiServiceClient({ endpoint: ai.endpoint }));
127
- }
128
-
129
- switch (ai?.provider) {
130
- case 'dev':
131
- return AiService.make(
132
- new EdgeAiServiceClient({
133
- endpoint: AI_SERVICE_ENDPOINT.LOCAL,
134
- defaultGenerationOptions: {
135
- model: '@anthropic/claude-3-5-sonnet-20241022',
136
- },
137
- }),
138
- );
139
-
140
- case 'edge':
141
- return AiService.make(
142
- new EdgeAiServiceClient({
143
- endpoint: AI_SERVICE_ENDPOINT.REMOTE,
144
- defaultGenerationOptions: {
145
- model: '@anthropic/claude-3-5-sonnet-20241022',
146
- },
147
- }),
148
- );
149
-
150
- case 'ollama':
151
- return AiService.make(createTestAiServiceClient());
152
-
153
- case 'lmstudio':
154
- throw new Error('LMStudio is not supported');
155
- }
156
- };
157
-
158
105
  const createCredentialsService = (
159
106
  credentials: TestServiceOptions['credentials'] | undefined,
160
107
  ): Context.Tag.Service<CredentialsService> | undefined => {
package/src/trace.ts CHANGED
@@ -2,14 +2,14 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Schema } from 'effect';
5
+ import * as Schema from 'effect/Schema';
6
6
 
7
- import { Type, type Ref } from '@dxos/echo';
7
+ import { type Ref, Type } from '@dxos/echo';
8
+ import { ObjectId } from '@dxos/echo/internal';
8
9
  import { Queue } from '@dxos/echo-db';
9
- import { ObjectId } from '@dxos/echo-schema';
10
10
  import { log } from '@dxos/log';
11
11
 
12
- import { FunctionTrigger, type FunctionTriggerType } from './types';
12
+ import { FunctionTrigger } from './types';
13
13
 
14
14
  export enum InvocationOutcome {
15
15
  SUCCESS = 'success',
@@ -24,7 +24,7 @@ export enum InvocationTraceEventType {
24
24
  }
25
25
 
26
26
  export const TraceEventException = Schema.Struct({
27
- timestampMs: Schema.Number,
27
+ timestamp: Schema.Number,
28
28
  message: Schema.String,
29
29
  name: Schema.String,
30
30
  stack: Schema.optional(Schema.String),
@@ -44,7 +44,7 @@ export const InvocationTraceStartEvent = Schema.Struct({
44
44
  /**
45
45
  * Event generation time.
46
46
  */
47
- timestampMs: Schema.Number,
47
+ timestamp: Schema.Number,
48
48
  /**
49
49
  * Data passed to function / workflow as an argument.
50
50
  */
@@ -53,11 +53,11 @@ export const InvocationTraceStartEvent = Schema.Struct({
53
53
  /**
54
54
  * Queue for function/workflow invocation events.
55
55
  */
56
- invocationTraceQueue: Type.Ref(Queue),
56
+ invocationTraceQueue: Schema.optional(Type.Ref(Queue)),
57
57
  /**
58
58
  * DXN of the invoked function/workflow.
59
59
  */
60
- invocationTarget: Type.Ref(Type.Expando),
60
+ invocationTarget: Schema.optional(Type.Ref(Type.Expando)),
61
61
  /**
62
62
  * Present for automatic invocations.
63
63
  */
@@ -80,7 +80,7 @@ export const InvocationTraceEndEvent = Schema.Struct({
80
80
  * Event generation time.
81
81
  */
82
82
  // TODO(burdon): Remove ms suffix.
83
- timestampMs: Schema.Number,
83
+ timestamp: Schema.Number,
84
84
  outcome: Schema.Enums(InvocationOutcome),
85
85
  exception: Schema.optional(TraceEventException),
86
86
  }).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));
@@ -90,7 +90,7 @@ export type InvocationTraceEndEvent = Schema.Schema.Type<typeof InvocationTraceE
90
90
  export type InvocationTraceEvent = InvocationTraceStartEvent | InvocationTraceEndEvent;
91
91
 
92
92
  export const TraceEventLog = Schema.Struct({
93
- timestampMs: Schema.Number,
93
+ timestamp: Schema.Number,
94
94
  level: Schema.String,
95
95
  message: Schema.String,
96
96
  context: Schema.optional(Schema.Object),
@@ -101,10 +101,8 @@ export const TraceEvent = Schema.Struct({
101
101
  // TODO(burdon): Need enum/numeric result (not string).
102
102
  outcome: Schema.String,
103
103
  truncated: Schema.Boolean,
104
- /**
105
- * Time when the event was persisted.
106
- */
107
- ingestionTimestampMs: Schema.Number,
104
+ /** Time when the event was persisted. */
105
+ ingestionTimestamp: Schema.Number,
108
106
  logs: Schema.Array(TraceEventLog),
109
107
  exceptions: Schema.Array(TraceEventException),
110
108
  }).pipe(Type.Obj({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));
@@ -117,13 +115,13 @@ export type TraceEvent = Schema.Schema.Type<typeof TraceEvent>;
117
115
  */
118
116
  export type InvocationSpan = {
119
117
  id: string;
120
- timestampMs: number;
118
+ timestamp: number;
119
+ duration: number;
121
120
  outcome: InvocationOutcome;
122
121
  input: object;
123
- durationMs: number;
124
- invocationTraceQueue: Ref.Ref<Queue>;
125
- invocationTarget: Ref.Ref<Type.Expando>;
126
- trigger?: Ref.Ref<FunctionTriggerType>;
122
+ invocationTraceQueue?: Ref.Ref<Queue>;
123
+ invocationTarget?: Ref.Ref<Type.Expando>;
124
+ trigger?: Ref.Ref<FunctionTrigger>;
127
125
  exception?: TraceEventException;
128
126
  };
129
127
 
@@ -165,8 +163,8 @@ export const createInvocationSpans = (items?: InvocationTraceEvent[]): Invocatio
165
163
 
166
164
  result.push({
167
165
  id: invocationId,
168
- timestampMs: start.timestampMs,
169
- durationMs: isInProgress ? now - start.timestampMs : end!.timestampMs - start.timestampMs,
166
+ timestamp: start.timestamp,
167
+ duration: isInProgress ? now - start.timestamp : end!.timestamp - start.timestamp,
170
168
  outcome: end?.outcome ?? InvocationOutcome.PENDING,
171
169
  exception: end?.exception,
172
170
  input: start.input,
@@ -0,0 +1,7 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './invocation-tracer';
6
+ export * from './trigger-dispatcher';
7
+ export * from './trigger-state-store';
@@ -0,0 +1,35 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { type EventType, type FunctionTrigger } from '@dxos/functions';
6
+
7
+ export const createInvocationPayload = (trigger: FunctionTrigger, event: EventType): any => {
8
+ if (!trigger.input) {
9
+ return event;
10
+ }
11
+
12
+ const payload: any = {};
13
+ for (const [key, value] of Object.entries(trigger.input)) {
14
+ if (typeof value !== 'string' || !(value.startsWith('{{') && value.endsWith('}}'))) {
15
+ payload[key] = value;
16
+ continue;
17
+ }
18
+
19
+ const propertyPath = value.slice(2, -2);
20
+ let valueSubstitution: any = propertyPath.startsWith('trigger.')
21
+ ? trigger
22
+ : propertyPath.startsWith('event.')
23
+ ? event
24
+ : undefined;
25
+
26
+ for (const pathSegment of propertyPath.split('.').slice(1)) {
27
+ if (valueSubstitution && typeof valueSubstitution === 'object') {
28
+ valueSubstitution = valueSubstitution[pathSegment];
29
+ }
30
+ }
31
+
32
+ payload[key] = valueSubstitution;
33
+ }
34
+ return payload;
35
+ };