@dxos/functions 0.8.3-main.672df60 → 0.8.3-staging.0fa589b

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 (65) hide show
  1. package/dist/lib/browser/chunk-WEFZUEL2.mjs +300 -0
  2. package/dist/lib/browser/chunk-WEFZUEL2.mjs.map +7 -0
  3. package/dist/lib/browser/index.mjs +43 -119
  4. package/dist/lib/browser/index.mjs.map +4 -4
  5. package/dist/lib/browser/meta.json +1 -1
  6. package/dist/lib/browser/testing/index.mjs +28 -0
  7. package/dist/lib/browser/testing/index.mjs.map +7 -0
  8. package/dist/lib/node/chunk-IJAE7FZK.cjs +320 -0
  9. package/dist/lib/node/chunk-IJAE7FZK.cjs.map +7 -0
  10. package/dist/lib/node/index.cjs +41 -114
  11. package/dist/lib/node/index.cjs.map +4 -4
  12. package/dist/lib/node/meta.json +1 -1
  13. package/dist/lib/node/testing/index.cjs +43 -0
  14. package/dist/lib/node/testing/index.cjs.map +7 -0
  15. package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs +302 -0
  16. package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs.map +7 -0
  17. package/dist/lib/node-esm/index.mjs +42 -119
  18. package/dist/lib/node-esm/index.mjs.map +4 -4
  19. package/dist/lib/node-esm/meta.json +1 -1
  20. package/dist/lib/node-esm/testing/index.mjs +29 -0
  21. package/dist/lib/node-esm/testing/index.mjs.map +7 -0
  22. package/dist/types/src/handler.d.ts +2 -2
  23. package/dist/types/src/schema.d.ts +16 -35
  24. package/dist/types/src/schema.d.ts.map +1 -1
  25. package/dist/types/src/services/ai.d.ts +6 -3
  26. package/dist/types/src/services/ai.d.ts.map +1 -1
  27. package/dist/types/src/services/database.d.ts +3 -1
  28. package/dist/types/src/services/database.d.ts.map +1 -1
  29. package/dist/types/src/services/event-logger.d.ts +37 -0
  30. package/dist/types/src/services/event-logger.d.ts.map +1 -0
  31. package/dist/types/src/services/function-call-service.d.ts +16 -0
  32. package/dist/types/src/services/function-call-service.d.ts.map +1 -0
  33. package/dist/types/src/services/index.d.ts +2 -0
  34. package/dist/types/src/services/index.d.ts.map +1 -1
  35. package/dist/types/src/services/queues.d.ts +12 -4
  36. package/dist/types/src/services/queues.d.ts.map +1 -1
  37. package/dist/types/src/services/service-container.d.ts +28 -9
  38. package/dist/types/src/services/service-container.d.ts.map +1 -1
  39. package/dist/types/src/testing/index.d.ts +2 -0
  40. package/dist/types/src/testing/index.d.ts.map +1 -0
  41. package/dist/types/src/testing/logger.d.ts +5 -0
  42. package/dist/types/src/testing/logger.d.ts.map +1 -0
  43. package/dist/types/src/testing/services.d.ts +13 -0
  44. package/dist/types/src/testing/services.d.ts.map +1 -0
  45. package/dist/types/src/trace.d.ts +19 -44
  46. package/dist/types/src/trace.d.ts.map +1 -1
  47. package/dist/types/src/translations.d.ts +4 -2
  48. package/dist/types/src/translations.d.ts.map +1 -1
  49. package/dist/types/src/types.d.ts +36 -32
  50. package/dist/types/src/types.d.ts.map +1 -1
  51. package/package.json +25 -19
  52. package/src/handler.ts +2 -2
  53. package/src/schema.ts +13 -8
  54. package/src/services/ai.ts +21 -4
  55. package/src/services/database.ts +16 -2
  56. package/src/services/event-logger.ts +87 -0
  57. package/src/services/function-call-service.ts +64 -0
  58. package/src/services/index.ts +2 -0
  59. package/src/services/queues.ts +27 -6
  60. package/src/services/service-container.ts +66 -15
  61. package/src/testing/index.ts +5 -0
  62. package/src/testing/logger.ts +16 -0
  63. package/src/testing/services.ts +32 -0
  64. package/src/trace.ts +13 -13
  65. package/src/translations.ts +6 -1
@@ -0,0 +1,87 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Effect, Context } from 'effect';
6
+
7
+ import { invariant } from '@dxos/invariant';
8
+ import { log, LogLevel } from '@dxos/log';
9
+
10
+ export type ComputeEvent =
11
+ | {
12
+ type: 'begin-compute';
13
+ nodeId: string;
14
+ inputs: Record<string, any>;
15
+ }
16
+ | {
17
+ type: 'end-compute';
18
+ nodeId: string;
19
+ outputs: Record<string, any>;
20
+ }
21
+ | {
22
+ type: 'compute-input';
23
+ nodeId: string;
24
+ property: string;
25
+ value: any;
26
+ }
27
+ | {
28
+ type: 'compute-output';
29
+ nodeId: string;
30
+ property: string;
31
+ value: any;
32
+ }
33
+ | {
34
+ type: 'custom';
35
+ nodeId: string;
36
+ event: any;
37
+ };
38
+
39
+ export class EventLogger extends Context.Tag('EventLogger')<
40
+ EventLogger,
41
+ { readonly log: (event: ComputeEvent) => void; readonly nodeId: string | undefined }
42
+ >() {
43
+ static noop: Context.Tag.Service<EventLogger> = {
44
+ log: () => {},
45
+ nodeId: undefined,
46
+ };
47
+ }
48
+
49
+ export const logCustomEvent = (data: any) =>
50
+ Effect.gen(function* () {
51
+ const logger = yield* EventLogger;
52
+ if (!logger.nodeId) {
53
+ throw new Error('logCustomEvent must be called within a node compute function');
54
+ }
55
+ logger.log({
56
+ type: 'custom',
57
+ nodeId: logger.nodeId,
58
+ event: data,
59
+ });
60
+ });
61
+
62
+ export const createDefectLogger = <A, E, R>(): ((self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>
63
+ Effect.catchAll((error) =>
64
+ Effect.gen(function* () {
65
+ log.error('unhandled effect error', { error });
66
+ throw error;
67
+ }),
68
+ );
69
+
70
+ export const createEventLogger = (level: LogLevel, message: string = 'event'): Context.Tag.Service<EventLogger> => {
71
+ const logFunction = (
72
+ {
73
+ [LogLevel.WARN]: log.warn,
74
+ [LogLevel.VERBOSE]: log.verbose,
75
+ [LogLevel.DEBUG]: log.debug,
76
+ [LogLevel.INFO]: log.info,
77
+ [LogLevel.ERROR]: log.error,
78
+ } as any
79
+ )[level];
80
+ invariant(logFunction);
81
+ return {
82
+ log: (event: ComputeEvent) => {
83
+ logFunction(message, event);
84
+ },
85
+ nodeId: undefined,
86
+ };
87
+ };
@@ -0,0 +1,64 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Context } from 'effect';
6
+
7
+ import type { SpaceId } from '@dxos/keys';
8
+
9
+ /**
10
+ * Allows calling into other functions.
11
+ */
12
+ export class FunctionCallService extends Context.Tag('FunctionCallService')<
13
+ FunctionCallService,
14
+ {
15
+ callFunction(deployedFunctionId: string, input: any, spaceId?: SpaceId): Promise<any>;
16
+ }
17
+ >() {
18
+ static fromClient(baseUrl: string, spaceId: SpaceId): Context.Tag.Service<FunctionCallService> {
19
+ return {
20
+ callFunction: async (deployedFunctionId: string, input: any) => {
21
+ const url = getInvocationUrl(deployedFunctionId, baseUrl, { spaceId });
22
+ const result = await fetch(url, {
23
+ method: 'POST',
24
+ headers: { 'Content-Type': 'application/json' },
25
+ body: JSON.stringify(input),
26
+ });
27
+ if (result.status >= 300 || result.status < 200) {
28
+ throw new Error('Failed to invoke function', { cause: new Error(`HTTP error: ${await result.text()}`) });
29
+ }
30
+ return await result.json();
31
+ },
32
+ };
33
+ }
34
+
35
+ static mock = () => {
36
+ return {
37
+ callFunction: async (deployedFunctionId: string, input: any) => {
38
+ return input;
39
+ },
40
+ };
41
+ };
42
+ }
43
+
44
+ // TODO(dmaretskyi): Reconcile with `getInvocationUrl` in `@dxos/functions/edge`.
45
+ const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {
46
+ const baseUrl = new URL('functions/', edgeUrl);
47
+
48
+ // Leading slashes cause the URL to be treated as an absolute path.
49
+ const relativeUrl = functionUrl.replace(/^\//, '');
50
+ const url = new URL(`./${relativeUrl}`, baseUrl.toString());
51
+ options.spaceId && url.searchParams.set('spaceId', options.spaceId);
52
+ options.subjectId && url.searchParams.set('subjectId', options.subjectId);
53
+ url.protocol = isSecure(url.protocol) ? 'https' : 'http';
54
+ return url.toString();
55
+ };
56
+
57
+ const isSecure = (protocol: string) => {
58
+ return protocol === 'https:' || protocol === 'wss:';
59
+ };
60
+
61
+ type InvocationOptions = {
62
+ spaceId?: SpaceId;
63
+ subjectId?: string;
64
+ };
@@ -8,3 +8,5 @@ export * from './queues';
8
8
  export * from './service-container';
9
9
  export * from './credentials';
10
10
  export * from './tracing';
11
+ export * from './event-logger';
12
+ export * from './function-call-service';
@@ -2,15 +2,36 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { Context } from 'effect';
5
+ import { Context, Layer } from 'effect';
6
6
 
7
7
  import type { Queue, QueueFactory } from '@dxos/echo-db';
8
8
 
9
- export class QueuesService extends Context.Tag('QueuesService')<
10
- QueuesService,
9
+ export class QueueService extends Context.Tag('QueueService')<
10
+ QueueService,
11
11
  {
12
- readonly contextQueue: Queue | undefined;
13
-
12
+ /**
13
+ * API to access the queues.
14
+ */
14
15
  readonly queues: QueueFactory;
16
+
17
+ /**
18
+ * The queue that is used to store the context of the current research.
19
+ */
20
+ // TODO(dmaretskyi): Is this really part of the queue service?
21
+ readonly contextQueue: Queue | undefined;
15
22
  }
16
- >() {}
23
+ >() {
24
+ static notAvailable = Layer.succeed(QueueService, {
25
+ get queues(): QueueFactory {
26
+ throw new Error('Queues not available');
27
+ },
28
+ contextQueue: undefined,
29
+ });
30
+
31
+ static make = (queues: QueueFactory, contextQueue: Queue | undefined): Context.Tag.Service<QueueService> => {
32
+ return {
33
+ queues,
34
+ contextQueue,
35
+ };
36
+ };
37
+ }
@@ -2,43 +2,74 @@
2
2
  // Copyright 2025 DXOS.org
3
3
  //
4
4
 
5
- import { type Context } from 'effect';
5
+ import { Layer, type Context } from 'effect';
6
6
 
7
7
  import { AiService } from './ai';
8
- import { CredentialsService } from './credentials';
8
+ import { ConfiguredCredentialsService, CredentialsService } from './credentials';
9
9
  import { DatabaseService } from './database';
10
- import { QueuesService } from './queues';
10
+ import { EventLogger } from './event-logger';
11
+ import { FunctionCallService } from './function-call-service';
12
+ import { QueueService } from './queues';
11
13
  import { TracingService } from './tracing';
12
14
 
13
- export interface Services {
14
- database: Context.Tag.Service<DatabaseService>;
15
- ai: Context.Tag.Service<AiService>;
16
- queues: Context.Tag.Service<QueuesService>;
17
- credentials: Context.Tag.Service<CredentialsService>;
18
- tracing: Context.Tag.Service<TracingService>;
15
+ /**
16
+ * List of all service tags and their names.
17
+ */
18
+ export interface ServiceTagRecord {
19
+ ai: AiService;
20
+ credentials: CredentialsService;
21
+ database: DatabaseService;
22
+ eventLogger: EventLogger;
23
+ functionCallService: FunctionCallService;
24
+ tracing: TracingService;
25
+ queues: QueueService;
19
26
  }
20
27
 
21
- const SERVICE_MAPPING: Record<string, keyof Services> = {
22
- [DatabaseService.key]: 'database',
28
+ /**
29
+ * List of all services and their runtime types.
30
+ */
31
+ export type ServiceRecord = {
32
+ [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;
33
+ };
34
+
35
+ /**
36
+ * Union of all services.
37
+ */
38
+ export type Services = ServiceTagRecord[keyof ServiceTagRecord];
39
+
40
+ const SERVICE_MAPPING: Record<string, keyof ServiceRecord> = {
23
41
  [AiService.key]: 'ai',
24
- [QueuesService.key]: 'queues',
25
42
  [CredentialsService.key]: 'credentials',
43
+ [DatabaseService.key]: 'database',
44
+ [EventLogger.key]: 'eventLogger',
45
+ [FunctionCallService.key]: 'functionCallService',
46
+ [QueueService.key]: 'queues',
26
47
  [TracingService.key]: 'tracing',
27
48
  };
28
49
 
29
- const DEFAULT_SERVICES: Partial<Services> = {
50
+ export const SERVICE_TAGS: Context.Tag<any, any>[] = [
51
+ AiService,
52
+ CredentialsService,
53
+ DatabaseService,
54
+ EventLogger,
55
+ FunctionCallService,
56
+ TracingService,
57
+ QueueService,
58
+ ];
59
+
60
+ const DEFAULT_SERVICES: Partial<ServiceRecord> = {
30
61
  tracing: TracingService.noop,
31
62
  };
32
63
 
33
64
  export class ServiceContainer {
34
- private _services: Partial<Services> = { ...DEFAULT_SERVICES };
65
+ private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };
35
66
 
36
67
  /**
37
68
  * Set services.
38
69
  * @param services - Services to set.
39
70
  * @returns The container instance.
40
71
  */
41
- setServices(services: Partial<Services>): this {
72
+ setServices(services: Partial<ServiceRecord>): this {
42
73
  this._services = { ...this._services, ...services };
43
74
  return this;
44
75
  }
@@ -55,4 +86,24 @@ export class ServiceContainer {
55
86
  clone(): ServiceContainer {
56
87
  return new ServiceContainer().setServices({ ...this._services });
57
88
  }
89
+
90
+ // TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but layer forces us to provide all services and makes stubs for the ones that are not available.
91
+ createLayer(): Layer.Layer<Services> {
92
+ const ai = this._services.ai != null ? Layer.succeed(AiService, this._services.ai) : AiService.notAvailable;
93
+ const credentials = Layer.succeed(CredentialsService, new ConfiguredCredentialsService());
94
+ const database =
95
+ this._services.database != null
96
+ ? Layer.succeed(DatabaseService, this._services.database)
97
+ : DatabaseService.notAvailable;
98
+ const queues =
99
+ this._services.queues != null ? Layer.succeed(QueueService, this._services.queues) : QueueService.notAvailable;
100
+ const tracing = Layer.succeed(TracingService, this._services.tracing ?? TracingService.noop);
101
+ const eventLogger = Layer.succeed(EventLogger, this._services.eventLogger ?? EventLogger.noop);
102
+ const functionCallService = Layer.succeed(
103
+ FunctionCallService,
104
+ this._services.functionCallService ?? FunctionCallService.mock(),
105
+ );
106
+
107
+ return Layer.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);
108
+ }
58
109
  }
@@ -0,0 +1,5 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ export * from './services';
@@ -0,0 +1,16 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { Effect, type Context } from 'effect';
6
+
7
+ import { LogLevel } from '@dxos/log';
8
+
9
+ import { type EventLogger, createEventLogger } from '../services';
10
+
11
+ export const noopLogger: Context.Tag.Service<EventLogger> = {
12
+ log: () => Effect.succeed(undefined),
13
+ nodeId: undefined,
14
+ };
15
+
16
+ export const consoleLogger: Context.Tag.Service<EventLogger> = createEventLogger(LogLevel.INFO);
@@ -0,0 +1,32 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import { type Context } from 'effect';
6
+
7
+ import type { AiServiceClient } from '@dxos/ai';
8
+ import type { QueueFactory } from '@dxos/echo-db';
9
+
10
+ import { consoleLogger, noopLogger } from './logger';
11
+ import { AiService, QueueService, ServiceContainer } from '../services';
12
+ import type { EventLogger } from '../services/event-logger';
13
+
14
+ export type TestServiceOptions = {
15
+ ai?: AiServiceClient;
16
+ queueFactory?: QueueFactory;
17
+ enableLogging?: boolean;
18
+ logger?: Context.Tag.Service<EventLogger>;
19
+ };
20
+
21
+ export const createTestServices = ({
22
+ ai,
23
+ queueFactory,
24
+ enableLogging = false,
25
+ logger = enableLogging ? consoleLogger : noopLogger,
26
+ }: TestServiceOptions = {}): ServiceContainer => {
27
+ return new ServiceContainer().setServices({
28
+ ai: ai != null ? AiService.make(ai) : undefined,
29
+ eventLogger: logger,
30
+ queues: queueFactory != null ? QueueService.make(queueFactory, undefined) : undefined,
31
+ });
32
+ };
package/src/trace.ts CHANGED
@@ -4,8 +4,9 @@
4
4
 
5
5
  import { Schema } from 'effect';
6
6
 
7
+ import { Type, type Ref } from '@dxos/echo';
7
8
  import { Queue } from '@dxos/echo-db';
8
- import { EchoObject, Expando, ObjectId, Ref } from '@dxos/echo-schema';
9
+ import { ObjectId } from '@dxos/echo-schema';
9
10
  import { log } from '@dxos/log';
10
11
 
11
12
  import { FunctionTrigger, type FunctionTriggerType } from './types';
@@ -52,16 +53,16 @@ export const InvocationTraceStartEvent = Schema.Struct({
52
53
  /**
53
54
  * Queue for function/workflow invocation events.
54
55
  */
55
- invocationTraceQueue: Ref(Queue),
56
+ invocationTraceQueue: Type.Ref(Queue),
56
57
  /**
57
58
  * DXN of the invoked function/workflow.
58
59
  */
59
- invocationTarget: Ref(Expando),
60
+ invocationTarget: Type.Ref(Type.Expando),
60
61
  /**
61
62
  * Present for automatic invocations.
62
63
  */
63
- trigger: Schema.optional(Ref(FunctionTrigger)),
64
- }).pipe(EchoObject({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));
64
+ trigger: Schema.optional(Type.Ref(FunctionTrigger)),
65
+ }).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));
65
66
 
66
67
  export type InvocationTraceStartEvent = Schema.Schema.Type<typeof InvocationTraceStartEvent>;
67
68
 
@@ -82,7 +83,7 @@ export const InvocationTraceEndEvent = Schema.Struct({
82
83
  timestampMs: Schema.Number,
83
84
  outcome: Schema.Enums(InvocationOutcome),
84
85
  exception: Schema.optional(TraceEventException),
85
- }).pipe(EchoObject({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));
86
+ }).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));
86
87
 
87
88
  export type InvocationTraceEndEvent = Schema.Schema.Type<typeof InvocationTraceEndEvent>;
88
89
 
@@ -106,24 +107,23 @@ export const TraceEvent = Schema.Struct({
106
107
  ingestionTimestampMs: Schema.Number,
107
108
  logs: Schema.Array(TraceEventLog),
108
109
  exceptions: Schema.Array(TraceEventException),
109
- }).pipe(EchoObject({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));
110
+ }).pipe(Type.Obj({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));
110
111
 
111
112
  export type TraceEvent = Schema.Schema.Type<typeof TraceEvent>;
112
113
 
113
114
  /**
114
- * Deprecated InvocationTrace event format.
115
- * @deprecated
115
+ * InvocationTrace event format.
116
+ * This is the combined format of InvocationTraceStartEvent and InvocationTraceEndEvents for UI consumption.
116
117
  */
117
- // TODO(burdon): Remove.
118
118
  export type InvocationSpan = {
119
119
  id: string;
120
120
  timestampMs: number;
121
121
  outcome: InvocationOutcome;
122
122
  input: object;
123
123
  durationMs: number;
124
- invocationTraceQueue: Ref<Queue>;
125
- invocationTarget: Ref<Expando>;
126
- trigger?: Ref<FunctionTriggerType>;
124
+ invocationTraceQueue: Ref.Ref<Queue>;
125
+ invocationTarget: Ref.Ref<Type.Expando>;
126
+ trigger?: Ref.Ref<FunctionTriggerType>;
127
127
  exception?: TraceEventException;
128
128
  };
129
129
 
@@ -2,13 +2,18 @@
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
4
 
5
+ import { Type } from '@dxos/echo';
6
+
5
7
  import { ScriptType } from './schema';
6
8
 
7
9
  export default [
8
10
  {
9
11
  'en-US': {
10
- [ScriptType.typename]: {
12
+ [Type.getTypename(ScriptType)]: {
11
13
  'typename label': 'Script',
14
+ 'typename label_zero': 'Scripts',
15
+ 'typename label_one': 'Script',
16
+ 'typename label_other': 'Scripts',
12
17
  },
13
18
  },
14
19
  },