@dxos/functions 0.8.4-main.70d3990 → 0.8.4-main.74a063c4e0
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.
- package/README.md +4 -6
- package/dist/lib/neutral/Trace.mjs +38 -0
- package/dist/lib/neutral/Trace.mjs.map +7 -0
- package/dist/lib/neutral/chunk-5T7GOX2V.mjs +149 -0
- package/dist/lib/neutral/chunk-5T7GOX2V.mjs.map +7 -0
- package/dist/lib/neutral/chunk-IVDUS56O.mjs +49 -0
- package/dist/lib/neutral/chunk-IVDUS56O.mjs.map +7 -0
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
- package/dist/lib/neutral/fib-N45KAC7C.mjs +23 -0
- package/dist/lib/neutral/fib-N45KAC7C.mjs.map +7 -0
- package/dist/lib/neutral/index.mjs +1266 -0
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/lib/neutral/reply-EUEPKNJF.mjs +19 -0
- package/dist/lib/neutral/reply-EUEPKNJF.mjs.map +7 -0
- package/dist/lib/neutral/sleep-PUK3D4FF.mjs +15 -0
- package/dist/lib/neutral/sleep-PUK3D4FF.mjs.map +7 -0
- package/dist/types/src/Trace.d.ts +155 -0
- package/dist/types/src/Trace.d.ts.map +1 -0
- package/dist/types/src/errors.d.ts +24 -32
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/example/definitions.d.ts +11 -0
- package/dist/types/src/example/definitions.d.ts.map +1 -0
- package/dist/types/src/example/fib.d.ts +3 -2
- package/dist/types/src/example/fib.d.ts.map +1 -1
- package/dist/types/src/example/index.d.ts +3 -11
- package/dist/types/src/example/index.d.ts.map +1 -1
- package/dist/types/src/example/reply.d.ts +2 -1
- package/dist/types/src/example/reply.d.ts.map +1 -1
- package/dist/types/src/example/sleep.d.ts +3 -2
- package/dist/types/src/example/sleep.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +4 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/process/Process.d.ts +247 -0
- package/dist/types/src/process/Process.d.ts.map +1 -0
- package/dist/types/src/process/ServiceResolver.d.ts +74 -0
- package/dist/types/src/process/ServiceResolver.d.ts.map +1 -0
- package/dist/types/src/process/StorageService.d.ts +58 -0
- package/dist/types/src/process/StorageService.d.ts.map +1 -0
- package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
- package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
- package/dist/types/src/protocol/protocol.d.ts +2 -2
- package/dist/types/src/protocol/protocol.d.ts.map +1 -1
- package/dist/types/src/sdk.d.ts +4 -90
- package/dist/types/src/sdk.d.ts.map +1 -1
- package/dist/types/src/services/credentials.d.ts +6 -4
- package/dist/types/src/services/credentials.d.ts.map +1 -1
- package/dist/types/src/services/event-logger.d.ts +25 -31
- package/dist/types/src/services/event-logger.d.ts.map +1 -1
- package/dist/types/src/services/function-invocation-service.d.ts +9 -3
- package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
- package/dist/types/src/services/index.d.ts +0 -1
- package/dist/types/src/services/index.d.ts.map +1 -1
- package/dist/types/src/services/queues.d.ts +5 -2
- package/dist/types/src/services/queues.d.ts.map +1 -1
- package/dist/types/src/services/tracing.d.ts +61 -4
- package/dist/types/src/services/tracing.d.ts.map +1 -1
- package/dist/types/src/types/Script.d.ts +9 -15
- package/dist/types/src/types/Script.d.ts.map +1 -1
- package/dist/types/src/types/Trigger.d.ts +57 -78
- package/dist/types/src/types/Trigger.d.ts.map +1 -1
- package/dist/types/src/types/TriggerEvent.d.ts +44 -12
- package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
- package/dist/types/src/types/index.d.ts +0 -1
- package/dist/types/src/types/index.d.ts.map +1 -1
- package/dist/types/src/types/url.d.ts +6 -5
- package/dist/types/src/types/url.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +29 -18
- package/src/Trace.ts +202 -0
- package/src/errors.ts +5 -5
- package/src/example/definitions.ts +49 -0
- package/src/example/fib.ts +15 -24
- package/src/example/forex-effect.ts +1 -1
- package/src/example/index.ts +7 -8
- package/src/example/reply.ts +11 -13
- package/src/example/sleep.ts +9 -16
- package/src/index.ts +4 -0
- package/src/process/Process.ts +486 -0
- package/src/process/ServiceResolver.ts +174 -0
- package/src/process/StorageService.ts +99 -0
- package/src/protocol/functions-ai-http-client.ts +67 -0
- package/src/protocol/protocol.test.ts +0 -1
- package/src/protocol/protocol.ts +142 -31
- package/src/sdk.ts +7 -208
- package/src/services/credentials.ts +31 -15
- package/src/services/event-logger.ts +2 -2
- package/src/services/function-invocation-service.ts +19 -3
- package/src/services/index.ts +0 -2
- package/src/services/queues.ts +11 -2
- package/src/services/tracing.ts +97 -5
- package/src/types/Script.ts +10 -5
- package/src/types/Trigger.ts +31 -17
- package/src/types/TriggerEvent.ts +29 -29
- package/src/types/index.ts +0 -1
- package/src/types/url.ts +6 -5
- package/dist/lib/browser/index.mjs +0 -1030
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/node-esm/index.mjs +0 -1031
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/types/src/types/Function.d.ts +0 -63
- package/dist/types/src/types/Function.d.ts.map +0 -1
- package/src/types/Function.ts +0 -80
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import * as Context from 'effect/Context';
|
|
6
|
+
import * as Effect from 'effect/Effect';
|
|
7
|
+
import * as Option from 'effect/Option';
|
|
8
|
+
import * as Pipeable from 'effect/Pipeable';
|
|
9
|
+
import * as Schema from 'effect/Schema';
|
|
10
|
+
|
|
11
|
+
export interface Service {
|
|
12
|
+
/** Read a value by key. Returns `None` if key does not exist. */
|
|
13
|
+
get<S extends Schema.Schema<any, string, any>>(
|
|
14
|
+
schema: S,
|
|
15
|
+
key: string,
|
|
16
|
+
): Effect.Effect<Option.Option<Schema.Schema.Type<S>>, never, Schema.Schema.Context<S>>;
|
|
17
|
+
|
|
18
|
+
/** Write a value for the given key. */
|
|
19
|
+
set<S extends Schema.Schema<any, string, any>>(
|
|
20
|
+
schema: S,
|
|
21
|
+
key: string,
|
|
22
|
+
value: Schema.Schema.Type<S>,
|
|
23
|
+
): Effect.Effect<void, never, Schema.Schema.Context<S>>;
|
|
24
|
+
|
|
25
|
+
/** Remove a key. */
|
|
26
|
+
delete(key: string): Effect.Effect<void>;
|
|
27
|
+
|
|
28
|
+
/** List all keys, optionally filtered by prefix. */
|
|
29
|
+
list(prefix?: string): Effect.Effect<readonly string[]>;
|
|
30
|
+
|
|
31
|
+
/** Remove all keys managed by this scoped store. */
|
|
32
|
+
clear(): Effect.Effect<void>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Scoped key-value storage service for processes.
|
|
37
|
+
* Each process receives its own namespaced instance via the process manager.
|
|
38
|
+
* Construct a live implementation with `StorageService.layer` from `@dxos/functions-runtime`.
|
|
39
|
+
*/
|
|
40
|
+
export class StorageService extends Context.Tag('@dxos/functions/StorageService')<StorageService, Service>() {}
|
|
41
|
+
|
|
42
|
+
export const get = Effect.serviceFunctionEffect(StorageService, (_) => _.get);
|
|
43
|
+
export const set = Effect.serviceFunctionEffect(StorageService, (_) => _.set);
|
|
44
|
+
export const deleteKey = Effect.serviceFunctionEffect(StorageService, (_) => _.delete);
|
|
45
|
+
export const list = Effect.serviceFunctionEffect(StorageService, (_) => _.list);
|
|
46
|
+
export const clear = Effect.serviceFunctionEffect(StorageService, (_) => _.clear);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Typed key in a storage service.
|
|
50
|
+
*/
|
|
51
|
+
export interface Key<T> extends Pipeable.Pipeable {
|
|
52
|
+
readonly key: string;
|
|
53
|
+
|
|
54
|
+
get: Effect.Effect<Option.Option<T>, never, StorageService>;
|
|
55
|
+
set(value: T): Effect.Effect<void, never, StorageService>;
|
|
56
|
+
delete(): Effect.Effect<void, never, StorageService>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Create a typed key in a storage service.
|
|
61
|
+
*/
|
|
62
|
+
export const key = <S extends Schema.Schema<any, string, any>>(schema: S, key: string): Key<Schema.Schema.Type<S>> => {
|
|
63
|
+
return {
|
|
64
|
+
key,
|
|
65
|
+
get: get(schema, key),
|
|
66
|
+
set: (value: Schema.Schema.Type<S>) => set(schema, key, value),
|
|
67
|
+
delete: () => deleteKey(key),
|
|
68
|
+
pipe(...args: any) {
|
|
69
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Typed key in a storage service with a default value.
|
|
76
|
+
*/
|
|
77
|
+
export interface KeyWithDefault<T, U> extends Pipeable.Pipeable {
|
|
78
|
+
readonly key: string;
|
|
79
|
+
get: Effect.Effect<T | U, never, StorageService>;
|
|
80
|
+
set(value: U): Effect.Effect<void, never, StorageService>;
|
|
81
|
+
delete(): Effect.Effect<void, never, StorageService>;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Assign a default value to a key if it is not present.
|
|
86
|
+
*/
|
|
87
|
+
export const withDefault =
|
|
88
|
+
<T>(getDefault: () => NoInfer<T>) =>
|
|
89
|
+
(key: Key<T>): KeyWithDefault<T, T> => {
|
|
90
|
+
return {
|
|
91
|
+
key: key.key,
|
|
92
|
+
get: key.get.pipe(Effect.map(Option.getOrElse(() => getDefault()))),
|
|
93
|
+
set: (value) => key.set(value),
|
|
94
|
+
delete: () => key.delete(),
|
|
95
|
+
pipe(...args: any) {
|
|
96
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
};
|
|
@@ -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
|
+
}
|
|
@@ -7,7 +7,6 @@ import { describe, test } from 'vitest';
|
|
|
7
7
|
import { FunctionError } from '../errors';
|
|
8
8
|
import fibFunc from '../example/fib';
|
|
9
9
|
import replyFunc from '../example/reply';
|
|
10
|
-
|
|
11
10
|
import { wrapFunctionHandler } from './protocol';
|
|
12
11
|
|
|
13
12
|
describe('wrapFunctionHandler', () => {
|
package/src/protocol/protocol.ts
CHANGED
|
@@ -2,44 +2,54 @@
|
|
|
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 { EchoClient, type EchoDatabaseImpl, type QueueFactory, createFeedServiceLayer } from '@dxos/echo-db';
|
|
16
|
+
import { refFromEncodedReference } from '@dxos/echo/internal';
|
|
17
|
+
import { runAndForwardErrors } from '@dxos/effect';
|
|
14
18
|
import { assertState, failedInvariant, invariant } from '@dxos/invariant';
|
|
15
19
|
import { PublicKey } from '@dxos/keys';
|
|
20
|
+
import { Operation } from '@dxos/operation';
|
|
16
21
|
import { type FunctionProtocol } from '@dxos/protocols';
|
|
17
22
|
|
|
18
23
|
import { FunctionError } from '../errors';
|
|
19
|
-
import {
|
|
20
|
-
import { CredentialsService,
|
|
21
|
-
import
|
|
24
|
+
import { type FunctionServices } from '../sdk';
|
|
25
|
+
import { CredentialsService, FunctionInvocationService, QueueService, TracingService } from '../services';
|
|
26
|
+
import * as Trace from '../Trace';
|
|
27
|
+
import { FunctionsAiHttpClient } from './functions-ai-http-client';
|
|
22
28
|
|
|
23
29
|
/**
|
|
24
30
|
* Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.
|
|
25
31
|
*/
|
|
26
|
-
export const wrapFunctionHandler = (func:
|
|
27
|
-
if (!
|
|
28
|
-
throw new TypeError('
|
|
32
|
+
export const wrapFunctionHandler = (func: Operation.WithHandler<Operation.Definition.Any>): FunctionProtocol.Func => {
|
|
33
|
+
if (!Operation.isOperationWithHandler(func)) {
|
|
34
|
+
throw new TypeError('Expected operation with handler');
|
|
29
35
|
}
|
|
30
36
|
|
|
37
|
+
const serviceTags = func.services.map((service) => service.key);
|
|
38
|
+
|
|
31
39
|
return {
|
|
32
40
|
meta: {
|
|
33
|
-
key: func.key,
|
|
34
|
-
name: func.name,
|
|
35
|
-
description: func.description,
|
|
36
|
-
inputSchema:
|
|
37
|
-
outputSchema: func.
|
|
38
|
-
services: func.services,
|
|
41
|
+
key: func.meta.key,
|
|
42
|
+
name: func.meta.name,
|
|
43
|
+
description: func.meta.description,
|
|
44
|
+
inputSchema: JsonSchema.toJsonSchema(func.input),
|
|
45
|
+
outputSchema: func.output === undefined ? undefined : JsonSchema.toJsonSchema(func.output),
|
|
46
|
+
services: func.services.map((service) => service.key),
|
|
39
47
|
},
|
|
40
48
|
handler: async ({ data, context }) => {
|
|
41
49
|
if (
|
|
42
|
-
(
|
|
50
|
+
(serviceTags.includes(Database.Service.key) ||
|
|
51
|
+
serviceTags.includes(QueueService.key) ||
|
|
52
|
+
serviceTags.includes(Feed.FeedService.key)) &&
|
|
43
53
|
(!context.services.dataService || !context.services.queryService)
|
|
44
54
|
) {
|
|
45
55
|
throw new FunctionError({
|
|
@@ -49,9 +59,9 @@ export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.
|
|
|
49
59
|
|
|
50
60
|
// eslint-disable-next-line no-useless-catch
|
|
51
61
|
try {
|
|
52
|
-
if (!SchemaAST.isAnyKeyword(func.
|
|
62
|
+
if (!SchemaAST.isAnyKeyword(func.input.ast)) {
|
|
53
63
|
try {
|
|
54
|
-
Schema.validateSync(func.
|
|
64
|
+
Schema.validateSync(func.input)(data);
|
|
55
65
|
} catch (error) {
|
|
56
66
|
throw new FunctionError({ message: 'Invalid input schema', cause: error });
|
|
57
67
|
}
|
|
@@ -61,17 +71,18 @@ export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.
|
|
|
61
71
|
|
|
62
72
|
if (func.types.length > 0) {
|
|
63
73
|
invariant(funcContext.db, 'Database is required for functions with types');
|
|
64
|
-
funcContext.db.graph.schemaRegistry.
|
|
74
|
+
await funcContext.db.graph.schemaRegistry.register(func.types as Type.AnyEntity[]);
|
|
65
75
|
}
|
|
66
76
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
77
|
+
const dataWithDecodedRefs =
|
|
78
|
+
funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast)
|
|
79
|
+
? decodeRefsFromSchema(func.input.ast, data, funcContext.db)
|
|
80
|
+
: data;
|
|
81
|
+
|
|
82
|
+
let result: any = await func.handler(dataWithDecodedRefs);
|
|
72
83
|
|
|
73
84
|
if (Effect.isEffect(result)) {
|
|
74
|
-
result = await
|
|
85
|
+
result = await runAndForwardErrors(
|
|
75
86
|
(result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(
|
|
76
87
|
Effect.orDie,
|
|
77
88
|
Effect.provide(funcContext.createLayer()),
|
|
@@ -79,8 +90,8 @@ export const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.
|
|
|
79
90
|
);
|
|
80
91
|
}
|
|
81
92
|
|
|
82
|
-
if (func.
|
|
83
|
-
Schema.validateSync(func.
|
|
93
|
+
if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {
|
|
94
|
+
Schema.validateSync(func.output)(result);
|
|
84
95
|
}
|
|
85
96
|
|
|
86
97
|
return result;
|
|
@@ -121,6 +132,7 @@ class FunctionContext extends Resource {
|
|
|
121
132
|
spaceId: this.context.spaceId ?? failedInvariant(),
|
|
122
133
|
spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),
|
|
123
134
|
reactiveSchemaQuery: false,
|
|
135
|
+
preloadSchemaOnOpen: false,
|
|
124
136
|
})
|
|
125
137
|
: undefined;
|
|
126
138
|
|
|
@@ -138,19 +150,118 @@ class FunctionContext extends Resource {
|
|
|
138
150
|
createLayer(): Layer.Layer<FunctionServices> {
|
|
139
151
|
assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');
|
|
140
152
|
|
|
141
|
-
const dbLayer = this.db ?
|
|
153
|
+
const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;
|
|
142
154
|
const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
|
|
155
|
+
const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
|
|
143
156
|
const credentials = dbLayer
|
|
144
|
-
? CredentialsService.layerFromDatabase().pipe(Layer.provide(dbLayer))
|
|
157
|
+
? CredentialsService.layerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))
|
|
145
158
|
: CredentialsService.configuredLayer([]);
|
|
146
159
|
const functionInvocationService = MockedFunctionInvocationService;
|
|
147
|
-
const aiService = AiService.notAvailable;
|
|
148
160
|
const tracing = TracingService.layerNoop;
|
|
149
161
|
|
|
150
|
-
|
|
162
|
+
const aiLayer = this.context.services.functionsAiService
|
|
163
|
+
? AiModelResolver.AiModelResolver.buildAiService.pipe(
|
|
164
|
+
Layer.provide(
|
|
165
|
+
AnthropicResolver.make().pipe(
|
|
166
|
+
Layer.provide(
|
|
167
|
+
AnthropicClient.layer({
|
|
168
|
+
// Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
|
|
169
|
+
apiUrl: 'http://internal/provider/anthropic',
|
|
170
|
+
}).pipe(Layer.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))),
|
|
171
|
+
),
|
|
172
|
+
),
|
|
173
|
+
),
|
|
174
|
+
)
|
|
175
|
+
: AiService.notAvailable;
|
|
176
|
+
|
|
177
|
+
return Layer.mergeAll(
|
|
178
|
+
dbLayer,
|
|
179
|
+
queuesLayer,
|
|
180
|
+
feedLayer,
|
|
181
|
+
credentials,
|
|
182
|
+
functionInvocationService,
|
|
183
|
+
aiLayer,
|
|
184
|
+
tracing,
|
|
185
|
+
// TODO(dmaretskyi): Forward trace events.
|
|
186
|
+
Trace.writerLayerNoop,
|
|
187
|
+
);
|
|
151
188
|
}
|
|
152
189
|
}
|
|
153
190
|
|
|
154
191
|
const MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {
|
|
155
192
|
invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),
|
|
193
|
+
resolveFunction: () => Effect.die('Not implemented.'),
|
|
156
194
|
});
|
|
195
|
+
|
|
196
|
+
const decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {
|
|
197
|
+
if (value == null) {
|
|
198
|
+
return value;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const encoded = SchemaAST.encodedBoundAST(ast);
|
|
202
|
+
if (Ref.isRefType(encoded)) {
|
|
203
|
+
if (Ref.isRef(value)) {
|
|
204
|
+
return value;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {
|
|
208
|
+
const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });
|
|
209
|
+
return refFromEncodedReference(value as any, resolver);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return value;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
switch (encoded._tag) {
|
|
216
|
+
case 'TypeLiteral': {
|
|
217
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
218
|
+
return value;
|
|
219
|
+
}
|
|
220
|
+
const result: Record<string, unknown> = { ...(value as any) };
|
|
221
|
+
for (const prop of SchemaAST.getPropertySignatures(encoded)) {
|
|
222
|
+
const key = prop.name.toString();
|
|
223
|
+
if (key in result) {
|
|
224
|
+
result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
case 'TupleType': {
|
|
231
|
+
if (!Array.isArray(value)) {
|
|
232
|
+
return value;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// For arrays, effect uses TupleType with empty elements and a single rest element.
|
|
236
|
+
if (encoded.elements.length === 0 && encoded.rest.length === 1) {
|
|
237
|
+
const elementType = encoded.rest[0].type;
|
|
238
|
+
return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
case 'Union': {
|
|
245
|
+
// Optional values are represented as union with undefined.
|
|
246
|
+
const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));
|
|
247
|
+
if (nonUndefined.length === 1) {
|
|
248
|
+
return decodeRefsFromSchema(nonUndefined[0], value, db);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// For other unions we can't safely pick a branch without validating.
|
|
252
|
+
return value;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
case 'Suspend': {
|
|
256
|
+
return decodeRefsFromSchema(encoded.f(), value, db);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
case 'Refinement': {
|
|
260
|
+
return decodeRefsFromSchema(encoded.from, value, db);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
default: {
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
};
|
package/src/sdk.ts
CHANGED
|
@@ -2,14 +2,9 @@
|
|
|
2
2
|
// Copyright 2023 DXOS.org
|
|
3
3
|
//
|
|
4
4
|
|
|
5
|
-
import type * as Context from 'effect/Context';
|
|
6
|
-
import * as Effect from 'effect/Effect';
|
|
7
|
-
import * as Schema from 'effect/Schema';
|
|
8
|
-
|
|
9
5
|
import { type AiService } from '@dxos/ai';
|
|
10
|
-
import {
|
|
11
|
-
import { type
|
|
12
|
-
import { assertArgument, failedInvariant } from '@dxos/invariant';
|
|
6
|
+
import { type Database, type Feed } from '@dxos/echo';
|
|
7
|
+
import { type Trace } from '@dxos/functions';
|
|
13
8
|
|
|
14
9
|
import {
|
|
15
10
|
type CredentialsService,
|
|
@@ -17,8 +12,6 @@ import {
|
|
|
17
12
|
type QueueService,
|
|
18
13
|
type TracingService,
|
|
19
14
|
} from './services';
|
|
20
|
-
import { Function } from './types';
|
|
21
|
-
import { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './types';
|
|
22
15
|
|
|
23
16
|
// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.
|
|
24
17
|
// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html
|
|
@@ -32,209 +25,15 @@ export type InvocationServices = TracingService;
|
|
|
32
25
|
|
|
33
26
|
/**
|
|
34
27
|
* Services that are available to invoked functions.
|
|
28
|
+
* @deprecated
|
|
35
29
|
*/
|
|
36
30
|
export type FunctionServices =
|
|
37
31
|
| InvocationServices
|
|
38
32
|
| AiService.AiService
|
|
39
33
|
| CredentialsService
|
|
40
|
-
|
|
|
34
|
+
| Database.Service
|
|
35
|
+
// TODO(wittjosiah): Remove QueueService — use Feed.FeedService instead.
|
|
41
36
|
| QueueService
|
|
37
|
+
| Feed.FeedService
|
|
38
|
+
| Trace.TraceService
|
|
42
39
|
| FunctionInvocationService;
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Function handler.
|
|
46
|
-
*/
|
|
47
|
-
export type FunctionHandler<TData = {}, TOutput = any, S extends FunctionServices = FunctionServices> = (params: {
|
|
48
|
-
/**
|
|
49
|
-
* Context available to the function.
|
|
50
|
-
*/
|
|
51
|
-
context: FunctionContext;
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Data passed as the input to the function.
|
|
55
|
-
* Must match the function's input schema.
|
|
56
|
-
* This will be the payload from the trigger or other data passed into the function in a workflow.
|
|
57
|
-
*/
|
|
58
|
-
data: TData;
|
|
59
|
-
}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, S>;
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Function context.
|
|
63
|
-
*/
|
|
64
|
-
export interface FunctionContext {
|
|
65
|
-
// TODO(dmaretskyi): Consider what we should put into context.
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
const typeId = Symbol.for('@dxos/functions/FunctionDefinition');
|
|
69
|
-
|
|
70
|
-
export type FunctionDefinition<T = any, O = any, S extends FunctionServices = FunctionServices> = {
|
|
71
|
-
[typeId]: true;
|
|
72
|
-
key: string;
|
|
73
|
-
name: string;
|
|
74
|
-
description?: string;
|
|
75
|
-
inputSchema: Schema.Schema<T, any>;
|
|
76
|
-
outputSchema?: Schema.Schema<O, any>;
|
|
77
|
-
|
|
78
|
-
/**
|
|
79
|
-
* List of types the function uses.
|
|
80
|
-
* This is used to ensure that the types are available when the function is executed.
|
|
81
|
-
*/
|
|
82
|
-
types: readonly Type.Obj.Any[];
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Keys of the required services.
|
|
86
|
-
*/
|
|
87
|
-
services: readonly string[];
|
|
88
|
-
|
|
89
|
-
handler: FunctionHandler<T, O, S>;
|
|
90
|
-
meta?: {
|
|
91
|
-
/**
|
|
92
|
-
* Tools that are projected from functions have this annotation.
|
|
93
|
-
*
|
|
94
|
-
* deployedFunctionId:
|
|
95
|
-
* - Backend deployment ID assigned by the EDGE function service (typically a UUID).
|
|
96
|
-
* - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.
|
|
97
|
-
* - Persisted on the corresponding ECHO `Function.Function` object's metadata under the
|
|
98
|
-
* `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.
|
|
99
|
-
*/
|
|
100
|
-
deployedFunctionId?: string;
|
|
101
|
-
};
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
export declare namespace FunctionDefinition {
|
|
105
|
-
export type Any = FunctionDefinition<any, any, any>;
|
|
106
|
-
export type Input<T extends Any> = T extends FunctionDefinition<infer I, infer _O, infer _S> ? I : never;
|
|
107
|
-
export type Output<T extends Any> = T extends FunctionDefinition<infer _I, infer O, infer _S> ? O : never;
|
|
108
|
-
export type Services<T extends Any> = T extends FunctionDefinition<infer _I, infer _O, infer S> ? S : never;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
export type FunctionProps<T, O> = {
|
|
112
|
-
key: string;
|
|
113
|
-
name: string;
|
|
114
|
-
description?: string;
|
|
115
|
-
inputSchema: Schema.Schema<T, any>;
|
|
116
|
-
outputSchema?: Schema.Schema<O, any>;
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* List of types the function uses.
|
|
120
|
-
* This is used to ensure that the types are available when the function is executed.
|
|
121
|
-
*/
|
|
122
|
-
types?: readonly Type.Obj.Any[];
|
|
123
|
-
// TODO(dmaretskyi): This currently doesn't cause a compile-time error if the handler requests a service that is not specified
|
|
124
|
-
services?: readonly Context.Tag<any, any>[];
|
|
125
|
-
|
|
126
|
-
handler: FunctionHandler<T, O, FunctionServices>;
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
// TODO(dmaretskyi): Output type doesn't get typechecked.
|
|
130
|
-
export const defineFunction: {
|
|
131
|
-
<I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O, FunctionServices>;
|
|
132
|
-
} = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler, types, services }) => {
|
|
133
|
-
if (!Schema.isSchema(inputSchema)) {
|
|
134
|
-
throw new Error('Input schema must be a valid schema');
|
|
135
|
-
}
|
|
136
|
-
if (typeof handler !== 'function') {
|
|
137
|
-
throw new Error('Handler must be a function');
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// Captures the function definition location.
|
|
141
|
-
const limit = Error.stackTraceLimit;
|
|
142
|
-
Error.stackTraceLimit = 2;
|
|
143
|
-
const traceError = new Error();
|
|
144
|
-
Error.stackTraceLimit = limit;
|
|
145
|
-
let cache: false | string = false;
|
|
146
|
-
const captureStackTrace = () => {
|
|
147
|
-
if (cache !== false) {
|
|
148
|
-
return cache;
|
|
149
|
-
}
|
|
150
|
-
if (traceError.stack !== undefined) {
|
|
151
|
-
const stack = traceError.stack.split('\n');
|
|
152
|
-
if (stack[2] !== undefined) {
|
|
153
|
-
cache = stack[2].trim();
|
|
154
|
-
return cache;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
const handlerWithSpan = (...args: any[]) => {
|
|
160
|
-
const result = (handler as any)(...args);
|
|
161
|
-
if (Effect.isEffect(result)) {
|
|
162
|
-
return Effect.withSpan(result, `${key ?? name}`, {
|
|
163
|
-
captureStackTrace,
|
|
164
|
-
});
|
|
165
|
-
}
|
|
166
|
-
return result;
|
|
167
|
-
};
|
|
168
|
-
|
|
169
|
-
return {
|
|
170
|
-
[typeId]: true,
|
|
171
|
-
key,
|
|
172
|
-
name,
|
|
173
|
-
description,
|
|
174
|
-
inputSchema,
|
|
175
|
-
outputSchema,
|
|
176
|
-
handler: handlerWithSpan,
|
|
177
|
-
types: types ?? [],
|
|
178
|
-
services: !services ? [] : getServiceKeys(services),
|
|
179
|
-
} satisfies FunctionDefinition.Any;
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
const getServiceKeys = (services: readonly Context.Tag<any, any>[]) => {
|
|
183
|
-
return services.map((tag: any) => {
|
|
184
|
-
if (typeof tag.key === 'string') {
|
|
185
|
-
return tag.key;
|
|
186
|
-
}
|
|
187
|
-
console.log(tag);
|
|
188
|
-
failedInvariant();
|
|
189
|
-
});
|
|
190
|
-
};
|
|
191
|
-
|
|
192
|
-
export const FunctionDefinition = {
|
|
193
|
-
make: defineFunction,
|
|
194
|
-
isFunction: (value: unknown): value is FunctionDefinition.Any => {
|
|
195
|
-
return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;
|
|
196
|
-
},
|
|
197
|
-
serialize: (functionDef: FunctionDefinition.Any): Function.Function => {
|
|
198
|
-
assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');
|
|
199
|
-
return serializeFunction(functionDef);
|
|
200
|
-
},
|
|
201
|
-
deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {
|
|
202
|
-
assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');
|
|
203
|
-
return deserializeFunction(functionObj);
|
|
204
|
-
},
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
export const serializeFunction = (functionDef: FunctionDefinition.Any): Function.Function => {
|
|
208
|
-
const fn = Function.make({
|
|
209
|
-
key: functionDef.key,
|
|
210
|
-
name: functionDef.name,
|
|
211
|
-
version: '0.1.0',
|
|
212
|
-
description: functionDef.description,
|
|
213
|
-
inputSchema: Type.toJsonSchema(functionDef.inputSchema),
|
|
214
|
-
outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),
|
|
215
|
-
services: functionDef.services,
|
|
216
|
-
});
|
|
217
|
-
if (functionDef.meta?.deployedFunctionId) {
|
|
218
|
-
setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta.deployedFunctionId);
|
|
219
|
-
}
|
|
220
|
-
return fn;
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
export const deserializeFunction = (functionObj: Function.Function): FunctionDefinition<unknown, unknown> => {
|
|
224
|
-
return {
|
|
225
|
-
[typeId]: true,
|
|
226
|
-
// TODO(dmaretskyi): Fix key.
|
|
227
|
-
key: functionObj.key ?? functionObj.name,
|
|
228
|
-
name: functionObj.name,
|
|
229
|
-
description: functionObj.description,
|
|
230
|
-
inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),
|
|
231
|
-
outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),
|
|
232
|
-
// TODO(dmaretskyi): This should throw error.
|
|
233
|
-
handler: () => {},
|
|
234
|
-
services: functionObj.services ?? [],
|
|
235
|
-
types: [],
|
|
236
|
-
meta: {
|
|
237
|
-
deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),
|
|
238
|
-
},
|
|
239
|
-
};
|
|
240
|
-
};
|