@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
@@ -0,0 +1,452 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
8
+ import * as Option from 'effect/Option';
9
+ import * as Schema from 'effect/Schema';
10
+ import * as SchemaAST from 'effect/SchemaAST';
11
+
12
+ import { AiModelResolver, AiService, OpaqueToolkit } from '@dxos/ai';
13
+ import { AnthropicResolver } from '@dxos/ai/resolvers';
14
+ import {
15
+ Blueprint,
16
+ FunctionError,
17
+ InvalidOperationInputError,
18
+ InvalidOperationOutputError,
19
+ Operation,
20
+ OperationRegistry,
21
+ Trace,
22
+ } from '@dxos/compute';
23
+ import { LifecycleState, Resource } from '@dxos/context';
24
+ import { Database, Feed, JsonSchema, Ref, type Type } from '@dxos/echo';
25
+ import { createFeedServiceLayer, EchoClient, type EchoDatabaseImpl, type QueueFactory } from '@dxos/echo-db';
26
+ import { refFromEncodedReference } from '@dxos/echo/internal';
27
+ import { runAndForwardErrors } from '@dxos/effect';
28
+ import { assertState, failedInvariant, invariant } from '@dxos/invariant';
29
+ import { PublicKey, type SpaceId } from '@dxos/keys';
30
+ import { log } from '@dxos/log';
31
+ import { EdgeFunctionEnv, ErrorCodec, type FunctionProtocol, type TraceProtocol } from '@dxos/protocols';
32
+
33
+ import { type FunctionServices } from '../sdk';
34
+ import {
35
+ configuredCredentialsLayer,
36
+ credentialsLayerFromDatabase,
37
+ FunctionInvocationService,
38
+ QueueService,
39
+ } from '../services';
40
+ import { FunctionsAiHttpClient } from './functions-ai-http-client';
41
+
42
+ export interface FunctionWrappingOptions {
43
+ /**
44
+ * Additional types to register with the database.
45
+ */
46
+ types?: Type.AnyEntity[];
47
+
48
+ /**
49
+ * Toolkits to make available via the `OpaqueToolkitProvider`.
50
+ */
51
+ toolkits?: OpaqueToolkit.OpaqueToolkit[];
52
+
53
+ /**
54
+ * Blueprint registry to expose as `Blueprint.RegistryService` inside handler Effects.
55
+ * Required for operations that declare `Blueprint.RegistryService` in their `services` list.
56
+ */
57
+ blueprintRegistry?: Blueprint.Registry;
58
+ }
59
+
60
+ /**
61
+ * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.
62
+ */
63
+ export const wrapFunctionHandler = (
64
+ func: Operation.WithHandler<Operation.Definition.Any>,
65
+ opts: FunctionWrappingOptions = {},
66
+ ): FunctionProtocol.Func => {
67
+ if (!Operation.isOperationWithHandler(func)) {
68
+ throw new TypeError('Expected operation with handler');
69
+ }
70
+
71
+ const serviceTags = func.services.map((service) => service.key);
72
+
73
+ return {
74
+ meta: {
75
+ key: func.meta.key,
76
+ name: func.meta.name,
77
+ description: func.meta.description,
78
+ inputSchema: JsonSchema.toJsonSchema(func.input),
79
+ outputSchema: func.output === undefined ? undefined : JsonSchema.toJsonSchema(func.output),
80
+ services: func.services.map((service) => service.key),
81
+ },
82
+ handler: async ({ data, context }) => {
83
+ if (
84
+ (serviceTags.includes(Database.Service.key) ||
85
+ serviceTags.includes(QueueService.key) ||
86
+ serviceTags.includes(Feed.FeedService.key)) &&
87
+ (!context.services.dataService || !context.services.queryService)
88
+ ) {
89
+ throw new FunctionError({
90
+ message: 'Services not provided: dataService, queryService',
91
+ });
92
+ }
93
+
94
+ // eslint-disable-next-line no-useless-catch
95
+ try {
96
+ if (!SchemaAST.isAnyKeyword(func.input.ast)) {
97
+ try {
98
+ Schema.validateSync(func.input, { onExcessProperty: 'error' })(data);
99
+ } catch (error: any) {
100
+ throw new InvalidOperationInputError({
101
+ message: `Operation input did not match schema (${func.meta.key}): ${error.message}`,
102
+ cause: error,
103
+ });
104
+ }
105
+ }
106
+
107
+ await using funcContext = await new FunctionContext(context, opts).open();
108
+
109
+ const types = [...(opts.types ?? []), ...(func.types ?? [])];
110
+ if (types.length > 0) {
111
+ invariant(funcContext.db, 'Database is required for functions with types');
112
+ await funcContext.db.graph.schemaRegistry.register(types as Type.AnyEntity[]);
113
+ }
114
+
115
+ const dataWithDecodedRefs =
116
+ funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast)
117
+ ? decodeRefsFromSchema(func.input.ast, data, funcContext.db)
118
+ : data;
119
+
120
+ let result: any = await func.handler(dataWithDecodedRefs);
121
+
122
+ if (Effect.isEffect(result)) {
123
+ result = await runAndForwardErrors(
124
+ (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(
125
+ Effect.orDie,
126
+ Effect.provide(funcContext.createLayer()),
127
+ ),
128
+ );
129
+ }
130
+
131
+ // Flush in-memory ECHO writes before the function scope closes.
132
+ // Writes performed by `db.add` / `db.remove` are buffered in the in-memory
133
+ // `EchoDatabaseImpl` and only pushed across the `DataService` binding when
134
+ // `db.flush({ disk })` is called. `FunctionContext._close` (invoked by the
135
+ // `await using` above) calls `db.close()` but does NOT flush, so mutations
136
+ // performed by handlers that declare `Database.Service` (e.g. `object-create`,
137
+ // `object-update`, `relation-create`) would be silently dropped before reaching
138
+ // the edge `AutomergeReplicator`. Flushing here closes that hole.
139
+ if (serviceTags.includes(Database.Service.key) && funcContext.db) {
140
+ await funcContext.db.flush({ disk: true, indexes: false });
141
+ }
142
+
143
+ if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {
144
+ try {
145
+ Schema.validateSync(func.output, { onExcessProperty: 'error' })(result);
146
+ } catch (error: any) {
147
+ throw new InvalidOperationOutputError({
148
+ message: `Operation output did not match schema (${func.meta.key}): ${error.message}`,
149
+ cause: error,
150
+ });
151
+ }
152
+ }
153
+
154
+ return result;
155
+ } catch (error) {
156
+ // TODO(dmaretskyi): We might do error wrapping here and add extra context.
157
+ throw error;
158
+ }
159
+ },
160
+ };
161
+ };
162
+
163
+ /**
164
+ * Container for services and context for a function.
165
+ */
166
+ class FunctionContext extends Resource {
167
+ readonly context: FunctionProtocol.Context;
168
+ readonly client: EchoClient | undefined;
169
+ db: EchoDatabaseImpl | undefined;
170
+ queues: QueueFactory | undefined;
171
+ readonly opts: FunctionWrappingOptions;
172
+
173
+ constructor(context: FunctionProtocol.Context, opts: FunctionWrappingOptions) {
174
+ super();
175
+ this.context = context;
176
+ this.opts = opts;
177
+ if (context.services.dataService && context.services.queryService) {
178
+ this.client = new EchoClient().connectToService({
179
+ dataService: context.services.dataService,
180
+ queryService: context.services.queryService,
181
+ queueService: context.services.queueService,
182
+ });
183
+ }
184
+ }
185
+
186
+ override async _open() {
187
+ await this.client?.open();
188
+ this.db =
189
+ this.client && this.context.spaceId
190
+ ? this.client.constructDatabase({
191
+ spaceId: this.context.spaceId ?? failedInvariant(),
192
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),
193
+ reactiveSchemaQuery: false,
194
+ preloadSchemaOnOpen: false,
195
+ })
196
+ : undefined;
197
+
198
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context'));
199
+ await this.db?.open();
200
+ this.queues =
201
+ this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : undefined;
202
+ }
203
+
204
+ override async _close() {
205
+ await this.db?.close();
206
+ await this.client?.close();
207
+ }
208
+
209
+ createLayer(): Layer.Layer<FunctionServices> {
210
+ assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');
211
+
212
+ const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;
213
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
214
+ const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
215
+ const credentials = dbLayer
216
+ ? credentialsLayerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))
217
+ : configuredCredentialsLayer([]);
218
+
219
+ const aiLayer = this.context.services.functionsAiService
220
+ ? InternalAiServiceLayer(this.context.services.functionsAiService)
221
+ : AiService.notAvailable;
222
+
223
+ const operationServiceLayer = this.context.services.functionsService
224
+ ? makeOperationServiceLayer(this.context.services.functionsService)
225
+ : unavailableOperationServiceLayer;
226
+
227
+ const operationRegistryLayer = this.context.services.functionsService
228
+ ? makeOperationRegistryLayer(this.context.services.functionsService, this.context.spaceId as SpaceId | undefined)
229
+ : emptyOperationRegistryLayer;
230
+
231
+ const traceWriterLayer = this.context.services.traceService
232
+ ? makeTraceWriterLayer(this.context.services.traceService)
233
+ : Trace.writerLayerNoop;
234
+
235
+ log('Creating function context layer', {
236
+ traceService: !!this.context.services.traceService,
237
+ functionsService: !!this.context.services.functionsService,
238
+ functionsAiService: !!this.context.services.functionsAiService,
239
+ spaceId: this.context.spaceId,
240
+ spaceRootUrl: this.context.spaceRootUrl,
241
+ toolkits: this.opts.toolkits?.length ?? 0,
242
+ types: this.opts.types?.length ?? 0,
243
+ });
244
+
245
+ const blueprintRegistryLayer = this.opts.blueprintRegistry
246
+ ? Layer.succeed(Blueprint.RegistryService, this.opts.blueprintRegistry)
247
+ : Blueprint.RegistryService.notAvailable;
248
+
249
+ return Layer.mergeAll(
250
+ dbLayer,
251
+ queuesLayer,
252
+ feedLayer,
253
+ credentials,
254
+ operationServiceLayer,
255
+ operationRegistryLayer,
256
+ aiLayer,
257
+ OpaqueToolkit.providerLayer(OpaqueToolkit.merge(...(this.opts.toolkits ?? []))),
258
+ traceWriterLayer,
259
+ blueprintRegistryLayer,
260
+
261
+ // `FunctionInvocationService` is deprecated; new code should yield `Operation.Service`.
262
+ // The cloudflare wrapper provides only the unavailable layer to satisfy the (still-present)
263
+ // type union — handlers that yield it will die at invocation time.
264
+ FunctionInvocationService.layerNotAvailable,
265
+ );
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Backs `Trace.TraceService` with the EDGE-provided `TraceService` so that operation
271
+ * handlers can write trace events that are forwarded to the runtime's trace sink.
272
+ */
273
+ const makeTraceWriterLayer = (traceService: TraceProtocol.TraceService): Layer.Layer<Trace.TraceService> =>
274
+ Layer.succeed(Trace.TraceService, {
275
+ write: (eventType, payload) => {
276
+ log('Writing trace event', {
277
+ eventType: eventType.key,
278
+ });
279
+ traceService.write([
280
+ {
281
+ key: eventType.key,
282
+ isEphemeral: eventType.isEphemeral,
283
+ data: payload,
284
+ },
285
+ ]);
286
+ },
287
+ });
288
+
289
+ /**
290
+ * AI service layer that proxies HTTP requests through the EDGE-provided `FunctionsAiService`.
291
+ */
292
+ const InternalAiServiceLayer = (functionsAiService: EdgeFunctionEnv.FunctionsAiService) =>
293
+ AiModelResolver.AiModelResolver.buildAiService.pipe(
294
+ Layer.provide(
295
+ AnthropicResolver.make().pipe(
296
+ Layer.provide(
297
+ AnthropicClient.layer({
298
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
299
+ apiUrl: 'http://internal/provider/anthropic',
300
+ }).pipe(Layer.provide(FunctionsAiHttpClient.layer(functionsAiService))),
301
+ ),
302
+ ),
303
+ ),
304
+ );
305
+
306
+ /**
307
+ * Backs `Operation.Service` with the EDGE-provided `FunctionsService` so that operation
308
+ * handlers can invoke other deployed operations remotely. The `deployedId` on the operation
309
+ * definition is used as the routing key.
310
+ */
311
+ const makeOperationServiceLayer = (
312
+ functionsService: EdgeFunctionEnv.FunctionsService,
313
+ ): Layer.Layer<Operation.Service> => {
314
+ const invokeRemote = async (
315
+ op: Operation.Definition.Any,
316
+ input: unknown,
317
+ options?: Operation.InvokeOptions,
318
+ ): Promise<{ data?: unknown; error?: Error }> => {
319
+ invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`);
320
+ const result = await functionsService.invoke(op.meta.deployedId, input, {
321
+ spaceId: options?.spaceId,
322
+ });
323
+ if (result._kind === 'success') {
324
+ return { data: result.data };
325
+ }
326
+ return { error: ErrorCodec.decode(result.error) };
327
+ };
328
+
329
+ return Layer.succeed(Operation.Service, {
330
+ invoke: ((op: Operation.Definition.Any, input: unknown, options?: Operation.InvokeOptions) =>
331
+ Effect.tryPromise(() => invokeRemote(op, input, options)).pipe(
332
+ Effect.orDie,
333
+ Effect.flatMap((outcome) =>
334
+ outcome.error ? Effect.die(outcome.error) : Effect.succeed(outcome.data as never),
335
+ ),
336
+ )) as Operation.OperationService['invoke'],
337
+ schedule: ((op: Operation.Definition.Any, input: unknown) =>
338
+ Effect.sync(() => {
339
+ invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`);
340
+ // Fire and forget — schedule is intentionally non-awaiting.
341
+ void functionsService.invoke(op.meta.deployedId, input).catch(() => {
342
+ // Swallow errors — schedule is observability-only.
343
+ });
344
+ })) as Operation.OperationService['schedule'],
345
+ invokePromise: ((op: Operation.Definition.Any, input: unknown, options?: Operation.InvokeOptions) =>
346
+ invokeRemote(op, input, options).catch((error: unknown) => ({
347
+ error: error instanceof Error ? error : new Error(String(error)),
348
+ }))) as Operation.OperationService['invokePromise'],
349
+ } satisfies Operation.OperationService);
350
+ };
351
+
352
+ const unavailableOperationServiceLayer = Layer.succeed(Operation.Service, {
353
+ invoke: () => Effect.die('Operation.Service is not available: missing functionsService in EDGE context.'),
354
+ schedule: () => Effect.die('Operation.Service is not available: missing functionsService in EDGE context.'),
355
+ invokePromise: async () => ({
356
+ error: new Error('Operation.Service is not available: missing functionsService in EDGE context.'),
357
+ }),
358
+ } as Operation.OperationService);
359
+
360
+ /**
361
+ * Backs `OperationRegistry.Service` with the EDGE-provided `FunctionsService.query`. Returns
362
+ * the first persistent operation matching the requested key, or `Option.none()` when not found.
363
+ */
364
+ const makeOperationRegistryLayer = (
365
+ functionsService: EdgeFunctionEnv.FunctionsService,
366
+ spaceId: SpaceId | undefined,
367
+ ): Layer.Layer<OperationRegistry.Service> =>
368
+ Layer.succeed(OperationRegistry.Service, {
369
+ resolve: (key: string) =>
370
+ Effect.gen(function* () {
371
+ const records = yield* Effect.tryPromise(() => functionsService.query({ spaceId })).pipe(Effect.orDie);
372
+ const match = (records as Operation.PersistentOperation[]).find((record) => Operation.getKey(record) === key);
373
+ return match ? Option.some(Operation.deserialize(match)) : Option.none();
374
+ }),
375
+ });
376
+
377
+ const emptyOperationRegistryLayer = Layer.succeed(OperationRegistry.Service, {
378
+ resolve: () => Effect.succeed(Option.none()),
379
+ });
380
+
381
+ const decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {
382
+ if (value == null) {
383
+ return value;
384
+ }
385
+
386
+ const encoded = SchemaAST.encodedBoundAST(ast);
387
+ if (Ref.isRefType(encoded)) {
388
+ if (Ref.isRef(value)) {
389
+ return value;
390
+ }
391
+
392
+ if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {
393
+ const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });
394
+ return refFromEncodedReference(value as any, resolver);
395
+ }
396
+
397
+ return value;
398
+ }
399
+
400
+ switch (encoded._tag) {
401
+ case 'TypeLiteral': {
402
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
403
+ return value;
404
+ }
405
+ const result: Record<string, unknown> = { ...(value as any) };
406
+ for (const prop of SchemaAST.getPropertySignatures(encoded)) {
407
+ const key = prop.name.toString();
408
+ if (key in result) {
409
+ result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);
410
+ }
411
+ }
412
+ return result;
413
+ }
414
+
415
+ case 'TupleType': {
416
+ if (!Array.isArray(value)) {
417
+ return value;
418
+ }
419
+
420
+ // For arrays, effect uses TupleType with empty elements and a single rest element.
421
+ if (encoded.elements.length === 0 && encoded.rest.length === 1) {
422
+ const elementType = encoded.rest[0].type;
423
+ return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));
424
+ }
425
+
426
+ return value;
427
+ }
428
+
429
+ case 'Union': {
430
+ // Optional values are represented as union with undefined.
431
+ const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));
432
+ if (nonUndefined.length === 1) {
433
+ return decodeRefsFromSchema(nonUndefined[0], value, db);
434
+ }
435
+
436
+ // For other unions we can't safely pick a branch without validating.
437
+ return value;
438
+ }
439
+
440
+ case 'Suspend': {
441
+ return decodeRefsFromSchema(encoded.f(), value, db);
442
+ }
443
+
444
+ case 'Refinement': {
445
+ return decodeRefsFromSchema(encoded.from, value, db);
446
+ }
447
+
448
+ default: {
449
+ return value;
450
+ }
451
+ }
452
+ };
package/src/sdk.ts ADDED
@@ -0,0 +1,31 @@
1
+ //
2
+ // Copyright 2023 DXOS.org
3
+ //
4
+
5
+ import { type AiService } from '@dxos/ai';
6
+ import { type Credential, type Operation, type Trace } from '@dxos/compute';
7
+ import { type Database, type Feed } from '@dxos/echo';
8
+
9
+ import { type FunctionInvocationService, type QueueService } from './services';
10
+
11
+ // TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
12
+ // https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
13
+ // https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions
14
+ // https://www.npmjs.com/package/aws-lambda
15
+
16
+ /**
17
+ * Services that are available to invoked functions.
18
+ * @deprecated
19
+ */
20
+ export type FunctionServices =
21
+ | AiService.AiService
22
+ | Credential.CredentialsService
23
+ | Database.Service
24
+ // TODO(wittjosiah): Remove QueueService — use Feed.FeedService instead.
25
+ | QueueService
26
+ | Feed.FeedService
27
+ | Trace.TraceService
28
+ // TODO(dmaretskyi): `FunctionInvocationService` is being phased out in favour of `Operation.Service`;
29
+ // it's kept in the union until `functions-runtime/local-function-execution.ts` migrates.
30
+ | FunctionInvocationService
31
+ | Operation.Service;
@@ -10,118 +10,23 @@ import * as Effect from 'effect/Effect';
10
10
  import * as Layer from 'effect/Layer';
11
11
  import * as Redacted from 'effect/Redacted';
12
12
 
13
- import { Query } from '@dxos/echo';
14
- import { DataType } from '@dxos/schema';
15
-
16
- import { DatabaseService } from './database';
17
-
18
- export type CredentialQuery = {
19
- service?: string;
20
- };
21
-
22
- // TODO(dmaretskyi): Unify with other apis.
23
- // packages/sdk/schema/src/common/access-token.ts
24
- export type ServiceCredential = {
25
- service: string;
26
-
27
- // TODO(dmaretskyi): Build out.
28
- apiKey?: string;
29
- };
30
-
31
- export class CredentialsService extends Context.Tag('@dxos/functions/CredentialsService')<
32
- CredentialsService,
33
- {
34
- /**
35
- * Query all.
36
- */
37
- queryCredentials: (query: CredentialQuery) => Promise<ServiceCredential[]>;
38
-
39
- /**
40
- * Get a single credential.
41
- * @throws {Error} If no credential is found.
42
- */
43
- getCredential: (query: CredentialQuery) => Promise<ServiceCredential>;
44
- }
45
- >() {
46
- static getCredential = (query: CredentialQuery): Effect.Effect<ServiceCredential, never, CredentialsService> =>
47
- Effect.gen(function* () {
48
- const credentials = yield* CredentialsService;
49
- return yield* Effect.promise(() => credentials.getCredential(query));
50
- });
51
-
52
- static getApiKey = (query: CredentialQuery): Effect.Effect<Redacted.Redacted<string>, never, CredentialsService> =>
53
- Effect.gen(function* () {
54
- const credential = yield* CredentialsService.getCredential(query);
55
- if (!credential.apiKey) {
56
- throw new Error(`API key not found for service: ${query.service}`);
57
- }
58
- return Redacted.make(credential.apiKey);
59
- });
60
-
61
- static configuredLayer = (credentials: ServiceCredential[]) =>
62
- Layer.succeed(CredentialsService, new ConfiguredCredentialsService(credentials));
63
-
64
- static layerConfig = (credentials: { service: string; apiKey: Config.Config<Redacted.Redacted<string>> }[]) =>
65
- Layer.effect(
66
- CredentialsService,
67
- Effect.gen(function* () {
68
- const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>
69
- Effect.gen(function* () {
70
- return {
71
- service,
72
- apiKey: Redacted.value(yield* apiKey),
73
- };
74
- }),
75
- );
76
-
77
- return new ConfiguredCredentialsService(serviceCredentials);
78
- }),
79
- );
80
-
81
- static layerFromDatabase = () =>
82
- Layer.effect(
83
- CredentialsService,
84
- Effect.gen(function* () {
85
- const dbService = yield* DatabaseService;
86
- const queryCredentials = async (query: CredentialQuery): Promise<ServiceCredential[]> => {
87
- const { objects: accessTokens } = await dbService.db.query(Query.type(DataType.AccessToken)).run();
88
- return accessTokens
89
- .filter((accessToken) => accessToken.source === query.service)
90
- .map((accessToken) => ({
91
- service: accessToken.source,
92
- apiKey: accessToken.token,
93
- }));
94
- };
95
- return {
96
- getCredential: async (query) => {
97
- const credentials = await queryCredentials(query);
98
- if (credentials.length === 0) {
99
- throw new Error(`Credential not found for service: ${query.service}`);
100
- }
101
-
102
- return credentials[0];
103
- },
104
- queryCredentials: async (query) => {
105
- return queryCredentials(query);
106
- },
107
- };
108
- }),
109
- );
110
- }
13
+ import { Credential } from '@dxos/compute';
14
+ import { Database, Query } from '@dxos/echo';
15
+ import { AccessToken } from '@dxos/types';
111
16
 
112
- export class ConfiguredCredentialsService implements Context.Tag.Service<CredentialsService> {
113
- constructor(private readonly credentials: ServiceCredential[] = []) {}
17
+ export class ConfiguredCredentialsService implements Context.Tag.Service<Credential.CredentialsService> {
18
+ constructor(private readonly credentials: Credential.ServiceCredential[] = []) {}
114
19
 
115
- addCredentials(credentials: ServiceCredential[]): ConfiguredCredentialsService {
20
+ addCredentials(credentials: Credential.ServiceCredential[]): ConfiguredCredentialsService {
116
21
  this.credentials.push(...credentials);
117
22
  return this;
118
23
  }
119
24
 
120
- async queryCredentials(query: CredentialQuery): Promise<ServiceCredential[]> {
25
+ async queryCredentials(query: Credential.CredentialQuery): Promise<Credential.ServiceCredential[]> {
121
26
  return this.credentials.filter((credential) => credential.service === query.service);
122
27
  }
123
28
 
124
- async getCredential(query: CredentialQuery): Promise<ServiceCredential> {
29
+ async getCredential(query: Credential.CredentialQuery): Promise<Credential.ServiceCredential> {
125
30
  const credential = this.credentials.find((credential) => credential.service === query.service);
126
31
  if (!credential) {
127
32
  throw new Error(`Credential not found for service: ${query.service}`);
@@ -132,13 +37,79 @@ export class ConfiguredCredentialsService implements Context.Tag.Service<Credent
132
37
  }
133
38
 
134
39
  /**
135
- * Maps the request to include the API key from the credential.
40
+ * Maps the request to include the given token in the Authorization header.
136
41
  */
137
- export const withAuthorization = (query: CredentialQuery, kind?: 'Bearer' | 'Basic') =>
138
- HttpClient.mapRequestEffect(
139
- Effect.fnUntraced(function* (request) {
140
- const key = yield* CredentialsService.getApiKey(query).pipe(Effect.map(Redacted.value));
141
- const authorization = kind ? `${kind} ${key}` : key;
142
- return HttpClientRequest.setHeader(request, 'Authorization', authorization);
42
+ export const withAuthorization = (token: string, kind?: 'Bearer' | 'Basic') =>
43
+ HttpClient.mapRequest((request) => {
44
+ const authorization = kind ? `${kind} ${token}` : token;
45
+ return HttpClientRequest.setHeader(request, 'Authorization', authorization);
46
+ });
47
+
48
+ export const configuredCredentialsLayer = (credentials: Credential.ServiceCredential[]) =>
49
+ Layer.succeed(Credential.CredentialsService, new ConfiguredCredentialsService(credentials));
50
+
51
+ export const credentialsLayerConfig = (
52
+ credentials: {
53
+ service: string;
54
+ apiKey: Config.Config<Redacted.Redacted<string>>;
55
+ }[],
56
+ ) =>
57
+ Layer.effect(
58
+ Credential.CredentialsService,
59
+ Effect.gen(function* () {
60
+ const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>
61
+ Effect.gen(function* () {
62
+ return {
63
+ service,
64
+ apiKey: Redacted.value(yield* apiKey),
65
+ };
66
+ }),
67
+ );
68
+
69
+ return new ConfiguredCredentialsService(serviceCredentials);
70
+ }),
71
+ );
72
+
73
+ export const credentialsLayerFromDatabase = ({ caching = false }: { caching?: boolean } = {}) =>
74
+ Layer.effect(
75
+ Credential.CredentialsService,
76
+ Effect.gen(function* () {
77
+ const dbService = yield* Database.Service;
78
+ const cache = new Map<string, Credential.ServiceCredential[]>();
79
+
80
+ const queryCredentials = async (query: Credential.CredentialQuery): Promise<Credential.ServiceCredential[]> => {
81
+ const cacheKey = JSON.stringify(query);
82
+ if (caching && cache.has(cacheKey)) {
83
+ return cache.get(cacheKey)!;
84
+ }
85
+
86
+ const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
87
+ const credentials = accessTokens
88
+ .filter((accessToken) => accessToken.source === query.service)
89
+ .map((accessToken) => ({
90
+ service: accessToken.source,
91
+ apiKey: accessToken.token,
92
+ }));
93
+
94
+ if (caching) {
95
+ cache.set(cacheKey, credentials);
96
+ }
97
+
98
+ return credentials;
99
+ };
100
+
101
+ return {
102
+ getCredential: async (query) => {
103
+ const credentials = await queryCredentials(query);
104
+ if (credentials.length === 0) {
105
+ throw new Error(`Credential not found for service: ${query.service}`);
106
+ }
107
+
108
+ return credentials[0];
109
+ },
110
+ queryCredentials: async (query) => {
111
+ return queryCredentials(query);
112
+ },
113
+ };
143
114
  }),
144
115
  );