@dxos/functions 0.8.4-main.fd6878d → 0.8.4-staging.60fe92afc8

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