@dxos/functions 0.8.4-main.ead640a → 0.8.4-main.f466a3d56e

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 (185) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +5 -7
  3. package/dist/lib/neutral/index.mjs +602 -0
  4. package/dist/lib/neutral/index.mjs.map +7 -0
  5. package/dist/lib/neutral/meta.json +1 -0
  6. package/dist/types/src/index.d.ts +3 -9
  7. package/dist/types/src/index.d.ts.map +1 -1
  8. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  9. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  10. package/dist/types/src/protocol/functions-ai-http-client.test.d.ts +2 -0
  11. package/dist/types/src/protocol/functions-ai-http-client.test.d.ts.map +1 -0
  12. package/dist/types/src/protocol/index.d.ts +2 -0
  13. package/dist/types/src/protocol/index.d.ts.map +1 -0
  14. package/dist/types/src/protocol/protocol.d.ts +24 -0
  15. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  16. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  17. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  18. package/dist/types/src/sdk.d.ts +10 -0
  19. package/dist/types/src/sdk.d.ts.map +1 -0
  20. package/dist/types/src/services/credentials.d.ts +17 -38
  21. package/dist/types/src/services/credentials.d.ts.map +1 -1
  22. package/dist/types/src/services/function-invocation-service.d.ts +9 -19
  23. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  24. package/dist/types/src/services/index.d.ts +1 -6
  25. package/dist/types/src/services/index.d.ts.map +1 -1
  26. package/dist/types/src/services/queues.d.ts +1 -46
  27. package/dist/types/src/services/queues.d.ts.map +1 -1
  28. package/dist/types/src/services/tracing.d.ts +2 -56
  29. package/dist/types/src/services/tracing.d.ts.map +1 -1
  30. package/dist/types/src/types/index.d.ts +2 -0
  31. package/dist/types/src/types/index.d.ts.map +1 -0
  32. package/dist/types/src/types/url.d.ts +13 -0
  33. package/dist/types/src/types/url.d.ts.map +1 -0
  34. package/dist/types/tsconfig.tsbuildinfo +1 -1
  35. package/package.json +26 -64
  36. package/src/index.ts +3 -9
  37. package/src/protocol/functions-ai-http-client.test.ts +105 -0
  38. package/src/protocol/functions-ai-http-client.ts +141 -0
  39. package/src/{executor → protocol}/index.ts +1 -1
  40. package/src/protocol/protocol.test.ts +58 -0
  41. package/src/protocol/protocol.ts +455 -0
  42. package/src/sdk.ts +31 -0
  43. package/src/services/credentials.ts +81 -110
  44. package/src/services/function-invocation-service.ts +22 -70
  45. package/src/services/index.ts +1 -6
  46. package/src/services/queues.ts +1 -80
  47. package/src/services/tracing.ts +1 -136
  48. package/src/types/index.ts +5 -0
  49. package/src/types/url.ts +32 -0
  50. package/dist/lib/browser/bundler/index.mjs +0 -269
  51. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  52. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  53. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  54. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  55. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  56. package/dist/lib/browser/edge/index.mjs +0 -83
  57. package/dist/lib/browser/edge/index.mjs.map +0 -7
  58. package/dist/lib/browser/index.mjs +0 -1395
  59. package/dist/lib/browser/index.mjs.map +0 -7
  60. package/dist/lib/browser/meta.json +0 -1
  61. package/dist/lib/browser/testing/index.mjs +0 -131
  62. package/dist/lib/browser/testing/index.mjs.map +0 -7
  63. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  64. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  65. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  66. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  67. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  68. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  69. package/dist/lib/node-esm/edge/index.mjs +0 -84
  70. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  71. package/dist/lib/node-esm/index.mjs +0 -1396
  72. package/dist/lib/node-esm/index.mjs.map +0 -7
  73. package/dist/lib/node-esm/meta.json +0 -1
  74. package/dist/lib/node-esm/testing/index.mjs +0 -132
  75. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  76. package/dist/types/src/bundler/bundler.d.ts +0 -49
  77. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  78. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  79. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  80. package/dist/types/src/bundler/index.d.ts +0 -2
  81. package/dist/types/src/bundler/index.d.ts.map +0 -1
  82. package/dist/types/src/edge/functions.d.ts +0 -17
  83. package/dist/types/src/edge/functions.d.ts.map +0 -1
  84. package/dist/types/src/edge/index.d.ts +0 -2
  85. package/dist/types/src/edge/index.d.ts.map +0 -1
  86. package/dist/types/src/errors.d.ts +0 -137
  87. package/dist/types/src/errors.d.ts.map +0 -1
  88. package/dist/types/src/examples/fib.d.ts +0 -7
  89. package/dist/types/src/examples/fib.d.ts.map +0 -1
  90. package/dist/types/src/examples/index.d.ts +0 -4
  91. package/dist/types/src/examples/index.d.ts.map +0 -1
  92. package/dist/types/src/examples/reply.d.ts +0 -3
  93. package/dist/types/src/examples/reply.d.ts.map +0 -1
  94. package/dist/types/src/examples/sleep.d.ts +0 -5
  95. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  96. package/dist/types/src/executor/executor.d.ts +0 -14
  97. package/dist/types/src/executor/executor.d.ts.map +0 -1
  98. package/dist/types/src/executor/index.d.ts +0 -2
  99. package/dist/types/src/executor/index.d.ts.map +0 -1
  100. package/dist/types/src/handler.d.ts +0 -109
  101. package/dist/types/src/handler.d.ts.map +0 -1
  102. package/dist/types/src/schema.d.ts +0 -43
  103. package/dist/types/src/schema.d.ts.map +0 -1
  104. package/dist/types/src/services/database.d.ts +0 -67
  105. package/dist/types/src/services/database.d.ts.map +0 -1
  106. package/dist/types/src/services/event-logger.d.ts +0 -75
  107. package/dist/types/src/services/event-logger.d.ts.map +0 -1
  108. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  109. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  110. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  111. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  112. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  113. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  114. package/dist/types/src/services/service-container.d.ts +0 -57
  115. package/dist/types/src/services/service-container.d.ts.map +0 -1
  116. package/dist/types/src/services/service-registry.d.ts +0 -31
  117. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  118. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  119. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  120. package/dist/types/src/testing/index.d.ts +0 -3
  121. package/dist/types/src/testing/index.d.ts.map +0 -1
  122. package/dist/types/src/testing/layer.d.ts +0 -18
  123. package/dist/types/src/testing/layer.d.ts.map +0 -1
  124. package/dist/types/src/testing/logger.d.ts +0 -5
  125. package/dist/types/src/testing/logger.d.ts.map +0 -1
  126. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  127. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  128. package/dist/types/src/testing/services.d.ts +0 -59
  129. package/dist/types/src/testing/services.d.ts.map +0 -1
  130. package/dist/types/src/trace.d.ts +0 -122
  131. package/dist/types/src/trace.d.ts.map +0 -1
  132. package/dist/types/src/translations.d.ts +0 -12
  133. package/dist/types/src/translations.d.ts.map +0 -1
  134. package/dist/types/src/triggers/index.d.ts +0 -4
  135. package/dist/types/src/triggers/index.d.ts.map +0 -1
  136. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  137. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  138. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  139. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  140. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  141. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  142. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  143. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  144. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  145. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  146. package/dist/types/src/types.d.ts +0 -230
  147. package/dist/types/src/types.d.ts.map +0 -1
  148. package/dist/types/src/url.d.ts +0 -21
  149. package/dist/types/src/url.d.ts.map +0 -1
  150. package/src/bundler/bundler.test.ts +0 -58
  151. package/src/bundler/bundler.ts +0 -295
  152. package/src/bundler/index.ts +0 -5
  153. package/src/edge/functions.ts +0 -67
  154. package/src/edge/index.ts +0 -9
  155. package/src/errors.ts +0 -21
  156. package/src/examples/fib.ts +0 -32
  157. package/src/examples/index.ts +0 -7
  158. package/src/examples/reply.ts +0 -21
  159. package/src/examples/sleep.ts +0 -24
  160. package/src/executor/executor.ts +0 -58
  161. package/src/handler.ts +0 -225
  162. package/src/schema.ts +0 -71
  163. package/src/services/database.ts +0 -175
  164. package/src/services/event-logger.ts +0 -121
  165. package/src/services/function-invocation-service.test.ts +0 -81
  166. package/src/services/local-function-execution.ts +0 -153
  167. package/src/services/remote-function-execution-service.ts +0 -63
  168. package/src/services/service-container.ts +0 -115
  169. package/src/services/service-registry.test.ts +0 -45
  170. package/src/services/service-registry.ts +0 -63
  171. package/src/testing/index.ts +0 -6
  172. package/src/testing/layer.ts +0 -114
  173. package/src/testing/logger.ts +0 -17
  174. package/src/testing/persist-database.test.ts +0 -87
  175. package/src/testing/services.ts +0 -115
  176. package/src/trace.ts +0 -178
  177. package/src/translations.ts +0 -20
  178. package/src/triggers/index.ts +0 -7
  179. package/src/triggers/input-builder.ts +0 -35
  180. package/src/triggers/invocation-tracer.ts +0 -101
  181. package/src/triggers/trigger-dispatcher.test.ts +0 -665
  182. package/src/triggers/trigger-dispatcher.ts +0 -533
  183. package/src/triggers/trigger-state-store.ts +0 -61
  184. package/src/types.ts +0 -218
  185. package/src/url.ts +0 -55
@@ -5,80 +5,32 @@ import * as Context from 'effect/Context';
5
5
  import * as Effect from 'effect/Effect';
6
6
  import * as Layer from 'effect/Layer';
7
7
 
8
- import { AiService } from '@dxos/ai';
9
-
10
- import { type FunctionDefinition } from '../handler';
11
-
12
- import { CredentialsService } from './credentials';
13
- import { DatabaseService } from './database';
14
- import {
15
- FunctionImplementationResolver,
16
- type InvocationServices,
17
- LocalFunctionExecutionService,
18
- } from './local-function-execution';
19
- import { QueueService } from './queues';
20
- import { RemoteFunctionExecutionService } from './remote-function-execution-service';
8
+ import { type FunctionNotFoundError, Operation } from '@dxos/compute';
21
9
 
10
+ /**
11
+ * @deprecated
12
+ */
22
13
  export class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<
23
14
  FunctionInvocationService,
24
15
  {
25
- invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;
16
+ invokeFunction<I, O>(functionDef: Operation.Definition<I, O, any>, input: I): Effect.Effect<O>;
17
+
18
+ resolveFunction(key: string): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError>;
26
19
  }
27
20
  >() {
28
- static invokeFunction = Effect.serviceFunctionEffect(FunctionInvocationService, (_) => _.invokeFunction);
29
-
30
- static layer = Layer.effect(
31
- FunctionInvocationService,
32
- Effect.gen(function* () {
33
- const localExecutioner = yield* LocalFunctionExecutionService;
34
- const remoteExecutioner = yield* RemoteFunctionExecutionService;
35
-
36
- return {
37
- invokeFunction: <I, O>(
38
- functionDef: FunctionDefinition<I, O>,
39
- input: I,
40
- ): Effect.Effect<O, never, InvocationServices> =>
41
- Effect.gen(function* () {
42
- if (functionDef.meta?.deployedFunctionId) {
43
- return yield* remoteExecutioner.callFunction<I, O>(functionDef.meta.deployedFunctionId, input);
44
- }
45
-
46
- return yield* localExecutioner.invokeFunction(functionDef, input);
47
- }),
48
- } satisfies Context.Tag.Service<FunctionInvocationService>;
49
- }),
50
- );
51
-
52
- // TODO(dmaretskyi): Don't provide `FunctionImplementationResolver`.
53
- static layerTest = ({
54
- functions = [],
55
- }: {
56
- functions?: FunctionDefinition<any, any>[];
57
- } = {}): Layer.Layer<
58
- FunctionInvocationService,
59
- never,
60
- AiService.AiService | CredentialsService | DatabaseService | QueueService
61
- > =>
62
- FunctionInvocationService.layer.pipe(
63
- Layer.provide(LocalFunctionExecutionService.layerLive),
64
- Layer.provide(FunctionImplementationResolver.layerTest({ functions })),
65
- Layer.provide(RemoteFunctionExecutionService.layerMock),
66
- );
67
-
68
- // TODO(dmaretskyi): This shouldn't default to all services being not available.
69
- // TODO(dmaretskyi): Don't provide `FunctionImplementationResolver`.
70
- /**
71
- * @deprecated Use {@link layerTest} instead.
72
- */
73
- static layerTestMocked = ({
74
- functions,
75
- }: {
76
- functions: FunctionDefinition<any, any>[];
77
- }): Layer.Layer<FunctionInvocationService> =>
78
- FunctionInvocationService.layerTest({ functions }).pipe(
79
- Layer.provide(AiService.notAvailable),
80
- Layer.provide(CredentialsService.configuredLayer([])),
81
- Layer.provide(DatabaseService.notAvailable),
82
- Layer.provide(QueueService.notAvailable),
83
- );
21
+ static layerNotAvailable = Layer.succeed(FunctionInvocationService, {
22
+ invokeFunction: () => Effect.die('FunctionInvocationService is not avaialble.'),
23
+ resolveFunction: () => Effect.die('FunctionInvocationService is not available.'),
24
+ });
25
+
26
+ static invokeFunction = <I, O>(
27
+ functionDef: Operation.Definition<I, O, any>,
28
+ input: I,
29
+ ): Effect.Effect<O, never, FunctionInvocationService> =>
30
+ Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
31
+
32
+ static resolveFunction = (
33
+ key: string,
34
+ ): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError, FunctionInvocationService> =>
35
+ Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.resolveFunction)(key);
84
36
  }
@@ -3,11 +3,6 @@
3
3
  //
4
4
 
5
5
  export * from './credentials';
6
- export * from './database';
7
- export * from './event-logger';
8
6
  export * from './function-invocation-service';
9
- export * from './local-function-execution';
10
7
  export * from './queues';
11
- export * from './service-container';
12
- export * from './tracing';
13
- export * from './remote-function-execution-service';
8
+ export { MESSAGE_PROPERTY_TOOL_CALL_ID } from './tracing';
@@ -2,83 +2,4 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
-
9
- import type { Obj, Relation } from '@dxos/echo';
10
- import type { Queue, QueueAPI, QueueFactory } from '@dxos/echo-db';
11
- import type { DXN, QueueSubspaceTag } from '@dxos/keys';
12
-
13
- /**
14
- * Gives access to all queues.
15
- */
16
- export class QueueService extends Context.Tag('@dxos/functions/QueueService')<
17
- QueueService,
18
- {
19
- /**
20
- * API to access the queues.
21
- */
22
- readonly queues: QueueAPI;
23
-
24
- /**
25
- * The queue that is used to store the context of the current research.
26
- * @deprecated Use `ContextQueueService` instead.
27
- */
28
- readonly queue: Queue | undefined;
29
- }
30
- >() {
31
- static notAvailable = Layer.succeed(QueueService, {
32
- queues: {
33
- get(_dxn) {
34
- throw new Error('Queues not available');
35
- },
36
- create() {
37
- throw new Error('Queues not available');
38
- },
39
- },
40
- queue: undefined,
41
- });
42
-
43
- static make = (queues: QueueFactory, queue?: Queue): Context.Tag.Service<QueueService> => {
44
- return {
45
- queues,
46
- queue,
47
- };
48
- };
49
-
50
- static layer = (queues: QueueFactory, queue?: Queue): Layer.Layer<QueueService> =>
51
- Layer.succeed(QueueService, QueueService.make(queues, queue));
52
-
53
- /**
54
- * Gets a queue by its DXN.
55
- */
56
- static getQueue = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(
57
- dxn: DXN,
58
- ): Effect.Effect<Queue<T>, never, QueueService> => QueueService.pipe(Effect.map(({ queues }) => queues.get<T>(dxn)));
59
-
60
- /**
61
- * Creates a new queue.
62
- */
63
- static createQueue = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(options?: {
64
- subspaceTag?: QueueSubspaceTag;
65
- }): Effect.Effect<Queue<T>, never, QueueService> =>
66
- QueueService.pipe(Effect.map(({ queues }) => queues.create<T>(options)));
67
-
68
- static append = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(
69
- queue: Queue<T>,
70
- objects: T[],
71
- ): Effect.Effect<void> => Effect.promise(() => queue.append(objects));
72
- }
73
-
74
- /**
75
- * Gives access to a specific queue passed as a context.
76
- */
77
- export class ContextQueueService extends Context.Tag('@dxos/functions/ContextQueueService')<
78
- ContextQueueService,
79
- {
80
- readonly queue: Queue;
81
- }
82
- >() {
83
- static layer = (queue: Queue) => Layer.succeed(ContextQueueService, { queue });
84
- }
5
+ export { QueueService, feedServiceFromQueueServiceLayer } from '@dxos/echo-db';
@@ -2,142 +2,7 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import * as Context from 'effect/Context';
6
- import * as Effect from 'effect/Effect';
7
- import * as Layer from 'effect/Layer';
8
-
9
- import { AgentStatus } from '@dxos/ai';
10
- import { Obj } from '@dxos/echo';
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';
15
-
16
- /**
17
- * Provides a way for compute primitives (functions, workflows, tools)
18
- * to emit an execution trace as a series of structured ECHO objects.
19
- */
20
- export class TracingService extends Context.Tag('@dxos/functions/TracingService')<
21
- TracingService,
22
- {
23
- /**
24
- * Gets the parent message ID.
25
- */
26
- getTraceContext: () => TracingService.TraceContext;
27
-
28
- /**
29
- * Write an event to the tracing queue.
30
- * @param event - The event to write. Must be an a typed object.
31
- */
32
- write: (event: Obj.Any) => void;
33
- }
34
- >() {
35
- static noop: Context.Tag.Service<TracingService> = { write: () => {}, getTraceContext: () => ({}) };
36
-
37
- static layerNoop = Layer.succeed(TracingService, TracingService.noop);
38
-
39
- static console: Context.Tag.Service<TracingService> = {
40
- write: (event) => {
41
- console.log(event);
42
- },
43
- getTraceContext: () => ({}),
44
- };
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
-
90
- /**
91
- * Emit the current human-readable execution status.
92
- */
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
- });
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
5
  /**
141
- * Goes into {@link DataType.Message['properties']}
6
+ * Goes into {@link Message['properties']}
142
7
  */
143
8
  export const MESSAGE_PROPERTY_TOOL_CALL_ID = 'toolCallId' as const;
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './url';
@@ -0,0 +1,32 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { type Obj } from '@dxos/echo';
6
+
7
+ // TODO: use URL scheme for source?
8
+ export const FUNCTIONS_META_KEY = 'org.dxos.service.function';
9
+
10
+ export const FUNCTIONS_PRESET_META_KEY = 'org.dxos.service.function-preset';
11
+
12
+ /**
13
+ * NOTE: functionId is backend ID, not ECHO object id.
14
+ */
15
+ export const getUserFunctionIdInMetadata = (meta: Obj.ReadonlyMeta) => {
16
+ return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
17
+ };
18
+
19
+ /**
20
+ * NOTE: functionId is backend ID, not ECHO object id.
21
+ * Must be called inside Obj.update() since it mutates the meta.
22
+ */
23
+ export const setUserFunctionIdInMetadata = (meta: Obj.Meta, functionId: string) => {
24
+ const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);
25
+ if (key) {
26
+ if (key.id !== functionId) {
27
+ throw new Error('Metadata mismatch');
28
+ }
29
+ } else {
30
+ meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionId });
31
+ }
32
+ };
@@ -1,269 +0,0 @@
1
- import "../chunk-J5LGTIGS.mjs";
2
-
3
- // src/bundler/bundler.ts
4
- import * as FetchHttpClient from "@effect/platform/FetchHttpClient";
5
- import * as HttpClient from "@effect/platform/HttpClient";
6
- import * as Duration from "effect/Duration";
7
- import * as Effect from "effect/Effect";
8
- import * as Function from "effect/Function";
9
- import * as Schedule from "effect/Schedule";
10
- import { build, initialize } from "esbuild-wasm";
11
- import { subtleCrypto } from "@dxos/crypto";
12
- import { runAndForwardErrors } from "@dxos/effect";
13
- import { invariant } from "@dxos/invariant";
14
- import { log } from "@dxos/log";
15
- function _define_property(obj, key, value) {
16
- if (key in obj) {
17
- Object.defineProperty(obj, key, {
18
- value,
19
- enumerable: true,
20
- configurable: true,
21
- writable: true
22
- });
23
- } else {
24
- obj[key] = value;
25
- }
26
- return obj;
27
- }
28
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/bundler/bundler.ts";
29
- var initialized;
30
- var initializeBundler = async (options) => {
31
- await (initialized ?? (initialized = initialize({
32
- wasmURL: options.wasmUrl
33
- })));
34
- };
35
- var Bundler = class {
36
- async bundle({ source }) {
37
- const { sandboxedModules: providedModules, ...options } = this._options;
38
- const sourceHash = Buffer.from(await subtleCrypto.digest("SHA-256", Buffer.from(source)));
39
- if (this._options.platform === "browser") {
40
- invariant(initialized, "Compiler not initialized.", {
41
- F: __dxlog_file,
42
- L: 70,
43
- S: this,
44
- A: [
45
- "initialized",
46
- "'Compiler not initialized.'"
47
- ]
48
- });
49
- await initialized;
50
- }
51
- const imports = source ? analyzeSourceFileImports(source) : [];
52
- try {
53
- const result = await build({
54
- platform: options.platform,
55
- conditions: [
56
- "workerd",
57
- "browser"
58
- ],
59
- metafile: true,
60
- write: false,
61
- entryPoints: {
62
- // Gets mapped to `userFunc.js` by esbuild.
63
- userFunc: "memory:main.tsx"
64
- },
65
- bundle: true,
66
- format: "esm",
67
- plugins: [
68
- {
69
- name: "memory",
70
- setup: (build2) => {
71
- build2.onResolve({
72
- filter: /^\.\/runtime\.js$/
73
- }, ({ path }) => {
74
- return {
75
- path,
76
- external: true
77
- };
78
- });
79
- build2.onResolve({
80
- filter: /^dxos:functions$/
81
- }, ({ path }) => {
82
- return {
83
- path: "./runtime.js",
84
- external: true
85
- };
86
- });
87
- build2.onResolve({
88
- filter: /^memory:/
89
- }, ({ path }) => {
90
- return {
91
- path: path.split(":")[1],
92
- namespace: "memory"
93
- };
94
- });
95
- build2.onLoad({
96
- filter: /.*/,
97
- namespace: "memory"
98
- }, ({ path }) => {
99
- if (path === "main.tsx") {
100
- return {
101
- contents: source,
102
- loader: "tsx"
103
- };
104
- }
105
- });
106
- for (const module of providedModules) {
107
- build2.onResolve({
108
- filter: new RegExp(`^${module}$`)
109
- }, ({ path }) => {
110
- return {
111
- path,
112
- namespace: "injected-module"
113
- };
114
- });
115
- }
116
- build2.onLoad({
117
- filter: /.*/,
118
- namespace: "injected-module"
119
- }, ({ path }) => {
120
- const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
121
- return {
122
- contents: `
123
- const { ${namedImports.join(",")} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
124
- export { ${namedImports.join(",")} };
125
- export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
126
- `,
127
- loader: "tsx"
128
- };
129
- });
130
- }
131
- },
132
- httpPlugin
133
- ]
134
- });
135
- log("compile complete", result.metafile, {
136
- F: __dxlog_file,
137
- L: 137,
138
- S: this,
139
- C: (f, a) => f(...a)
140
- });
141
- const entryPoint = "userFunc.js";
142
- return {
143
- timestamp: Date.now(),
144
- sourceHash,
145
- imports: this.analyzeImports(result),
146
- entryPoint,
147
- asset: result.outputFiles[0].contents,
148
- bundle: result.outputFiles[0].text
149
- };
150
- } catch (err) {
151
- return {
152
- timestamp: Date.now(),
153
- sourceHash,
154
- error: err
155
- };
156
- }
157
- }
158
- // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
159
- analyzeImports(result) {
160
- invariant(result.outputFiles, void 0, {
161
- F: __dxlog_file,
162
- L: 155,
163
- S: this,
164
- A: [
165
- "result.outputFiles",
166
- ""
167
- ]
168
- });
169
- const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
170
- return Object.values(result.metafile.outputs)[0].imports.map((entry) => {
171
- const namedImports = [];
172
- const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
173
- if (parsedImport?.[2]) {
174
- NAMED_IMPORTS_REGEX.lastIndex = 0;
175
- const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
176
- if (namedImportsMatch) {
177
- namedImportsMatch[1].split(",").forEach((importName) => {
178
- namedImports.push(importName.trim());
179
- });
180
- }
181
- }
182
- return {
183
- moduleUrl: entry.path,
184
- defaultImport: !!parsedImport?.[1],
185
- namedImports
186
- };
187
- });
188
- }
189
- analyzeSourceFileImports(code) {
190
- const parsedImports = allMatches(IMPORT_REGEX, code);
191
- return parsedImports.map((capture) => {
192
- return {
193
- defaultImportName: capture[1],
194
- namedImports: capture[2]?.split(",").map((importName) => importName.trim()),
195
- wildcardImportName: capture[3],
196
- moduleIdentifier: capture[4],
197
- quotes: capture[5]
198
- };
199
- });
200
- }
201
- constructor(_options) {
202
- _define_property(this, "_options", void 0);
203
- this._options = _options;
204
- }
205
- };
206
- var IMPORT_REGEX = /import(?:(?:(?:[ \n\t]+([^ *\n\t{},]+)[ \n\t]*(?:,|[ \n\t]+))?([ \n\t]*{(?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+})?[ \n\t]*)|[ \n\t]*\*[ \n\t]*as[ \n\t]+([^ \n\t{}]+)[ \n\t]+)from[ \n\t]*(?:['"])([^'"\n]+)(['"])/gm;
207
- var NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
208
- var allMatches = (regex, str) => {
209
- let match;
210
- const matches = [];
211
- regex.lastIndex = 0;
212
- while (match = regex.exec(str)) {
213
- matches.push(match);
214
- }
215
- return matches;
216
- };
217
- var analyzeSourceFileImports = (code) => {
218
- const parsedImports = allMatches(IMPORT_REGEX, code);
219
- return parsedImports.map((capture) => {
220
- return {
221
- defaultImportName: capture[1],
222
- namedImports: capture[2]?.trim().slice(1, -1).split(",").map((importName) => importName.trim()),
223
- wildcardImportName: capture[3],
224
- moduleIdentifier: capture[4],
225
- quotes: capture[5]
226
- };
227
- });
228
- };
229
- var MAX_RETRIES = 5;
230
- var INITIAL_DELAY = 1e3;
231
- var httpPlugin = {
232
- name: "http",
233
- setup: (build2) => {
234
- build2.onResolve({
235
- filter: /^https?:\/\//
236
- }, (args) => ({
237
- path: args.path,
238
- namespace: "http-url"
239
- }));
240
- build2.onResolve({
241
- filter: /.*/,
242
- namespace: "http-url"
243
- }, (args) => ({
244
- path: new URL(args.path, args.importer).toString(),
245
- namespace: "http-url"
246
- }));
247
- build2.onLoad({
248
- filter: /.*/,
249
- namespace: "http-url"
250
- }, async (args) => {
251
- return Effect.gen(function* () {
252
- const response = yield* HttpClient.get(args.path);
253
- if (response.status !== 200) {
254
- throw new Error(`failed to fetch: ${response.status}`);
255
- }
256
- const text = yield* response.text;
257
- return {
258
- contents: text,
259
- loader: "jsx"
260
- };
261
- }).pipe(Effect.retry(Function.pipe(Schedule.exponential(Duration.millis(INITIAL_DELAY)), Schedule.jittered, Schedule.intersect(Schedule.recurs(MAX_RETRIES - 1)))), Effect.provide(FetchHttpClient.layer), runAndForwardErrors);
262
- });
263
- }
264
- };
265
- export {
266
- Bundler,
267
- initializeBundler
268
- };
269
- //# sourceMappingURL=index.mjs.map