@dxos/functions 0.8.4-main.ae835ea → 0.8.4-main.bc2380dfbc

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 (197) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +5 -7
  3. package/dist/lib/neutral/index.mjs +599 -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 +2 -7
  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 +6 -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 +1 -4
  31. package/dist/types/src/types/index.d.ts.map +1 -1
  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 -61
  36. package/src/index.ts +2 -7
  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 +452 -0
  42. package/src/sdk.ts +31 -0
  43. package/src/services/credentials.ts +81 -110
  44. package/src/services/function-invocation-service.ts +19 -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 +1 -4
  49. package/src/types/url.ts +32 -0
  50. package/dist/lib/browser/bundler/index.mjs +0 -256
  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-M6EXIREF.mjs +0 -610
  55. package/dist/lib/browser/chunk-M6EXIREF.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 -1346
  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 -257
  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-P3IATZMZ.mjs +0 -612
  68. package/dist/lib/node-esm/chunk-P3IATZMZ.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 -1347
  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/e2e/deploy.test.d.ts +0 -2
  83. package/dist/types/src/e2e/deploy.test.d.ts.map +0 -1
  84. package/dist/types/src/edge/functions.d.ts +0 -17
  85. package/dist/types/src/edge/functions.d.ts.map +0 -1
  86. package/dist/types/src/edge/index.d.ts +0 -2
  87. package/dist/types/src/edge/index.d.ts.map +0 -1
  88. package/dist/types/src/errors.d.ts +0 -137
  89. package/dist/types/src/errors.d.ts.map +0 -1
  90. package/dist/types/src/example/fib.d.ts +0 -7
  91. package/dist/types/src/example/fib.d.ts.map +0 -1
  92. package/dist/types/src/example/forex-effect.d.ts +0 -3
  93. package/dist/types/src/example/forex-effect.d.ts.map +0 -1
  94. package/dist/types/src/example/index.d.ts +0 -12
  95. package/dist/types/src/example/index.d.ts.map +0 -1
  96. package/dist/types/src/example/reply.d.ts +0 -3
  97. package/dist/types/src/example/reply.d.ts.map +0 -1
  98. package/dist/types/src/example/sleep.d.ts +0 -5
  99. package/dist/types/src/example/sleep.d.ts.map +0 -1
  100. package/dist/types/src/executor/executor.d.ts +0 -14
  101. package/dist/types/src/executor/executor.d.ts.map +0 -1
  102. package/dist/types/src/executor/index.d.ts +0 -2
  103. package/dist/types/src/executor/index.d.ts.map +0 -1
  104. package/dist/types/src/handler.d.ts +0 -102
  105. package/dist/types/src/handler.d.ts.map +0 -1
  106. package/dist/types/src/services/database.d.ts +0 -67
  107. package/dist/types/src/services/database.d.ts.map +0 -1
  108. package/dist/types/src/services/event-logger.d.ts +0 -75
  109. package/dist/types/src/services/event-logger.d.ts.map +0 -1
  110. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  111. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  112. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  113. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  114. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  115. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  116. package/dist/types/src/services/service-container.d.ts +0 -57
  117. package/dist/types/src/services/service-container.d.ts.map +0 -1
  118. package/dist/types/src/services/service-registry.d.ts +0 -31
  119. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  120. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  121. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  122. package/dist/types/src/testing/index.d.ts +0 -3
  123. package/dist/types/src/testing/index.d.ts.map +0 -1
  124. package/dist/types/src/testing/layer.d.ts +0 -18
  125. package/dist/types/src/testing/layer.d.ts.map +0 -1
  126. package/dist/types/src/testing/logger.d.ts +0 -5
  127. package/dist/types/src/testing/logger.d.ts.map +0 -1
  128. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  129. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  130. package/dist/types/src/testing/services.d.ts +0 -59
  131. package/dist/types/src/testing/services.d.ts.map +0 -1
  132. package/dist/types/src/trace.d.ts +0 -122
  133. package/dist/types/src/trace.d.ts.map +0 -1
  134. package/dist/types/src/translations.d.ts +0 -12
  135. package/dist/types/src/translations.d.ts.map +0 -1
  136. package/dist/types/src/triggers/index.d.ts +0 -4
  137. package/dist/types/src/triggers/index.d.ts.map +0 -1
  138. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  139. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  140. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  141. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  142. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  143. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  144. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  145. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  146. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  147. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  148. package/dist/types/src/types/Function.d.ts +0 -47
  149. package/dist/types/src/types/Function.d.ts.map +0 -1
  150. package/dist/types/src/types/Script.d.ts +0 -28
  151. package/dist/types/src/types/Script.d.ts.map +0 -1
  152. package/dist/types/src/types/Trigger.d.ts +0 -139
  153. package/dist/types/src/types/Trigger.d.ts.map +0 -1
  154. package/dist/types/src/types/TriggerEvent.d.ts +0 -44
  155. package/dist/types/src/types/TriggerEvent.d.ts.map +0 -1
  156. package/dist/types/src/url.d.ts +0 -21
  157. package/dist/types/src/url.d.ts.map +0 -1
  158. package/src/bundler/bundler.test.ts +0 -58
  159. package/src/bundler/bundler.ts +0 -295
  160. package/src/bundler/index.ts +0 -5
  161. package/src/e2e/deploy.test.ts +0 -69
  162. package/src/edge/functions.ts +0 -67
  163. package/src/edge/index.ts +0 -9
  164. package/src/errors.ts +0 -21
  165. package/src/example/fib.ts +0 -32
  166. package/src/example/forex-effect.ts +0 -40
  167. package/src/example/index.ts +0 -13
  168. package/src/example/reply.ts +0 -21
  169. package/src/example/sleep.ts +0 -24
  170. package/src/executor/executor.ts +0 -58
  171. package/src/handler.ts +0 -226
  172. package/src/services/database.ts +0 -175
  173. package/src/services/event-logger.ts +0 -121
  174. package/src/services/function-invocation-service.test.ts +0 -81
  175. package/src/services/local-function-execution.ts +0 -153
  176. package/src/services/remote-function-execution-service.ts +0 -63
  177. package/src/services/service-container.ts +0 -115
  178. package/src/services/service-registry.test.ts +0 -45
  179. package/src/services/service-registry.ts +0 -63
  180. package/src/testing/index.ts +0 -6
  181. package/src/testing/layer.ts +0 -114
  182. package/src/testing/logger.ts +0 -17
  183. package/src/testing/persist-database.test.ts +0 -87
  184. package/src/testing/services.ts +0 -115
  185. package/src/trace.ts +0 -178
  186. package/src/translations.ts +0 -20
  187. package/src/triggers/index.ts +0 -7
  188. package/src/triggers/input-builder.ts +0 -35
  189. package/src/triggers/invocation-tracer.ts +0 -101
  190. package/src/triggers/trigger-dispatcher.test.ts +0 -664
  191. package/src/triggers/trigger-dispatcher.ts +0 -521
  192. package/src/triggers/trigger-state-store.ts +0 -61
  193. package/src/types/Function.ts +0 -51
  194. package/src/types/Script.ts +0 -33
  195. package/src/types/Trigger.ts +0 -139
  196. package/src/types/TriggerEvent.ts +0 -62
  197. package/src/url.ts +0 -55
@@ -5,80 +5,29 @@ 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
 
22
10
  export class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<
23
11
  FunctionInvocationService,
24
12
  {
25
- invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;
13
+ invokeFunction<I, O>(functionDef: Operation.Definition<I, O, any>, input: I): Effect.Effect<O>;
14
+
15
+ resolveFunction(key: string): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError>;
26
16
  }
27
17
  >() {
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?: readonly 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?: readonly 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
- );
18
+ static layerNotAvailable = Layer.succeed(FunctionInvocationService, {
19
+ invokeFunction: () => Effect.die('FunctionInvocationService is not avaialble.'),
20
+ resolveFunction: () => Effect.die('FunctionInvocationService is not available.'),
21
+ });
22
+
23
+ static invokeFunction = <I, O>(
24
+ functionDef: Operation.Definition<I, O, any>,
25
+ input: I,
26
+ ): Effect.Effect<O, never, FunctionInvocationService> =>
27
+ Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
28
+
29
+ static resolveFunction = (
30
+ key: string,
31
+ ): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError, FunctionInvocationService> =>
32
+ Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.resolveFunction)(key);
84
33
  }
@@ -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;
@@ -2,7 +2,4 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- export * as Function from './Function';
6
- export * as Script from './Script';
7
- export * as Trigger from './Trigger';
8
- export * as TriggerEvent from './TriggerEvent';
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,256 +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
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/bundler/bundler.ts";
16
- var initialized;
17
- var initializeBundler = async (options) => {
18
- await (initialized ??= initialize({
19
- wasmURL: options.wasmUrl
20
- }));
21
- };
22
- var Bundler = class {
23
- _options;
24
- constructor(_options) {
25
- this._options = _options;
26
- }
27
- async bundle({ source }) {
28
- const { sandboxedModules: providedModules, ...options } = this._options;
29
- const sourceHash = Buffer.from(await subtleCrypto.digest("SHA-256", Buffer.from(source)));
30
- if (this._options.platform === "browser") {
31
- invariant(initialized, "Compiler not initialized.", {
32
- F: __dxlog_file,
33
- L: 70,
34
- S: this,
35
- A: [
36
- "initialized",
37
- "'Compiler not initialized.'"
38
- ]
39
- });
40
- await initialized;
41
- }
42
- const imports = source ? analyzeSourceFileImports(source) : [];
43
- try {
44
- const result = await build({
45
- platform: options.platform,
46
- conditions: [
47
- "workerd",
48
- "browser"
49
- ],
50
- metafile: true,
51
- write: false,
52
- entryPoints: {
53
- // Gets mapped to `userFunc.js` by esbuild.
54
- userFunc: "memory:main.tsx"
55
- },
56
- bundle: true,
57
- format: "esm",
58
- plugins: [
59
- {
60
- name: "memory",
61
- setup: (build2) => {
62
- build2.onResolve({
63
- filter: /^\.\/runtime\.js$/
64
- }, ({ path }) => {
65
- return {
66
- path,
67
- external: true
68
- };
69
- });
70
- build2.onResolve({
71
- filter: /^dxos:functions$/
72
- }, ({ path }) => {
73
- return {
74
- path: "./runtime.js",
75
- external: true
76
- };
77
- });
78
- build2.onResolve({
79
- filter: /^memory:/
80
- }, ({ path }) => {
81
- return {
82
- path: path.split(":")[1],
83
- namespace: "memory"
84
- };
85
- });
86
- build2.onLoad({
87
- filter: /.*/,
88
- namespace: "memory"
89
- }, ({ path }) => {
90
- if (path === "main.tsx") {
91
- return {
92
- contents: source,
93
- loader: "tsx"
94
- };
95
- }
96
- });
97
- for (const module of providedModules) {
98
- build2.onResolve({
99
- filter: new RegExp(`^${module}$`)
100
- }, ({ path }) => {
101
- return {
102
- path,
103
- namespace: "injected-module"
104
- };
105
- });
106
- }
107
- build2.onLoad({
108
- filter: /.*/,
109
- namespace: "injected-module"
110
- }, ({ path }) => {
111
- const namedImports = imports.find((entry) => entry.moduleIdentifier === path)?.namedImports ?? [];
112
- return {
113
- contents: `
114
- const { ${namedImports.join(",")} } = window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}];
115
- export { ${namedImports.join(",")} };
116
- export default window.__DXOS_SANDBOX_MODULES__[${JSON.stringify(path)}].default;
117
- `,
118
- loader: "tsx"
119
- };
120
- });
121
- }
122
- },
123
- httpPlugin
124
- ]
125
- });
126
- log("compile complete", result.metafile, {
127
- F: __dxlog_file,
128
- L: 137,
129
- S: this,
130
- C: (f, a) => f(...a)
131
- });
132
- const entryPoint = "userFunc.js";
133
- return {
134
- timestamp: Date.now(),
135
- sourceHash,
136
- imports: this.analyzeImports(result),
137
- entryPoint,
138
- asset: result.outputFiles[0].contents,
139
- bundle: result.outputFiles[0].text
140
- };
141
- } catch (err) {
142
- return {
143
- timestamp: Date.now(),
144
- sourceHash,
145
- error: err
146
- };
147
- }
148
- }
149
- // TODO(dmaretskyi): In the future we can replace the compiler with SWC with plugins running in WASM.
150
- analyzeImports(result) {
151
- invariant(result.outputFiles, void 0, {
152
- F: __dxlog_file,
153
- L: 155,
154
- S: this,
155
- A: [
156
- "result.outputFiles",
157
- ""
158
- ]
159
- });
160
- const parsedImports = allMatches(IMPORT_REGEX, result.outputFiles[0].text);
161
- return Object.values(result.metafile.outputs)[0].imports.map((entry) => {
162
- const namedImports = [];
163
- const parsedImport = parsedImports.find((capture) => capture?.[4] === entry.path);
164
- if (parsedImport?.[2]) {
165
- NAMED_IMPORTS_REGEX.lastIndex = 0;
166
- const namedImportsMatch = NAMED_IMPORTS_REGEX.exec(parsedImport[2]);
167
- if (namedImportsMatch) {
168
- namedImportsMatch[1].split(",").forEach((importName) => {
169
- namedImports.push(importName.trim());
170
- });
171
- }
172
- }
173
- return {
174
- moduleUrl: entry.path,
175
- defaultImport: !!parsedImport?.[1],
176
- namedImports
177
- };
178
- });
179
- }
180
- analyzeSourceFileImports(code) {
181
- const parsedImports = allMatches(IMPORT_REGEX, code);
182
- return parsedImports.map((capture) => {
183
- return {
184
- defaultImportName: capture[1],
185
- namedImports: capture[2]?.split(",").map((importName) => importName.trim()),
186
- wildcardImportName: capture[3],
187
- moduleIdentifier: capture[4],
188
- quotes: capture[5]
189
- };
190
- });
191
- }
192
- };
193
- 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;
194
- var NAMED_IMPORTS_REGEX = /[ \n\t]*{((?:[ \n\t]*[^ \n\t"'{}]+[ \n\t]*,?)+)}[ \n\t]*/gm;
195
- var allMatches = (regex, str) => {
196
- let match;
197
- const matches = [];
198
- regex.lastIndex = 0;
199
- while (match = regex.exec(str)) {
200
- matches.push(match);
201
- }
202
- return matches;
203
- };
204
- var analyzeSourceFileImports = (code) => {
205
- const parsedImports = allMatches(IMPORT_REGEX, code);
206
- return parsedImports.map((capture) => {
207
- return {
208
- defaultImportName: capture[1],
209
- namedImports: capture[2]?.trim().slice(1, -1).split(",").map((importName) => importName.trim()),
210
- wildcardImportName: capture[3],
211
- moduleIdentifier: capture[4],
212
- quotes: capture[5]
213
- };
214
- });
215
- };
216
- var MAX_RETRIES = 5;
217
- var INITIAL_DELAY = 1e3;
218
- var httpPlugin = {
219
- name: "http",
220
- setup: (build2) => {
221
- build2.onResolve({
222
- filter: /^https?:\/\//
223
- }, (args) => ({
224
- path: args.path,
225
- namespace: "http-url"
226
- }));
227
- build2.onResolve({
228
- filter: /.*/,
229
- namespace: "http-url"
230
- }, (args) => ({
231
- path: new URL(args.path, args.importer).toString(),
232
- namespace: "http-url"
233
- }));
234
- build2.onLoad({
235
- filter: /.*/,
236
- namespace: "http-url"
237
- }, async (args) => {
238
- return Effect.gen(function* () {
239
- const response = yield* HttpClient.get(args.path);
240
- if (response.status !== 200) {
241
- throw new Error(`failed to fetch: ${response.status}`);
242
- }
243
- const text = yield* response.text;
244
- return {
245
- contents: text,
246
- loader: "jsx"
247
- };
248
- }).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);
249
- });
250
- }
251
- };
252
- export {
253
- Bundler,
254
- initializeBundler
255
- };
256
- //# sourceMappingURL=index.mjs.map