@dxos/functions 0.8.4-main.b97322e → 0.8.4-main.bc674ce

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 (164) hide show
  1. package/dist/lib/browser/index.mjs +1098 -372
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +1098 -372
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +91 -38
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +7 -0
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/example/reply.d.ts +3 -0
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/example/sleep.d.ts +5 -0
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +5 -7
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  22. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  23. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  24. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  25. package/dist/types/src/protocol/index.d.ts +2 -0
  26. package/dist/types/src/protocol/index.d.ts.map +1 -0
  27. package/dist/types/src/protocol/protocol.d.ts +7 -0
  28. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  29. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  30. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  31. package/dist/types/src/sdk.d.ts +114 -0
  32. package/dist/types/src/sdk.d.ts.map +1 -0
  33. package/dist/types/src/services/credentials.d.ts +22 -3
  34. package/dist/types/src/services/credentials.d.ts.map +1 -1
  35. package/dist/types/src/services/event-logger.d.ts +74 -30
  36. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  37. package/dist/types/src/services/function-invocation-service.d.ts +16 -0
  38. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  39. package/dist/types/src/services/index.d.ts +5 -5
  40. package/dist/types/src/services/index.d.ts.map +1 -1
  41. package/dist/types/src/services/queues.d.ts +23 -6
  42. package/dist/types/src/services/queues.d.ts.map +1 -1
  43. package/dist/types/src/services/tracing.d.ts +70 -7
  44. package/dist/types/src/services/tracing.d.ts.map +1 -1
  45. package/dist/types/src/types/Function.d.ts +52 -0
  46. package/dist/types/src/types/Function.d.ts.map +1 -0
  47. package/dist/types/src/types/Script.d.ts +21 -0
  48. package/dist/types/src/types/Script.d.ts.map +1 -0
  49. package/dist/types/src/types/Trigger.d.ts +121 -0
  50. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  51. package/dist/types/src/types/TriggerEvent.d.ts +74 -0
  52. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  53. package/dist/types/src/types/index.d.ts +6 -0
  54. package/dist/types/src/types/index.d.ts.map +1 -0
  55. package/dist/types/src/types/url.d.ts +13 -0
  56. package/dist/types/src/types/url.d.ts.map +1 -0
  57. package/dist/types/tsconfig.tsbuildinfo +1 -1
  58. package/package.json +26 -68
  59. package/src/errors.ts +13 -5
  60. package/src/example/fib.ts +32 -0
  61. package/src/example/forex-effect.ts +40 -0
  62. package/src/example/index.ts +13 -0
  63. package/src/example/reply.ts +21 -0
  64. package/src/example/sleep.ts +24 -0
  65. package/src/index.ts +5 -9
  66. package/src/operation-compatibility.test.ts +185 -0
  67. package/src/protocol/functions-ai-http-client.ts +67 -0
  68. package/src/{executor → protocol}/index.ts +1 -1
  69. package/src/protocol/protocol.test.ts +59 -0
  70. package/src/protocol/protocol.ts +262 -0
  71. package/src/sdk.ts +289 -0
  72. package/src/services/credentials.ts +101 -3
  73. package/src/services/event-logger.ts +77 -37
  74. package/src/services/function-invocation-service.ts +37 -0
  75. package/src/services/index.ts +5 -5
  76. package/src/services/queues.ts +37 -10
  77. package/src/services/tracing.ts +142 -17
  78. package/src/types/Function.ts +82 -0
  79. package/src/types/Script.ts +34 -0
  80. package/src/types/Trigger.ts +143 -0
  81. package/src/types/TriggerEvent.ts +62 -0
  82. package/src/types/index.ts +9 -0
  83. package/src/types/url.ts +32 -0
  84. package/dist/lib/browser/bundler/index.mjs +0 -247
  85. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  86. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  87. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  88. package/dist/lib/browser/edge/index.mjs +0 -69
  89. package/dist/lib/browser/edge/index.mjs.map +0 -7
  90. package/dist/lib/browser/testing/index.mjs +0 -91
  91. package/dist/lib/browser/testing/index.mjs.map +0 -7
  92. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  93. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  94. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  95. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  96. package/dist/lib/node-esm/edge/index.mjs +0 -71
  97. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  98. package/dist/lib/node-esm/testing/index.mjs +0 -92
  99. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  100. package/dist/types/src/bundler/bundler.d.ts +0 -50
  101. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  102. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  103. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  104. package/dist/types/src/bundler/index.d.ts +0 -2
  105. package/dist/types/src/bundler/index.d.ts.map +0 -1
  106. package/dist/types/src/edge/functions.d.ts +0 -16
  107. package/dist/types/src/edge/functions.d.ts.map +0 -1
  108. package/dist/types/src/edge/index.d.ts +0 -2
  109. package/dist/types/src/edge/index.d.ts.map +0 -1
  110. package/dist/types/src/executor/executor.d.ts +0 -8
  111. package/dist/types/src/executor/executor.d.ts.map +0 -1
  112. package/dist/types/src/executor/index.d.ts +0 -2
  113. package/dist/types/src/executor/index.d.ts.map +0 -1
  114. package/dist/types/src/handler.d.ts +0 -62
  115. package/dist/types/src/handler.d.ts.map +0 -1
  116. package/dist/types/src/schema.d.ts +0 -38
  117. package/dist/types/src/schema.d.ts.map +0 -1
  118. package/dist/types/src/services/database.d.ts +0 -29
  119. package/dist/types/src/services/database.d.ts.map +0 -1
  120. package/dist/types/src/services/function-call-service.d.ts +0 -16
  121. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  122. package/dist/types/src/services/service-container.d.ts +0 -56
  123. package/dist/types/src/services/service-container.d.ts.map +0 -1
  124. package/dist/types/src/services/service-registry.d.ts +0 -29
  125. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  126. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  127. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  128. package/dist/types/src/testing/index.d.ts +0 -3
  129. package/dist/types/src/testing/index.d.ts.map +0 -1
  130. package/dist/types/src/testing/layer.d.ts +0 -10
  131. package/dist/types/src/testing/layer.d.ts.map +0 -1
  132. package/dist/types/src/testing/logger.d.ts +0 -5
  133. package/dist/types/src/testing/logger.d.ts.map +0 -1
  134. package/dist/types/src/testing/services.d.ts +0 -70
  135. package/dist/types/src/testing/services.d.ts.map +0 -1
  136. package/dist/types/src/trace.d.ts +0 -124
  137. package/dist/types/src/trace.d.ts.map +0 -1
  138. package/dist/types/src/translations.d.ts +0 -12
  139. package/dist/types/src/translations.d.ts.map +0 -1
  140. package/dist/types/src/types.d.ts +0 -411
  141. package/dist/types/src/types.d.ts.map +0 -1
  142. package/dist/types/src/url.d.ts +0 -17
  143. package/dist/types/src/url.d.ts.map +0 -1
  144. package/src/bundler/bundler.test.ts +0 -59
  145. package/src/bundler/bundler.ts +0 -292
  146. package/src/bundler/index.ts +0 -5
  147. package/src/edge/functions.ts +0 -64
  148. package/src/edge/index.ts +0 -9
  149. package/src/executor/executor.ts +0 -54
  150. package/src/handler.ts +0 -120
  151. package/src/schema.ts +0 -57
  152. package/src/services/database.ts +0 -70
  153. package/src/services/function-call-service.ts +0 -64
  154. package/src/services/service-container.ts +0 -113
  155. package/src/services/service-registry.test.ts +0 -42
  156. package/src/services/service-registry.ts +0 -56
  157. package/src/testing/index.ts +0 -6
  158. package/src/testing/layer.ts +0 -31
  159. package/src/testing/logger.ts +0 -16
  160. package/src/testing/services.ts +0 -168
  161. package/src/trace.ts +0 -180
  162. package/src/translations.ts +0 -20
  163. package/src/types.ts +0 -211
  164. package/src/url.ts +0 -52
@@ -1,64 +0,0 @@
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
- };
@@ -1,113 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { type Context, Layer } from 'effect';
6
-
7
- import { AiService } from '@dxos/ai';
8
- import { entries } from '@dxos/util';
9
-
10
- import { ConfiguredCredentialsService, CredentialsService } from './credentials';
11
- import { DatabaseService } from './database';
12
- import { EventLogger } from './event-logger';
13
- import { FunctionCallService } from './function-call-service';
14
- import { QueueService } from './queues';
15
- import { TracingService } from './tracing';
16
-
17
- // TODO(dmaretskyi): Refactor this module to only rely on tags and not the human-assigned names.
18
-
19
- /**
20
- * List of all services.
21
- */
22
- const SERVICES = {
23
- ai: AiService,
24
- credentials: CredentialsService,
25
- database: DatabaseService,
26
- eventLogger: EventLogger,
27
- functionCallService: FunctionCallService,
28
- queues: QueueService,
29
- tracing: TracingService,
30
- } as const satisfies Record<string, Context.TagClass<any, string, any>>;
31
-
32
- /**
33
- * Mapping of service names to their tags.
34
- */
35
- export type ServiceTagRecord = {
36
- [K in keyof typeof SERVICES]: (typeof SERVICES)[K] extends { new (_: never): infer T } ? T : never;
37
- };
38
-
39
- /**
40
- * Mapping of service names to their runtime types.
41
- */
42
- export type ServiceRecord = {
43
- [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;
44
- };
45
-
46
- /**
47
- * Union of all services tags.
48
- */
49
- export type Services = ServiceTagRecord[keyof ServiceTagRecord];
50
-
51
- const SERVICE_MAPPING: Record<string, keyof ServiceRecord> = Object.fromEntries(
52
- entries(SERVICES).map(([name, tag]) => [tag.key, name]),
53
- );
54
-
55
- export const SERVICE_TAGS: Context.Tag<any, any>[] = Object.values(SERVICES);
56
-
57
- const DEFAULT_SERVICES: Partial<ServiceRecord> = {
58
- tracing: TracingService.noop,
59
- };
60
-
61
- /**
62
- * @deprecated
63
- */
64
- export class ServiceContainer {
65
- private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };
66
-
67
- /**
68
- * Set services.
69
- * @param services - Services to set.
70
- * @returns The container instance.
71
- */
72
- setServices(services: Partial<ServiceRecord>): this {
73
- this._services = { ...this._services, ...services };
74
- return this;
75
- }
76
-
77
- getService<Id, T>(tag: Context.Tag<Id, T>): T {
78
- const serviceKey = SERVICE_MAPPING[tag.key];
79
- const service = serviceKey != null ? this._services[serviceKey] : undefined;
80
- if (!service) {
81
- throw new Error(`Service not available: ${tag.key}`);
82
- }
83
-
84
- return service as T;
85
- }
86
-
87
- clone(): ServiceContainer {
88
- return new ServiceContainer().setServices({ ...this._services });
89
- }
90
-
91
- // 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.
92
- createLayer(): Layer.Layer<Services> {
93
- const ai = this._services.ai != null ? Layer.succeed(AiService, this._services.ai) : AiService.notAvailable;
94
- const credentials = Layer.succeed(
95
- CredentialsService,
96
- this._services.credentials ?? new ConfiguredCredentialsService(),
97
- );
98
- const database =
99
- this._services.database != null
100
- ? Layer.succeed(DatabaseService, this._services.database)
101
- : DatabaseService.notAvailable;
102
- const queues =
103
- this._services.queues != null ? Layer.succeed(QueueService, this._services.queues) : QueueService.notAvailable;
104
- const tracing = Layer.succeed(TracingService, this._services.tracing ?? TracingService.noop);
105
- const eventLogger = Layer.succeed(EventLogger, this._services.eventLogger ?? EventLogger.noop);
106
- const functionCallService = Layer.succeed(
107
- FunctionCallService,
108
- this._services.functionCallService ?? FunctionCallService.mock(),
109
- );
110
-
111
- return Layer.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);
112
- }
113
- }
@@ -1,42 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { describe, it } from '@effect/vitest';
6
- import { Context, Effect, Layer, Option } from 'effect';
7
-
8
- import { ServiceRegistry } from './service-registry';
9
-
10
- class MyTag extends Context.Tag('MyTag')<MyTag, { value: string }>() {}
11
-
12
- const mockRegistry = Layer.succeed(ServiceRegistry, {
13
- resolve: (tag) => ((tag as any) === MyTag ? Option.some({ value: 'test' } as any) : Option.none()),
14
- });
15
-
16
- describe('ServiceRegistry', () => {
17
- it.effect(
18
- 'provide',
19
- Effect.fn(function* ({ expect }) {
20
- const body = Effect.gen(function* () {
21
- const { value } = yield* MyTag;
22
- expect(value).toEqual('test');
23
- });
24
-
25
- const eff = body.pipe(ServiceRegistry.provide(MyTag));
26
- yield* eff;
27
- }, Effect.provide(mockRegistry)),
28
- );
29
-
30
- it.effect(
31
- 'provide or die',
32
- Effect.fn(function* ({ expect }) {
33
- const body = Effect.gen(function* () {
34
- const { value } = yield* MyTag;
35
- expect(value).toEqual('test');
36
- });
37
-
38
- const eff = body.pipe(ServiceRegistry.provideOrDie(MyTag));
39
- yield* eff;
40
- }, Effect.provide(mockRegistry)),
41
- );
42
- });
@@ -1,56 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Context, Effect, flow, type Option } from 'effect';
6
-
7
- import { ServiceNotAvailableError } from '../errors';
8
-
9
- export namespace ServiceRegistry {
10
- export interface Service {
11
- resolve: <T extends Context.Tag<any, any>>(tag: T) => Option.Option<Context.Tag.Service<T>>;
12
- }
13
- }
14
-
15
- export class ServiceRegistry extends Context.Tag('ServiceRegistry')<ServiceRegistry, ServiceRegistry.Service>() {
16
- /**
17
- * Resolves the service from the registry.
18
- * @param tag Service tag to resolve.
19
- * @throws {@link ServiceNotAvailableError} if the service is not found.
20
- * @returns Effect that resolve to the service.
21
- */
22
- static resolve: <T extends Context.Tag<any, any>>(
23
- tag: T,
24
- ) => Effect.Effect<T, ServiceNotAvailableError, ServiceRegistry> = (tag) =>
25
- ServiceRegistry.pipe(
26
- Effect.flatMap((_) => _.resolve(tag)),
27
- Effect.mapError(() => new ServiceNotAvailableError(tag.key)),
28
- );
29
-
30
- static provide: {
31
- <Tags extends [Context.Tag<any, any>, ...Context.Tag<any, any>[]]>(
32
- ...tags: Tags
33
- ): <A, E, R>(
34
- effect: Effect.Effect<A, E, R>,
35
- ) => Effect.Effect<
36
- A,
37
- E | ServiceNotAvailableError,
38
- Exclude<R, { [K in keyof Tags]: Context.Tag.Identifier<Tags[K]> }[number]> | ServiceRegistry
39
- >;
40
- } = (...tags) => (flow as any)(...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag))));
41
-
42
- static provideOrDie: {
43
- <Tags extends [Context.Tag<any, any>, ...Context.Tag<any, any>[]]>(
44
- ...tags: Tags
45
- ): <A, E, R>(
46
- effect: Effect.Effect<A, E, R>,
47
- ) => Effect.Effect<
48
- A,
49
- E,
50
- Exclude<R, { [K in keyof Tags]: Context.Tag.Identifier<Tags[K]> }[number]> | ServiceRegistry
51
- >;
52
- } = (...tags) =>
53
- (flow as any)(
54
- ...tags.map((tag) => Effect.provideServiceEffect(tag, ServiceRegistry.resolve(tag).pipe(Effect.orDie))),
55
- );
56
- }
@@ -1,6 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- export * from './services';
6
- export * from './layer';
@@ -1,31 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Context, Effect, Layer } from 'effect';
6
- import type { Schema } from 'effect';
7
-
8
- import { EchoTestBuilder } from '@dxos/echo-db/testing';
9
- import type { EchoHostIndexingConfig } from '@dxos/echo-pipeline';
10
- import { accuireReleaseResource } from '@dxos/effect';
11
-
12
- import { DatabaseService, QueueService } from '../services';
13
-
14
- const testBuilder = accuireReleaseResource(() => new EchoTestBuilder());
15
-
16
- export type TestDatabaseOptions = {
17
- indexing?: Partial<EchoHostIndexingConfig>;
18
- types?: Schema.Schema.AnyNoContext[];
19
- };
20
-
21
- export const TestDatabaseLayer = ({ indexing, types }: TestDatabaseOptions = {}) =>
22
- Layer.scopedContext(
23
- Effect.gen(function* () {
24
- const builder = yield* testBuilder;
25
- const { db, queues } = yield* Effect.promise(() => builder.createDatabase({ indexing, types }));
26
- return Context.mergeAll(
27
- Context.make(DatabaseService, DatabaseService.make(db)),
28
- Context.make(QueueService, QueueService.make(queues, undefined)),
29
- );
30
- }),
31
- );
@@ -1,16 +0,0 @@
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);
@@ -1,168 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { type Context } from 'effect';
6
-
7
- import { AiService, type AiServiceClient, type AiServiceEdgeClientOptions, EdgeAiServiceClient } from '@dxos/ai';
8
- import { AI_SERVICE_ENDPOINT, createTestAiServiceClient } from '@dxos/ai/testing';
9
- import type { Space } from '@dxos/client/echo';
10
- import type { EchoDatabase, QueueFactory } from '@dxos/echo-db';
11
- import { assertArgument } from '@dxos/invariant';
12
-
13
- import { consoleLogger, noopLogger } from './logger';
14
- import {
15
- ConfiguredCredentialsService,
16
- type CredentialsService,
17
- DatabaseService,
18
- type EventLogger,
19
- QueueService,
20
- ServiceContainer,
21
- type ServiceCredential,
22
- type TracingService,
23
- } from '../services';
24
-
25
- // TODO(burdon): Factor out.
26
- export type OneOf<T> = {
27
- [K in keyof T]: { [P in K]: T[P] } & { [P in Exclude<keyof T, K>]?: never };
28
- }[keyof T];
29
-
30
- export type AiServiceProvider = 'dev' | 'edge' | 'ollama' | 'lmstudio';
31
-
32
- export type TestServiceOptions = {
33
- /**
34
- * AI service configuration.
35
- */
36
- ai?: OneOf<{
37
- /**
38
- * Custom AI service client.
39
- */
40
- client?: AiServiceClient;
41
-
42
- /**
43
- * Edge AI service at specified endpoint.
44
- */
45
- endpoint?: AiServiceEdgeClientOptions['endpoint'];
46
-
47
- /**
48
- * Predefined AI service configuration.
49
- */
50
- // TODO(burdon): 'dev' and 'edge' are redundant with providing an endpoint.
51
- provider?: AiServiceProvider;
52
- }>;
53
-
54
- /**
55
- * Credentials service configuration.
56
- */
57
- credentials?: OneOf<{
58
- /**
59
- * Predefined credentials list.
60
- */
61
- services?: ServiceCredential[];
62
-
63
- /**
64
- * Custom credentials service.
65
- */
66
- service?: Context.Tag.Service<CredentialsService>;
67
- }>;
68
-
69
- /**
70
- * Database configuration.
71
- */
72
- db?: EchoDatabase;
73
-
74
- /**
75
- * Gets database and queue services from the space.
76
- * Exclusive with: `db`, `queues`
77
- */
78
- space?: Space;
79
-
80
- /**
81
- * Logging configuration.
82
- */
83
- logging?: {
84
- enabled?: boolean;
85
- logger?: Context.Tag.Service<EventLogger>;
86
- };
87
-
88
- /**
89
- * Queue service configuration.
90
- */
91
- queues?: QueueFactory;
92
-
93
- tracing?: {
94
- service?: Context.Tag.Service<TracingService>;
95
- };
96
- };
97
-
98
- export const createTestServices = ({
99
- ai,
100
- credentials,
101
- db,
102
- logging,
103
- queues,
104
- space,
105
- tracing,
106
- }: TestServiceOptions = {}): ServiceContainer => {
107
- assertArgument(!(!!space && (!!db || !!queues)), 'space can be provided only if db and queues are not');
108
-
109
- return new ServiceContainer().setServices({
110
- ai: createAiService(ai),
111
- credentials: createCredentialsService(credentials),
112
- database: space || db ? DatabaseService.make(space?.db || db!) : undefined,
113
- eventLogger: (logging?.logger ?? logging?.enabled) ? consoleLogger : noopLogger,
114
- queues: space || queues ? QueueService.make(space?.queues || queues!, undefined) : undefined,
115
- tracing: tracing?.service,
116
- });
117
- };
118
-
119
- // TODO(burdon): Enable model configuration.
120
- const createAiService = (ai: TestServiceOptions['ai']): Context.Tag.Service<AiService> | undefined => {
121
- if (ai?.client != null) {
122
- return AiService.make(ai.client);
123
- }
124
-
125
- if (ai?.endpoint != null) {
126
- return AiService.make(new EdgeAiServiceClient({ endpoint: ai.endpoint }));
127
- }
128
-
129
- switch (ai?.provider) {
130
- case 'dev':
131
- return AiService.make(
132
- new EdgeAiServiceClient({
133
- endpoint: AI_SERVICE_ENDPOINT.LOCAL,
134
- defaultGenerationOptions: {
135
- model: '@anthropic/claude-3-5-sonnet-20241022',
136
- },
137
- }),
138
- );
139
-
140
- case 'edge':
141
- return AiService.make(
142
- new EdgeAiServiceClient({
143
- endpoint: AI_SERVICE_ENDPOINT.REMOTE,
144
- defaultGenerationOptions: {
145
- model: '@anthropic/claude-3-5-sonnet-20241022',
146
- },
147
- }),
148
- );
149
-
150
- case 'ollama':
151
- return AiService.make(createTestAiServiceClient());
152
-
153
- case 'lmstudio':
154
- throw new Error('LMStudio is not supported');
155
- }
156
- };
157
-
158
- const createCredentialsService = (
159
- credentials: TestServiceOptions['credentials'] | undefined,
160
- ): Context.Tag.Service<CredentialsService> | undefined => {
161
- if (credentials?.services) {
162
- return new ConfiguredCredentialsService(credentials.services);
163
- }
164
-
165
- if (credentials?.service) {
166
- return credentials.service;
167
- }
168
- };
package/src/trace.ts DELETED
@@ -1,180 +0,0 @@
1
- //
2
- // Copyright 2025 DXOS.org
3
- //
4
-
5
- import { Schema } from 'effect';
6
-
7
- import { Type, type Ref } from '@dxos/echo';
8
- import { Queue } from '@dxos/echo-db';
9
- import { ObjectId } from '@dxos/echo-schema';
10
- import { log } from '@dxos/log';
11
-
12
- import { FunctionTrigger, type FunctionTriggerType } from './types';
13
-
14
- export enum InvocationOutcome {
15
- SUCCESS = 'success',
16
- FAILURE = 'failure',
17
- PENDING = 'pending',
18
- }
19
-
20
- // TODO(burdon): Convert to extensible discriminated union of EDGE events.
21
- export enum InvocationTraceEventType {
22
- START = 'start',
23
- END = 'end',
24
- }
25
-
26
- export const TraceEventException = Schema.Struct({
27
- timestampMs: Schema.Number,
28
- message: Schema.String,
29
- name: Schema.String,
30
- stack: Schema.optional(Schema.String),
31
- });
32
- export type TraceEventException = Schema.Schema.Type<typeof TraceEventException>;
33
-
34
- export const InvocationTraceStartEvent = Schema.Struct({
35
- /**
36
- * Queue message id.
37
- */
38
- id: ObjectId,
39
- type: Schema.Literal(InvocationTraceEventType.START),
40
- /**
41
- * Invocation id, the same for invocation start and end events.
42
- */
43
- invocationId: ObjectId,
44
- /**
45
- * Event generation time.
46
- */
47
- timestampMs: Schema.Number,
48
- /**
49
- * Data passed to function / workflow as an argument.
50
- */
51
- // TODO(burdon): Input schema?
52
- input: Schema.Object,
53
- /**
54
- * Queue for function/workflow invocation events.
55
- */
56
- invocationTraceQueue: Type.Ref(Queue),
57
- /**
58
- * DXN of the invoked function/workflow.
59
- */
60
- invocationTarget: Type.Ref(Type.Expando),
61
- /**
62
- * Present for automatic invocations.
63
- */
64
- trigger: Schema.optional(Type.Ref(FunctionTrigger)),
65
- }).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));
66
-
67
- export type InvocationTraceStartEvent = Schema.Schema.Type<typeof InvocationTraceStartEvent>;
68
-
69
- export const InvocationTraceEndEvent = Schema.Struct({
70
- /**
71
- * Trace event id.
72
- */
73
- id: ObjectId,
74
- type: Schema.Literal(InvocationTraceEventType.END),
75
- /**
76
- * Invocation id, will be the same for invocation start and end.
77
- */
78
- invocationId: ObjectId,
79
- /**
80
- * Event generation time.
81
- */
82
- // TODO(burdon): Remove ms suffix.
83
- timestampMs: Schema.Number,
84
- outcome: Schema.Enums(InvocationOutcome),
85
- exception: Schema.optional(TraceEventException),
86
- }).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));
87
-
88
- export type InvocationTraceEndEvent = Schema.Schema.Type<typeof InvocationTraceEndEvent>;
89
-
90
- export type InvocationTraceEvent = InvocationTraceStartEvent | InvocationTraceEndEvent;
91
-
92
- export const TraceEventLog = Schema.Struct({
93
- timestampMs: Schema.Number,
94
- level: Schema.String,
95
- message: Schema.String,
96
- context: Schema.optional(Schema.Object),
97
- });
98
-
99
- export const TraceEvent = Schema.Struct({
100
- id: ObjectId,
101
- // TODO(burdon): Need enum/numeric result (not string).
102
- outcome: Schema.String,
103
- truncated: Schema.Boolean,
104
- /**
105
- * Time when the event was persisted.
106
- */
107
- ingestionTimestampMs: Schema.Number,
108
- logs: Schema.Array(TraceEventLog),
109
- exceptions: Schema.Array(TraceEventException),
110
- }).pipe(Type.Obj({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));
111
-
112
- export type TraceEvent = Schema.Schema.Type<typeof TraceEvent>;
113
-
114
- /**
115
- * InvocationTrace event format.
116
- * This is the combined format of InvocationTraceStartEvent and InvocationTraceEndEvents for UI consumption.
117
- */
118
- export type InvocationSpan = {
119
- id: string;
120
- timestampMs: number;
121
- outcome: InvocationOutcome;
122
- input: object;
123
- durationMs: number;
124
- invocationTraceQueue: Ref.Ref<Queue>;
125
- invocationTarget: Ref.Ref<Type.Expando>;
126
- trigger?: Ref.Ref<FunctionTriggerType>;
127
- exception?: TraceEventException;
128
- };
129
-
130
- export const createInvocationSpans = (items?: InvocationTraceEvent[]): InvocationSpan[] => {
131
- if (!items) {
132
- return [];
133
- }
134
-
135
- const eventsByInvocationId = new Map<string, { start?: InvocationTraceStartEvent; end?: InvocationTraceEndEvent }>();
136
- for (const event of items) {
137
- if (!('invocationId' in event)) {
138
- // Skip legacy format entries.
139
- continue;
140
- }
141
-
142
- const invocationId = event.invocationId;
143
- const entry = eventsByInvocationId.get(invocationId) || { start: undefined, end: undefined };
144
- if (event.type === InvocationTraceEventType.START) {
145
- entry.start = event as InvocationTraceStartEvent;
146
- } else if (event.type === InvocationTraceEventType.END) {
147
- entry.end = event as InvocationTraceEndEvent;
148
- }
149
-
150
- eventsByInvocationId.set(invocationId, entry);
151
- }
152
-
153
- const now = Date.now();
154
- const result: InvocationSpan[] = [];
155
-
156
- // Create spans for each invocation
157
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
158
- if (!start) {
159
- // No start event, can't create a meaningful span
160
- log.warn('found end event without matching start', { invocationId });
161
- continue;
162
- }
163
-
164
- const isInProgress = end === undefined;
165
-
166
- result.push({
167
- id: invocationId,
168
- timestampMs: start.timestampMs,
169
- durationMs: isInProgress ? now - start.timestampMs : end!.timestampMs - start.timestampMs,
170
- outcome: end?.outcome ?? InvocationOutcome.PENDING,
171
- exception: end?.exception,
172
- input: start.input,
173
- invocationTraceQueue: start.invocationTraceQueue,
174
- invocationTarget: start.invocationTarget,
175
- trigger: start.trigger,
176
- });
177
- }
178
-
179
- return result;
180
- };
@@ -1,20 +0,0 @@
1
- //
2
- // Copyright 2023 DXOS.org
3
- //
4
-
5
- import { type Resource } from 'i18next';
6
-
7
- import { ScriptType } from './schema';
8
-
9
- export const translations = [
10
- {
11
- 'en-US': {
12
- [ScriptType.typename]: {
13
- 'typename label': 'Script',
14
- 'typename label_zero': 'Scripts',
15
- 'typename label_one': 'Script',
16
- 'typename label_other': 'Scripts',
17
- },
18
- },
19
- },
20
- ] as const satisfies Resource[];