@dxos/functions 0.8.4-main.7ace549 → 0.8.4-main.8360d9e660

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 (59) hide show
  1. package/README.md +4 -6
  2. package/dist/lib/{browser → neutral}/index.mjs +327 -114
  3. package/dist/lib/neutral/index.mjs.map +7 -0
  4. package/dist/lib/neutral/meta.json +1 -0
  5. package/dist/types/src/errors.d.ts +24 -32
  6. package/dist/types/src/errors.d.ts.map +1 -1
  7. package/dist/types/src/example/index.d.ts +5 -5
  8. package/dist/types/src/example/index.d.ts.map +1 -1
  9. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  10. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  11. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  12. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  13. package/dist/types/src/protocol/protocol.d.ts.map +1 -1
  14. package/dist/types/src/sdk.d.ts +26 -9
  15. package/dist/types/src/sdk.d.ts.map +1 -1
  16. package/dist/types/src/services/credentials.d.ts +6 -4
  17. package/dist/types/src/services/credentials.d.ts.map +1 -1
  18. package/dist/types/src/services/event-logger.d.ts +25 -31
  19. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  20. package/dist/types/src/services/function-invocation-service.d.ts +5 -0
  21. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  22. package/dist/types/src/services/index.d.ts +0 -1
  23. package/dist/types/src/services/index.d.ts.map +1 -1
  24. package/dist/types/src/services/tracing.d.ts +37 -3
  25. package/dist/types/src/services/tracing.d.ts.map +1 -1
  26. package/dist/types/src/types/Function.d.ts +34 -45
  27. package/dist/types/src/types/Function.d.ts.map +1 -1
  28. package/dist/types/src/types/Script.d.ts +8 -15
  29. package/dist/types/src/types/Script.d.ts.map +1 -1
  30. package/dist/types/src/types/Trigger.d.ts +59 -78
  31. package/dist/types/src/types/Trigger.d.ts.map +1 -1
  32. package/dist/types/src/types/TriggerEvent.d.ts +44 -12
  33. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
  34. package/dist/types/src/types/url.d.ts +6 -5
  35. package/dist/types/src/types/url.d.ts.map +1 -1
  36. package/dist/types/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +23 -18
  38. package/src/errors.ts +4 -4
  39. package/src/example/forex-effect.ts +1 -1
  40. package/src/example/index.ts +8 -8
  41. package/src/operation-compatibility.test.ts +185 -0
  42. package/src/protocol/functions-ai-http-client.ts +67 -0
  43. package/src/protocol/protocol.ts +117 -15
  44. package/src/sdk.ts +73 -16
  45. package/src/services/credentials.ts +31 -15
  46. package/src/services/event-logger.ts +2 -2
  47. package/src/services/function-invocation-service.ts +14 -0
  48. package/src/services/index.ts +0 -2
  49. package/src/services/tracing.ts +63 -4
  50. package/src/types/Function.ts +16 -13
  51. package/src/types/Script.ts +9 -4
  52. package/src/types/Trigger.ts +30 -16
  53. package/src/types/TriggerEvent.ts +29 -29
  54. package/src/types/url.ts +6 -5
  55. package/dist/lib/browser/index.mjs.map +0 -7
  56. package/dist/lib/browser/meta.json +0 -1
  57. package/dist/lib/node-esm/index.mjs +0 -1031
  58. package/dist/lib/node-esm/index.mjs.map +0 -7
  59. package/dist/lib/node-esm/meta.json +0 -1
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "@dxos/functions",
3
- "version": "0.8.4-main.7ace549",
3
+ "version": "0.8.4-main.8360d9e660",
4
4
  "description": "Functions API.",
5
5
  "homepage": "https://dxos.org",
6
6
  "bugs": "https://github.com/dxos/dxos/issues",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/dxos/dxos"
10
+ },
7
11
  "license": "MIT",
8
12
  "author": "info@dxos.org",
9
13
  "sideEffects": false,
@@ -12,8 +16,7 @@
12
16
  ".": {
13
17
  "source": "./src/index.ts",
14
18
  "types": "./dist/types/src/index.d.ts",
15
- "browser": "./dist/lib/browser/index.mjs",
16
- "node": "./dist/lib/node-esm/index.mjs"
19
+ "default": "./dist/lib/neutral/index.mjs"
17
20
  }
18
21
  },
19
22
  "types": "dist/types/src/index.d.ts",
@@ -23,21 +26,23 @@
23
26
  "src"
24
27
  ],
25
28
  "dependencies": {
26
- "@effect/platform": "0.92.1",
27
- "effect": "3.18.3",
28
- "@dxos/ai": "0.8.4-main.7ace549",
29
- "@dxos/context": "0.8.4-main.7ace549",
30
- "@dxos/effect": "0.8.4-main.7ace549",
31
- "@dxos/errors": "0.8.4-main.7ace549",
32
- "@dxos/echo": "0.8.4-main.7ace549",
33
- "@dxos/invariant": "0.8.4-main.7ace549",
34
- "@dxos/echo-db": "0.8.4-main.7ace549",
35
- "@dxos/log": "0.8.4-main.7ace549",
36
- "@dxos/node-std": "0.8.4-main.7ace549",
37
- "@dxos/protocols": "0.8.4-main.7ace549",
38
- "@dxos/schema": "0.8.4-main.7ace549",
39
- "@dxos/types": "0.8.4-main.7ace549",
40
- "@dxos/keys": "0.8.4-main.7ace549"
29
+ "@effect/ai-anthropic": "0.23.0",
30
+ "@effect/platform": "0.94.4",
31
+ "effect": "3.19.16",
32
+ "@dxos/ai": "0.8.4-main.8360d9e660",
33
+ "@dxos/context": "0.8.4-main.8360d9e660",
34
+ "@dxos/echo": "0.8.4-main.8360d9e660",
35
+ "@dxos/effect": "0.8.4-main.8360d9e660",
36
+ "@dxos/invariant": "0.8.4-main.8360d9e660",
37
+ "@dxos/keys": "0.8.4-main.8360d9e660",
38
+ "@dxos/log": "0.8.4-main.8360d9e660",
39
+ "@dxos/node-std": "0.8.4-main.8360d9e660",
40
+ "@dxos/echo-db": "0.8.4-main.8360d9e660",
41
+ "@dxos/protocols": "0.8.4-main.8360d9e660",
42
+ "@dxos/schema": "0.8.4-main.8360d9e660",
43
+ "@dxos/types": "0.8.4-main.8360d9e660",
44
+ "@dxos/operation": "0.8.4-main.8360d9e660",
45
+ "@dxos/errors": "0.8.4-main.8360d9e660"
41
46
  },
42
47
  "publishConfig": {
43
48
  "access": "public"
package/src/errors.ts CHANGED
@@ -4,18 +4,18 @@
4
4
 
5
5
  import { BaseError, type BaseErrorOptions } from '@dxos/errors';
6
6
 
7
- export class ServiceNotAvailableError extends BaseError.extend('SERVICE_NOT_AVAILABLE', 'Service not available') {
7
+ export class ServiceNotAvailableError extends BaseError.extend('ServiceNotAvailable', 'Service not available') {
8
8
  constructor(service: string, options?: Omit<BaseErrorOptions, 'context'>) {
9
9
  super({ context: { service }, ...options });
10
10
  }
11
11
  }
12
12
 
13
- export class FunctionNotFoundError extends BaseError.extend('FUNCTION_NOT_FOUND', 'Function not found') {
13
+ export class FunctionNotFoundError extends BaseError.extend('FunctionNotFound', 'Function not found') {
14
14
  constructor(functionKey: string, options?: Omit<BaseErrorOptions, 'context'>) {
15
15
  super({ context: { function: functionKey }, ...options });
16
16
  }
17
17
  }
18
18
 
19
- export class FunctionError extends BaseError.extend('FUNCTION_ERROR', 'Function invocation error') {}
19
+ export class FunctionError extends BaseError.extend('FunctionError', 'Function invocation error') {}
20
20
 
21
- export class TriggerStateNotFoundError extends BaseError.extend('TRIGGER_STATE_NOT_FOUND', 'Trigger state not found') {}
21
+ export class TriggerStateNotFoundError extends BaseError.extend('TriggerStateNotFound', 'Trigger state not found') {}
@@ -14,7 +14,7 @@ import {
14
14
  import { Effect, Schedule } from 'https://esm.sh/effect@3.17.0?bundle=false';
15
15
 
16
16
  export default defineFunction({
17
- key: 'dxos.org/script/forex-effect',
17
+ key: 'org.dxos.script.forex-effect',
18
18
  name: 'Forex Effect',
19
19
  description: 'Returns the exchange rate between two currencies.',
20
20
 
@@ -2,12 +2,12 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { default as fib$ } from './fib';
6
- import { default as reply$ } from './reply';
7
- import { default as sleep$ } from './sleep';
5
+ import Fibonacci from './fib';
6
+ import Reply from './reply';
7
+ import Sleep from './sleep';
8
8
 
9
- export namespace Example {
10
- export const fib = fib$;
11
- export const reply = reply$;
12
- export const sleep = sleep$;
13
- }
9
+ export const ExampleFunctions = {
10
+ Fibonacci,
11
+ Reply,
12
+ Sleep,
13
+ };
@@ -0,0 +1,185 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Effect from 'effect/Effect';
6
+ import * as Schema from 'effect/Schema';
7
+ import { describe, expect, test } from 'vitest';
8
+
9
+ import { FunctionDefinition, defineFunction } from './sdk';
10
+
11
+ describe('Function/Operation Compatibility', () => {
12
+ test('can convert FunctionDefinition to OperationDefinition', () => {
13
+ const func = defineFunction({
14
+ key: 'test.function',
15
+ name: 'Test Function',
16
+ description: 'A test function',
17
+ inputSchema: Schema.Struct({ value: Schema.Number }),
18
+ outputSchema: Schema.Struct({ result: Schema.String }),
19
+ handler: async ({ data }) => {
20
+ return { result: data.value.toString() };
21
+ },
22
+ });
23
+
24
+ const op = FunctionDefinition.toOperation(func);
25
+
26
+ expect(op.meta.key).toBe('test.function');
27
+ expect(op.meta.name).toBe('Test Function');
28
+ expect(op.meta.description).toBe('A test function');
29
+ expect(Schema.isSchema(op.schema.input)).toBe(true);
30
+ expect(Schema.isSchema(op.schema.output)).toBe(true);
31
+ });
32
+
33
+ test('converted operation has matching schemas', () => {
34
+ const inputSchema = Schema.Struct({
35
+ name: Schema.String,
36
+ age: Schema.Number,
37
+ });
38
+ const outputSchema = Schema.Struct({
39
+ greeting: Schema.String,
40
+ });
41
+
42
+ const func = defineFunction({
43
+ key: 'test.greet',
44
+ name: 'Greet',
45
+ inputSchema,
46
+ outputSchema,
47
+ handler: async ({ data }) => {
48
+ return { greeting: `Hello, ${data.name}!` };
49
+ },
50
+ });
51
+
52
+ const op = FunctionDefinition.toOperation(func);
53
+
54
+ // Verify schemas match
55
+ const testInput = { name: 'Alice', age: 30 };
56
+ const validatedInput = Schema.decodeSync(op.schema.input)(testInput);
57
+ expect(validatedInput).toEqual(testInput);
58
+
59
+ const testOutput = { greeting: 'Hello, Alice!' };
60
+ const validatedOutput = Schema.decodeSync(op.schema.output)(testOutput);
61
+ expect(validatedOutput).toEqual(testOutput);
62
+ });
63
+
64
+ test('converted operation preserves metadata', () => {
65
+ const func = defineFunction({
66
+ key: 'test.meta',
67
+ name: 'Meta Test',
68
+ description: 'Tests metadata preservation',
69
+ inputSchema: Schema.Void,
70
+ outputSchema: Schema.Void,
71
+ handler: async () => {},
72
+ });
73
+
74
+ const op = FunctionDefinition.toOperation(func);
75
+
76
+ expect(op.meta.key).toBe('test.meta');
77
+ expect(op.meta.name).toBe('Meta Test');
78
+ expect(op.meta.description).toBe('Tests metadata preservation');
79
+ });
80
+
81
+ test('converted operation is pipeable', () => {
82
+ const func = defineFunction({
83
+ key: 'test.pipe',
84
+ name: 'Pipe Test',
85
+ inputSchema: Schema.Void,
86
+ outputSchema: Schema.Void,
87
+ handler: async () => {},
88
+ });
89
+
90
+ const op = FunctionDefinition.toOperation(func);
91
+
92
+ expect(typeof op.pipe).toBe('function');
93
+ });
94
+
95
+ test('handles functions without output schema', () => {
96
+ const func = defineFunction({
97
+ key: 'test.no-output',
98
+ name: 'No Output',
99
+ inputSchema: Schema.Struct({ value: Schema.Number }),
100
+ handler: async ({ data }) => {
101
+ return data.value * 2;
102
+ },
103
+ });
104
+
105
+ const op = FunctionDefinition.toOperation(func);
106
+
107
+ expect(op.meta.key).toBe('test.no-output');
108
+ expect(Schema.isSchema(op.schema.output)).toBe(true);
109
+ });
110
+
111
+ test('converted operation includes handler', () => {
112
+ const func = defineFunction({
113
+ key: 'test.handler',
114
+ name: 'Handler Test',
115
+ inputSchema: Schema.Struct({ value: Schema.Number }),
116
+ outputSchema: Schema.Struct({ doubled: Schema.Number }),
117
+ handler: async ({ data }) => {
118
+ return { doubled: data.value * 2 };
119
+ },
120
+ });
121
+
122
+ const op = FunctionDefinition.toOperation(func);
123
+
124
+ expect(op.handler).toBeDefined();
125
+ expect(typeof op.handler).toBe('function');
126
+ });
127
+
128
+ test('converted operation has handler function', () => {
129
+ const func = defineFunction({
130
+ key: 'test.execute',
131
+ name: 'Execute Test',
132
+ inputSchema: Schema.Struct({ value: Schema.Number }),
133
+ outputSchema: Schema.Struct({ result: Schema.Number }),
134
+ handler: async ({ data }) => {
135
+ return { result: data.value * 3 };
136
+ },
137
+ });
138
+
139
+ const op = FunctionDefinition.toOperation(func);
140
+
141
+ // Handler is present and is a function that returns an Effect
142
+ expect(op.handler).toBeDefined();
143
+ const effect = op.handler({ value: 5 });
144
+ // Verify it returns an Effect-like object
145
+ expect(effect).toHaveProperty('pipe');
146
+ });
147
+
148
+ test('converted operation works with Effect-based handlers', () => {
149
+ const func = defineFunction({
150
+ key: 'test.effect',
151
+ name: 'Effect Test',
152
+ inputSchema: Schema.Struct({ value: Schema.Number }),
153
+ outputSchema: Schema.Struct({ result: Schema.Number }),
154
+ handler: Effect.fn(function* ({ data }) {
155
+ return { result: data.value * 4 };
156
+ }),
157
+ });
158
+
159
+ const op = FunctionDefinition.toOperation(func);
160
+
161
+ // Handler is present and produces an Effect
162
+ expect(op.handler).toBeDefined();
163
+ const effect = op.handler({ value: 3 });
164
+ expect(effect).toHaveProperty('pipe');
165
+ });
166
+
167
+ test('converted operation works with synchronous handlers', () => {
168
+ const func = defineFunction({
169
+ key: 'test.sync',
170
+ name: 'Sync Test',
171
+ inputSchema: Schema.Struct({ value: Schema.Number }),
172
+ outputSchema: Schema.Struct({ result: Schema.Number }),
173
+ handler: ({ data }) => {
174
+ return { result: data.value * 5 };
175
+ },
176
+ });
177
+
178
+ const op = FunctionDefinition.toOperation(func);
179
+
180
+ // Handler is present and produces an Effect
181
+ expect(op.handler).toBeDefined();
182
+ const effect = op.handler({ value: 2 });
183
+ expect(effect).toHaveProperty('pipe');
184
+ });
185
+ });
@@ -0,0 +1,67 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Headers from '@effect/platform/Headers';
6
+ import * as HttpClient from '@effect/platform/HttpClient';
7
+ import * as HttpClientError from '@effect/platform/HttpClientError';
8
+ import * as HttpClientResponse from '@effect/platform/HttpClientResponse';
9
+ import * as Effect from 'effect/Effect';
10
+ import * as FiberRef from 'effect/FiberRef';
11
+ import * as Layer from 'effect/Layer';
12
+ import * as Stream from 'effect/Stream';
13
+
14
+ import { log } from '@dxos/log';
15
+ import { type EdgeFunctionEnv, ErrorCodec } from '@dxos/protocols';
16
+ /**
17
+ * Copy pasted from https://github.com/Effect-TS/effect/blob/main/packages/platform/src/internal/fetchHttpClient.ts
18
+ */
19
+ export const requestInitTagKey = '@effect/platform/FetchHttpClient/FetchOptions';
20
+
21
+ export class FunctionsAiHttpClient {
22
+ static make = (service: EdgeFunctionEnv.FunctionsAiService) =>
23
+ HttpClient.make((request, url, signal, fiber) => {
24
+ const context = fiber.getFiberRef(FiberRef.currentContext);
25
+ const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {};
26
+ const headers = options.headers
27
+ ? Headers.merge(Headers.fromInput(options.headers), request.headers)
28
+ : request.headers;
29
+
30
+ const send = (body: BodyInit | undefined) =>
31
+ Effect.tryPromise({
32
+ try: () =>
33
+ service.fetch(
34
+ new Request(url, {
35
+ ...options,
36
+ method: request.method,
37
+ headers,
38
+ body,
39
+ // Note: Don't pass signal - it can't be serialized through RPC
40
+ }),
41
+ ),
42
+ catch: (cause) => {
43
+ log.error('Failed to fetch', { errorSerialized: ErrorCodec.encode(cause as Error) });
44
+ return new HttpClientError.RequestError({
45
+ request,
46
+ reason: 'Transport',
47
+ cause,
48
+ });
49
+ },
50
+ }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response)));
51
+
52
+ switch (request.body._tag) {
53
+ case 'Raw':
54
+ case 'Uint8Array':
55
+ return send(request.body.body as any);
56
+ case 'FormData':
57
+ return send(request.body.formData);
58
+ case 'Stream':
59
+ return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect.flatMap(send));
60
+ }
61
+
62
+ return send(undefined);
63
+ });
64
+
65
+ static layer = (service: EdgeFunctionEnv.FunctionsAiService) =>
66
+ Layer.succeed(HttpClient.HttpClient, FunctionsAiHttpClient.make(service));
67
+ }
@@ -2,23 +2,28 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
+ import * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';
5
6
  import * as Effect from 'effect/Effect';
6
7
  import * as Layer from 'effect/Layer';
7
8
  import * as Schema from 'effect/Schema';
8
9
  import * as SchemaAST from 'effect/SchemaAST';
9
10
 
10
- import { AiService } from '@dxos/ai';
11
+ import { AiModelResolver, AiService } from '@dxos/ai';
12
+ import { AnthropicResolver } from '@dxos/ai/resolvers';
11
13
  import { LifecycleState, Resource } from '@dxos/context';
12
- import { Type } from '@dxos/echo';
13
- import { EchoClient, type EchoDatabaseImpl, type QueueFactory } from '@dxos/echo-db';
14
+ import { Database, Feed, JsonSchema, Ref, type Type } from '@dxos/echo';
15
+ import { refFromEncodedReference } from '@dxos/echo/internal';
16
+ import { EchoClient, type EchoDatabaseImpl, type QueueFactory, createFeedServiceLayer } from '@dxos/echo-db';
17
+ import { runAndForwardErrors } from '@dxos/effect';
14
18
  import { assertState, failedInvariant, invariant } from '@dxos/invariant';
15
19
  import { PublicKey } from '@dxos/keys';
16
20
  import { type FunctionProtocol } from '@dxos/protocols';
17
21
 
18
22
  import { FunctionError } from '../errors';
19
23
  import { FunctionDefinition, type FunctionServices } from '../sdk';
20
- import { CredentialsService, DatabaseService, FunctionInvocationService, TracingService } from '../services';
21
- import { QueueService } from '../services';
24
+ import { CredentialsService, FunctionInvocationService, QueueService, TracingService } from '../services';
25
+
26
+ import { FunctionsAiHttpClient } from './functions-ai-http-client';
22
27
 
23
28
  /**
24
29
  * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.
@@ -33,13 +38,15 @@ export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.
33
38
  key: func.key,
34
39
  name: func.name,
35
40
  description: func.description,
36
- inputSchema: Type.toJsonSchema(func.inputSchema),
37
- outputSchema: func.outputSchema === undefined ? undefined : Type.toJsonSchema(func.outputSchema),
41
+ inputSchema: JsonSchema.toJsonSchema(func.inputSchema),
42
+ outputSchema: func.outputSchema === undefined ? undefined : JsonSchema.toJsonSchema(func.outputSchema),
38
43
  services: func.services,
39
44
  },
40
45
  handler: async ({ data, context }) => {
41
46
  if (
42
- (func.services.includes(DatabaseService.key) || func.services.includes(QueueService.key)) &&
47
+ (func.services.includes(Database.Service.key) ||
48
+ func.services.includes(QueueService.key) ||
49
+ func.services.includes(Feed.Service.key)) &&
43
50
  (!context.services.dataService || !context.services.queryService)
44
51
  ) {
45
52
  throw new FunctionError({
@@ -61,17 +68,22 @@ export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.
61
68
 
62
69
  if (func.types.length > 0) {
63
70
  invariant(funcContext.db, 'Database is required for functions with types');
64
- funcContext.db.graph.schemaRegistry.addSchema(func.types);
71
+ await funcContext.db.graph.schemaRegistry.register(func.types as Type.AnyEntity[]);
65
72
  }
66
73
 
74
+ const dataWithDecodedRefs =
75
+ funcContext.db && !SchemaAST.isAnyKeyword(func.inputSchema.ast)
76
+ ? decodeRefsFromSchema(func.inputSchema.ast, data, funcContext.db)
77
+ : data;
78
+
67
79
  let result = await func.handler({
68
80
  // TODO(dmaretskyi): Fix the types.
69
81
  context: context as any,
70
- data,
82
+ data: dataWithDecodedRefs,
71
83
  });
72
84
 
73
85
  if (Effect.isEffect(result)) {
74
- result = await Effect.runPromise(
86
+ result = await runAndForwardErrors(
75
87
  (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(
76
88
  Effect.orDie,
77
89
  Effect.provide(funcContext.createLayer()),
@@ -121,6 +133,7 @@ class FunctionContext extends Resource {
121
133
  spaceId: this.context.spaceId ?? failedInvariant(),
122
134
  spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),
123
135
  reactiveSchemaQuery: false,
136
+ preloadSchemaOnOpen: false,
124
137
  })
125
138
  : undefined;
126
139
 
@@ -138,19 +151,108 @@ class FunctionContext extends Resource {
138
151
  createLayer(): Layer.Layer<FunctionServices> {
139
152
  assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');
140
153
 
141
- const dbLayer = this.db ? DatabaseService.layer(this.db) : DatabaseService.notAvailable;
154
+ const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;
142
155
  const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
156
+ const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
143
157
  const credentials = dbLayer
144
- ? CredentialsService.layerFromDatabase().pipe(Layer.provide(dbLayer))
158
+ ? CredentialsService.layerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))
145
159
  : CredentialsService.configuredLayer([]);
146
160
  const functionInvocationService = MockedFunctionInvocationService;
147
- const aiService = AiService.notAvailable;
148
161
  const tracing = TracingService.layerNoop;
149
162
 
150
- return Layer.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
163
+ const aiLayer = this.context.services.functionsAiService
164
+ ? AiModelResolver.AiModelResolver.buildAiService.pipe(
165
+ Layer.provide(
166
+ AnthropicResolver.make().pipe(
167
+ Layer.provide(
168
+ AnthropicClient.layer({
169
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
170
+ apiUrl: 'http://internal/provider/anthropic',
171
+ }).pipe(Layer.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))),
172
+ ),
173
+ ),
174
+ ),
175
+ )
176
+ : AiService.notAvailable;
177
+
178
+ return Layer.mergeAll(dbLayer, queuesLayer, feedLayer, credentials, functionInvocationService, aiLayer, tracing);
151
179
  }
152
180
  }
153
181
 
154
182
  const MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {
155
183
  invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),
184
+ resolveFunction: () => Effect.die('Not implemented.'),
156
185
  });
186
+
187
+ const decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {
188
+ if (value == null) {
189
+ return value;
190
+ }
191
+
192
+ const encoded = SchemaAST.encodedBoundAST(ast);
193
+ if (Ref.isRefType(encoded)) {
194
+ if (Ref.isRef(value)) {
195
+ return value;
196
+ }
197
+
198
+ if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {
199
+ const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });
200
+ return refFromEncodedReference(value as any, resolver);
201
+ }
202
+
203
+ return value;
204
+ }
205
+
206
+ switch (encoded._tag) {
207
+ case 'TypeLiteral': {
208
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
209
+ return value;
210
+ }
211
+ const result: Record<string, unknown> = { ...(value as any) };
212
+ for (const prop of SchemaAST.getPropertySignatures(encoded)) {
213
+ const key = prop.name.toString();
214
+ if (key in result) {
215
+ result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);
216
+ }
217
+ }
218
+ return result;
219
+ }
220
+
221
+ case 'TupleType': {
222
+ if (!Array.isArray(value)) {
223
+ return value;
224
+ }
225
+
226
+ // For arrays, effect uses TupleType with empty elements and a single rest element.
227
+ if (encoded.elements.length === 0 && encoded.rest.length === 1) {
228
+ const elementType = encoded.rest[0].type;
229
+ return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));
230
+ }
231
+
232
+ return value;
233
+ }
234
+
235
+ case 'Union': {
236
+ // Optional values are represented as union with undefined.
237
+ const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));
238
+ if (nonUndefined.length === 1) {
239
+ return decodeRefsFromSchema(nonUndefined[0], value, db);
240
+ }
241
+
242
+ // For other unions we can't safely pick a branch without validating.
243
+ return value;
244
+ }
245
+
246
+ case 'Suspend': {
247
+ return decodeRefsFromSchema(encoded.f(), value, db);
248
+ }
249
+
250
+ case 'Refinement': {
251
+ return decodeRefsFromSchema(encoded.from, value, db);
252
+ }
253
+
254
+ default: {
255
+ return value;
256
+ }
257
+ }
258
+ };