@dxos/compute 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef

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 (161) hide show
  1. package/README.md +36 -1
  2. package/dist/lib/neutral/StorageService.mjs +22 -0
  3. package/dist/lib/neutral/chunk-4N4JAXCP.mjs +17 -0
  4. package/dist/lib/neutral/chunk-4N4JAXCP.mjs.map +7 -0
  5. package/dist/lib/neutral/chunk-DDEBBRCI.mjs +62 -0
  6. package/dist/lib/neutral/chunk-DDEBBRCI.mjs.map +7 -0
  7. package/dist/lib/neutral/chunk-FEABF5XY.mjs +25 -0
  8. package/dist/lib/neutral/chunk-FEABF5XY.mjs.map +7 -0
  9. package/dist/lib/neutral/chunk-H6EHIVDN.mjs +21 -0
  10. package/dist/lib/neutral/chunk-H6EHIVDN.mjs.map +7 -0
  11. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  12. package/dist/lib/neutral/chunk-N462A6NO.mjs +138 -0
  13. package/dist/lib/neutral/chunk-N462A6NO.mjs.map +7 -0
  14. package/dist/lib/neutral/chunk-QPCDM7MF.mjs +179 -0
  15. package/dist/lib/neutral/chunk-QPCDM7MF.mjs.map +7 -0
  16. package/dist/lib/neutral/chunk-S24LL2D5.mjs +52 -0
  17. package/dist/lib/neutral/chunk-S24LL2D5.mjs.map +7 -0
  18. package/dist/lib/neutral/fib-HDHBZHPE.mjs +10 -0
  19. package/dist/lib/neutral/fib-HDHBZHPE.mjs.map +7 -0
  20. package/dist/lib/neutral/index.mjs +1034 -0
  21. package/dist/lib/neutral/index.mjs.map +7 -0
  22. package/dist/lib/neutral/meta.json +1 -0
  23. package/dist/lib/neutral/reply-XSQMXAPX.mjs +10 -0
  24. package/dist/lib/neutral/reply-XSQMXAPX.mjs.map +7 -0
  25. package/dist/lib/neutral/sleep-WHTJQ56P.mjs +10 -0
  26. package/dist/lib/neutral/sleep-WHTJQ56P.mjs.map +7 -0
  27. package/dist/lib/neutral/testing/index.mjs +32 -0
  28. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  29. package/dist/types/src/Blueprint.d.ts +148 -0
  30. package/dist/types/src/Blueprint.d.ts.map +1 -0
  31. package/dist/types/src/Credential.d.ts +27 -0
  32. package/dist/types/src/Credential.d.ts.map +1 -0
  33. package/dist/types/src/Operation.d.ts +303 -0
  34. package/dist/types/src/Operation.d.ts.map +1 -0
  35. package/dist/types/src/OperationHandlerSet.d.ts +60 -0
  36. package/dist/types/src/OperationHandlerSet.d.ts.map +1 -0
  37. package/dist/types/src/OperationRegistry.d.ts +23 -0
  38. package/dist/types/src/OperationRegistry.d.ts.map +1 -0
  39. package/dist/types/src/Process.d.ts +247 -0
  40. package/dist/types/src/Process.d.ts.map +1 -0
  41. package/dist/types/src/Routine.d.ts +61 -0
  42. package/dist/types/src/Routine.d.ts.map +1 -0
  43. package/dist/types/src/Script.d.ts +22 -0
  44. package/dist/types/src/Script.d.ts.map +1 -0
  45. package/dist/types/src/ServiceResolver.d.ts +74 -0
  46. package/dist/types/src/ServiceResolver.d.ts.map +1 -0
  47. package/dist/types/src/StorageService.d.ts +58 -0
  48. package/dist/types/src/StorageService.d.ts.map +1 -0
  49. package/dist/types/src/Template.d.ts +56 -0
  50. package/dist/types/src/Template.d.ts.map +1 -0
  51. package/dist/types/src/Trace.d.ts +174 -0
  52. package/dist/types/src/Trace.d.ts.map +1 -0
  53. package/dist/types/src/Trigger.d.ts +150 -0
  54. package/dist/types/src/Trigger.d.ts.map +1 -0
  55. package/dist/types/src/TriggerEvent.d.ts +75 -0
  56. package/dist/types/src/TriggerEvent.d.ts.map +1 -0
  57. package/dist/types/src/errors.d.ts +239 -0
  58. package/dist/types/src/errors.d.ts.map +1 -0
  59. package/dist/types/src/index.d.ts +15 -5
  60. package/dist/types/src/index.d.ts.map +1 -1
  61. package/dist/types/src/testing/definitions.d.ts +11 -0
  62. package/dist/types/src/testing/definitions.d.ts.map +1 -0
  63. package/dist/types/src/testing/fib.d.ts +8 -0
  64. package/dist/types/src/testing/fib.d.ts.map +1 -0
  65. package/dist/types/src/testing/index.d.ts +6 -3
  66. package/dist/types/src/testing/index.d.ts.map +1 -1
  67. package/dist/types/src/testing/reply.d.ts +4 -0
  68. package/dist/types/src/testing/reply.d.ts.map +1 -0
  69. package/dist/types/src/testing/sleep.d.ts +6 -0
  70. package/dist/types/src/testing/sleep.d.ts.map +1 -0
  71. package/dist/types/src/umbrella.test.d.ts +2 -0
  72. package/dist/types/src/umbrella.test.d.ts.map +1 -0
  73. package/dist/types/tsconfig.tsbuildinfo +1 -1
  74. package/package.json +27 -39
  75. package/src/Blueprint.ts +221 -0
  76. package/src/Credential.ts +51 -0
  77. package/src/Operation.ts +513 -0
  78. package/src/OperationHandlerSet.ts +132 -0
  79. package/src/OperationRegistry.ts +48 -0
  80. package/src/Process.ts +490 -0
  81. package/src/Routine.ts +84 -0
  82. package/src/Script.ts +38 -0
  83. package/src/ServiceResolver.ts +174 -0
  84. package/src/StorageService.ts +99 -0
  85. package/src/Template.ts +105 -0
  86. package/src/Trace.ts +231 -0
  87. package/src/Trigger.ts +207 -0
  88. package/src/TriggerEvent.ts +62 -0
  89. package/src/errors.ts +50 -0
  90. package/src/index.ts +16 -33
  91. package/src/testing/definitions.ts +49 -0
  92. package/src/testing/fib.ts +22 -0
  93. package/src/testing/index.ts +13 -4
  94. package/src/testing/reply.ts +18 -0
  95. package/src/testing/sleep.ts +16 -0
  96. package/src/umbrella.test.ts +51 -0
  97. package/dist/lib/browser/chunk-XQYPCRZP.mjs +0 -3140
  98. package/dist/lib/browser/chunk-XQYPCRZP.mjs.map +0 -7
  99. package/dist/lib/browser/index.mjs +0 -55
  100. package/dist/lib/browser/meta.json +0 -1
  101. package/dist/lib/browser/testing/index.mjs +0 -186
  102. package/dist/lib/browser/testing/index.mjs.map +0 -7
  103. package/dist/lib/node-esm/chunk-2XWWSGAU.mjs +0 -3142
  104. package/dist/lib/node-esm/chunk-2XWWSGAU.mjs.map +0 -7
  105. package/dist/lib/node-esm/index.mjs +0 -56
  106. package/dist/lib/node-esm/meta.json +0 -1
  107. package/dist/lib/node-esm/testing/index.mjs +0 -187
  108. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  109. package/dist/types/src/compute-graph-registry.d.ts +0 -32
  110. package/dist/types/src/compute-graph-registry.d.ts.map +0 -1
  111. package/dist/types/src/compute-graph.d.ts +0 -64
  112. package/dist/types/src/compute-graph.d.ts.map +0 -1
  113. package/dist/types/src/compute-graph.test.d.ts +0 -2
  114. package/dist/types/src/compute-graph.test.d.ts.map +0 -1
  115. package/dist/types/src/compute-node.d.ts +0 -24
  116. package/dist/types/src/compute-node.d.ts.map +0 -1
  117. package/dist/types/src/functions/async-function.d.ts +0 -66
  118. package/dist/types/src/functions/async-function.d.ts.map +0 -1
  119. package/dist/types/src/functions/edge-function.d.ts +0 -20
  120. package/dist/types/src/functions/edge-function.d.ts.map +0 -1
  121. package/dist/types/src/functions/function-defs.d.ts +0 -11
  122. package/dist/types/src/functions/function-defs.d.ts.map +0 -1
  123. package/dist/types/src/functions/index.d.ts +0 -4
  124. package/dist/types/src/functions/index.d.ts.map +0 -1
  125. package/dist/types/src/hyperformula.test.d.ts +0 -2
  126. package/dist/types/src/hyperformula.test.d.ts.map +0 -1
  127. package/dist/types/src/testing/test-builder.d.ts +0 -15
  128. package/dist/types/src/testing/test-builder.d.ts.map +0 -1
  129. package/dist/types/src/testing/test-plugin.d.ts +0 -35
  130. package/dist/types/src/testing/test-plugin.d.ts.map +0 -1
  131. package/dist/types/src/testing/util.d.ts +0 -2
  132. package/dist/types/src/testing/util.d.ts.map +0 -1
  133. package/dist/types/src/types/hyperformula.d.ts +0 -8
  134. package/dist/types/src/types/hyperformula.d.ts.map +0 -1
  135. package/dist/types/src/types/index.d.ts +0 -3
  136. package/dist/types/src/types/index.d.ts.map +0 -1
  137. package/dist/types/src/types/types.d.ts +0 -20
  138. package/dist/types/src/types/types.d.ts.map +0 -1
  139. package/dist/types/src/types/types.test.d.ts +0 -2
  140. package/dist/types/src/types/types.test.d.ts.map +0 -1
  141. package/dist/types/src/util.d.ts +0 -2
  142. package/dist/types/src/util.d.ts.map +0 -1
  143. package/src/compute-graph-registry.ts +0 -88
  144. package/src/compute-graph.test.ts +0 -88
  145. package/src/compute-graph.ts +0 -258
  146. package/src/compute-node.ts +0 -59
  147. package/src/functions/async-function.ts +0 -183
  148. package/src/functions/edge-function.ts +0 -111
  149. package/src/functions/function-defs.ts +0 -2427
  150. package/src/functions/index.ts +0 -7
  151. package/src/hyperformula.test.ts +0 -14
  152. package/src/testing/test-builder.ts +0 -54
  153. package/src/testing/test-plugin.ts +0 -98
  154. package/src/testing/util.ts +0 -9
  155. package/src/types/hyperformula.ts +0 -19
  156. package/src/types/index.ts +0 -6
  157. package/src/types/types.test.ts +0 -91
  158. package/src/types/types.ts +0 -80
  159. package/src/util.ts +0 -8
  160. /package/dist/lib/{browser/index.mjs.map → neutral/StorageService.mjs.map} +0 -0
  161. /package/dist/lib/{node-esm/index.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
@@ -0,0 +1,513 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ import * as Context from 'effect/Context';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Layer from 'effect/Layer';
8
+ import * as Pipeable from 'effect/Pipeable';
9
+ import * as Schema$ from 'effect/Schema';
10
+ import type * as Types from 'effect/Types';
11
+
12
+ import { Annotation, JsonSchema, Obj, Ref, Type, type DXN, type Key } from '@dxos/echo';
13
+
14
+ import type { NoHandlerError } from './errors';
15
+ import type { Operation } from './index';
16
+
17
+ // @import-as-namespace
18
+
19
+ /**
20
+ * Schema type that accepts any Encoded form but requires no Context.
21
+ * This allows ECHO object schemas where Type !== Encoded due to [KindId] symbol.
22
+ */
23
+ type Schema<T> = Schema$.Schema<T, any, never>;
24
+
25
+ export const DefinitionTypeId = '~@dxos/operation/OperationDefinition' as const;
26
+ export type DefinitionTypeId = typeof DefinitionTypeId;
27
+
28
+ /**
29
+ * Serializable definition of an Operation.
30
+ * Contains schema and metadata, but no runtime logic.
31
+ */
32
+ export interface Definition<I, O, S = any> extends Pipeable.Pipeable, Definition.Variance<I, O, S> {
33
+ /**
34
+ * Input schema for the operation.
35
+ */
36
+ readonly input: Schema<I>;
37
+ /**
38
+ * Output schema for the operation.
39
+ */
40
+ readonly output: Schema<O>;
41
+
42
+ readonly meta: {
43
+ readonly key: string;
44
+ readonly name?: string;
45
+ readonly version?: string;
46
+ readonly description?: string;
47
+ /**
48
+ * Deployment ID for remote invocation.
49
+ * Assigned by the EDGE function service when deployed.
50
+ */
51
+ readonly deployedId?: string;
52
+ };
53
+
54
+ /**
55
+ * Execution mode for the operation.
56
+ * - 'sync': Operation completes synchronously (fast, UI-blocking acceptable).
57
+ * - 'async': Operation may take time (should not block UI).
58
+ */
59
+ readonly executionMode: 'sync' | 'async';
60
+
61
+ /**
62
+ * ECHO types the operation uses.
63
+ * Ensures types are available when the operation is executed remotely.
64
+ */
65
+ readonly types: readonly Type.AnyEntity[];
66
+
67
+ /**
68
+ * Effect services required by this operation.
69
+ * These services will be automatically provided to the handler at invocation time.
70
+ */
71
+ readonly services: readonly Context.Tag<any, any>[];
72
+ }
73
+
74
+ /**
75
+ * Namespace for OperationDefinition helper types.
76
+ */
77
+ export declare namespace Definition {
78
+ export interface Variance<I, O, S> {
79
+ [DefinitionTypeId]: {
80
+ readonly _Input: Types.Contravariant<I>;
81
+ readonly _Output: Types.Covariant<O>;
82
+ readonly _Services: Types.Covariant<S>;
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Any operation definition, regardless of input/output types.
88
+ */
89
+ export type Any = Definition<any, any, any>;
90
+
91
+ /**
92
+ * Extract the input type from an operation definition.
93
+ */
94
+ export type Input<T extends Any> = T extends Variance<infer I, infer _O, infer _S> ? I : never;
95
+
96
+ /**
97
+ * Extract the output type from an operation definition.
98
+ */
99
+ export type Output<T extends Any> = T extends Variance<infer _I, infer O, infer _S> ? O : never;
100
+
101
+ /**
102
+ * Extract the service identifier types from an operation's services array.
103
+ * Returns `never` if the operation has no services declared.
104
+ */
105
+ export type Services<T extends Any> = T extends Variance<infer _I, infer _O, infer S> ? S : never;
106
+
107
+ export type HandlerType<T extends Any> =
108
+ T extends Variance<infer I, infer O, infer S> ? Handler<I, O, any, S> : never;
109
+ }
110
+
111
+ /**
112
+ * Runtime handler for an Operation.
113
+ */
114
+ export type Handler<I, O, E = Error, R = never> = (input: I) => Effect.Effect<O, E, R>;
115
+
116
+ export type WithHandler<T extends Definition.Any> = T & {
117
+ handler: Definition.HandlerType<T>;
118
+ };
119
+
120
+ /**
121
+ * Checks if a value is an operation definition.
122
+ */
123
+ export const isOperationDefinition = (value: unknown): value is Definition.Any => {
124
+ return typeof value === 'object' && value !== null && DefinitionTypeId in value;
125
+ };
126
+
127
+ /**
128
+ * Checks if a value is an operation with a handler.
129
+ */
130
+ export const isOperationWithHandler = (value: unknown): value is WithHandler<Definition.Any> => {
131
+ return isOperationDefinition(value) && 'handler' in value;
132
+ };
133
+
134
+ /**a
135
+ * Props for creating an Operation definition.
136
+ * Derived from OperationDefinition with executionMode made optional (defaults to 'async').
137
+ */
138
+ export type Props<I, O> = Omit<Definition<I, O>, DefinitionTypeId | 'pipe' | 'executionMode' | 'types' | 'services'> & {
139
+ readonly executionMode?: 'sync' | 'async';
140
+ readonly types?: Definition<I, O>['types'];
141
+ readonly services?: Definition<I, O>['services'];
142
+ };
143
+
144
+ /**
145
+ * Creates a new Operation definition.
146
+ * Applies default executionMode of 'async' if not specified.
147
+ * The returned type preserves the literal types of props (including services).
148
+ */
149
+ export const make = <const P extends Types.NoExcessProperties<Props<any, any>, P>>(
150
+ props: P,
151
+ ): Definition<
152
+ Schema$.Schema.Type<P['input']>,
153
+ Schema$.Schema.Type<P['output']>,
154
+ Context.Tag.Identifier<NonNullable<P['services']>[number]>
155
+ > => {
156
+ return {
157
+ [DefinitionTypeId]: {},
158
+ ...props,
159
+ executionMode: props.executionMode ?? 'async',
160
+ types: props.types ?? [],
161
+ services: props.services ?? [],
162
+ pipe() {
163
+ // eslint-disable-next-line prefer-rest-params
164
+ return Pipeable.pipeArguments(this, arguments);
165
+ },
166
+ } as any;
167
+ };
168
+
169
+ /**
170
+ * Attaches a handler to an Operation definition.
171
+ * The handler may use any services declared in the operation, plus Operation.Service (always available).
172
+ * Dual API: can be called directly or used in a pipe.
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * const MyOp = Operation.make({
177
+ * input: Schema.Void,
178
+ * output: Schema.Void,
179
+ * meta: { key: 'my-op' },
180
+ * services: [DatabaseService],
181
+ * });
182
+ *
183
+ * // Direct call - handler can use DatabaseService
184
+ * const op = Operation.withHandler(MyOp, (input) =>
185
+ * Effect.gen(function* () {
186
+ * const db = yield* DatabaseService;
187
+ * return {};
188
+ * }),
189
+ * );
190
+ *
191
+ * // Piped call
192
+ * const op = MyOp.pipe(Operation.withHandler((input) => Effect.succeed({})));
193
+ * ```
194
+ */
195
+ export const withHandler: {
196
+ <Def extends Definition<any, any>, E = never>(
197
+ handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
198
+ ): (op: Def) => WithHandler<Def>;
199
+ <Def extends Definition<any, any>, E = never>(
200
+ op: Def,
201
+ handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
202
+ ): WithHandler<Def>;
203
+ } = <Def extends Definition<any, any>, E = never>(
204
+ opOrHandler: Def | Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
205
+ handler?: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
206
+ ): WithHandler<Def> => {
207
+ // If called with just handler (piped usage).
208
+ if (handler === undefined) {
209
+ const handlerFn = opOrHandler as Handler<
210
+ Definition.Input<Def>,
211
+ Definition.Output<Def>,
212
+ E,
213
+ Definition.Services<Def> | Service
214
+ >;
215
+ return ((op: Def) => ({
216
+ ...op,
217
+ handler: handlerFn,
218
+ })) as any;
219
+ }
220
+
221
+ // If called with both op and handler (direct usage).
222
+ const op = opOrHandler as Def;
223
+ return {
224
+ ...op,
225
+ handler,
226
+ } as any;
227
+ };
228
+
229
+ /**
230
+ * Helper to make the handler type opaque.
231
+ * Workaround for TypeScript's inability to infer the handler type from the operation definition:
232
+ * ```
233
+ * error TS2742: The inferred type of 'default' cannot be named without a reference.
234
+ * ```
235
+ *
236
+ * Most of the time the exact handler type is not needed.
237
+ *
238
+ * @example
239
+ * ```ts
240
+ * const MyOp = Operation.make({
241
+ * input: Schema.Void,
242
+ * output: Schema.Void,
243
+ * meta: { key: 'my-op' },
244
+ * services: [DatabaseService],
245
+ * });
246
+ *
247
+ * export default MyOp.pipe(
248
+ * Operation.withHandler(
249
+ * Effect.fn(function* (input) {
250
+ * return { result: 'ok' };
251
+ * }),
252
+ * ),
253
+ * Operation.opaqueHandler,
254
+ * );
255
+ * ```
256
+ */
257
+ export const opaqueHandler = <T extends Operation.Definition.Any>(
258
+ handler: Operation.WithHandler<T>,
259
+ ): Operation.WithHandler<Operation.Definition.Any> => handler;
260
+
261
+ //
262
+ // Invocation Interfaces
263
+ //
264
+
265
+ /**
266
+ * Local invocation of an operation.
267
+ */
268
+ export type Invoke = <I, O, E>(op: Definition<I, O>, input: I) => Effect.Effect<O, E>;
269
+
270
+ /**
271
+ * Remote invocation of an operation.
272
+ */
273
+ export type InvokeRemote = <I, O, E>(
274
+ op: Definition<I, O>,
275
+ input: I,
276
+ options?: { timeout?: number },
277
+ ) => Effect.Effect<O, E>;
278
+
279
+ /**
280
+ * Database record of an operation.
281
+ */
282
+ export const PersistentOperation = Schema$.Struct({
283
+ /**
284
+ * Global registry ID.
285
+ * NOTE: The `key` property refers to the original registry entry.
286
+ */
287
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
288
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
289
+ // TODO(dmaretskyi): Make required.
290
+ key: Schema$.optional(Schema$.String).annotations({
291
+ description: 'Unique registration key for the blueprint',
292
+ }),
293
+
294
+ name: Schema$.NonEmptyString,
295
+ version: Schema$.String,
296
+
297
+ description: Schema$.optional(Schema$.String),
298
+
299
+ /**
300
+ * ISO date string of the last deployment.
301
+ */
302
+ updated: Schema$.optional(Schema$.String),
303
+
304
+ // Reference to a source script if it exists within ECHO.
305
+ // TODO(burdon): Don't ref ScriptType directly (core).
306
+ source: Schema$.optional(Ref.Ref(Obj.Unknown)),
307
+
308
+ inputSchema: Schema$.optional(JsonSchema.JsonSchema),
309
+ outputSchema: Schema$.optional(JsonSchema.JsonSchema),
310
+
311
+ /**
312
+ * List of required services.
313
+ * Match the Context.Tag keys of the FunctionServices variants.
314
+ */
315
+ services: Schema$.optional(Schema$.Array(Schema$.String)),
316
+
317
+ // Local binding to a function name.
318
+ // TODO(dmaretskyi): Add this field to Operation.Definition.
319
+ binding: Schema$.optional(Schema$.String),
320
+ }).pipe(
321
+ // TODO(dmaretskyi): Keep typename as 'org.dxos.type.function' (not 'operation') to maintain
322
+ // backward compatibility with existing data and avoid requiring data migration.
323
+ Type.object({
324
+ typename: 'org.dxos.type.function',
325
+ version: '0.1.0',
326
+ }),
327
+ Annotation.LabelAnnotation.set(['name']),
328
+ Annotation.IconAnnotation.set({ icon: 'ph--function--regular', hue: 'blue' }),
329
+ Annotation.SystemTypeAnnotation.set(true),
330
+ );
331
+ export interface PersistentOperation extends Schema$.Schema.Type<typeof PersistentOperation> {}
332
+
333
+ /**
334
+ * Serialize an operation definition to a persistent operation record.
335
+ */
336
+ export const serialize = (operation: Definition.Any): PersistentOperation => {
337
+ return Obj.make(PersistentOperation, {
338
+ key: operation.meta.key,
339
+ name: operation.meta.name ?? '',
340
+ version: operation.meta.version ?? '0.0.0',
341
+ description: operation.meta.description,
342
+ updated: undefined,
343
+ source: undefined,
344
+ inputSchema: JsonSchema.toJsonSchema(operation.input),
345
+ outputSchema: JsonSchema.toJsonSchema(operation.output),
346
+ services: operation.services.map((service) => service.key),
347
+ });
348
+ };
349
+
350
+ /**
351
+ * Deserialize a persistent operation record to an operation definition.
352
+ */
353
+ export const deserialize = (record: PersistentOperation): Definition.Any => {
354
+ // Extract deployed function ID from ECHO meta keys (matches FUNCTIONS_META_KEY in @dxos/functions).
355
+ const deployedId = Obj.getMeta(record).keys.find((key) => key.source === 'org.dxos.service.function')?.id;
356
+ return make({
357
+ input: record.inputSchema ? JsonSchema.toEffectSchema(record.inputSchema) : Schema$.Unknown,
358
+ output: record.outputSchema ? JsonSchema.toEffectSchema(record.outputSchema) : Schema$.Unknown,
359
+ services: record.services?.map((service) => Context.GenericTag(service)) ?? [],
360
+ executionMode: 'async',
361
+ types: [],
362
+ meta: {
363
+ key: record.key ?? record.name,
364
+ name: record.name,
365
+ version: record.version,
366
+ description: record.description,
367
+ deployedId,
368
+ },
369
+ });
370
+ };
371
+
372
+ /**
373
+ * Update properties on the target operation record from the source operation record.
374
+ */
375
+ export const setFrom = (target: PersistentOperation, source: PersistentOperation) => {
376
+ Obj.update(target, (target) => {
377
+ target.key = source.key ?? target.key;
378
+ target.name = source.name ?? target.name;
379
+ target.version = source.version;
380
+ target.description = source.description;
381
+ target.updated = source.updated;
382
+ // TODO(dmaretskyi): A workaround for an ECHO bug.
383
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;
384
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;
385
+ Obj.getMeta(target).keys = JSON.parse(JSON.stringify(Obj.getMeta(source).keys));
386
+ });
387
+ };
388
+
389
+ /**
390
+ * Options for operation invocation.
391
+ */
392
+ export interface InvokeOptions {
393
+ /**
394
+ * Space ID to provide database context for the handler.
395
+ */
396
+ spaceId?: Key.SpaceId;
397
+ /**
398
+ * DXN string of the conversation feed (queue).
399
+ * Passed to the process environment so nested operations can resolve AiContextService and related services.
400
+ */
401
+ conversation?: DXN.String;
402
+ /**
403
+ * Optional process-runtime tracing metadata (consumed by `@dxos/functions-runtime` when wired).
404
+ */
405
+ tracing?: unknown;
406
+ }
407
+
408
+ /**
409
+ * Operation service interface - provides unified access to operation invocation and scheduling.
410
+ * This service is automatically provided to operation handlers.
411
+ */
412
+ export interface OperationService {
413
+ /**
414
+ * Invoke an operation as an Effect.
415
+ * Returns an Effect that resolves to the operation output.
416
+ */
417
+ invoke: <I, O>(
418
+ op: Operation.Definition<I, O>,
419
+ ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]
420
+ ) => Effect.Effect<O, NoHandlerError>;
421
+
422
+ /**
423
+ * Schedule an operation to run as a followup.
424
+ * The followup is tracked and won't be cancelled when the parent operation completes.
425
+ * Returns an Effect that completes immediately after scheduling.
426
+ */
427
+ schedule: <I, O>(
428
+ op: Operation.Definition<I, O>,
429
+ ...args: void extends I ? [input?: I] : [input: I]
430
+ ) => Effect.Effect<void>;
431
+
432
+ /**
433
+ * Invoke an operation and return a Promise.
434
+ * Useful for async contexts where Effect is not available.
435
+ */
436
+ invokePromise: <I, O>(
437
+ op: Operation.Definition<I, O>,
438
+ ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]
439
+ ) => Promise<{ data?: O; error?: Error }>;
440
+ }
441
+
442
+ /**
443
+ * Context tag for the Operation service.
444
+ * Operation handlers can yield this to invoke other operations or schedule followups.
445
+ *
446
+ * @example
447
+ * ```ts
448
+ * const handler = (input) => Effect.gen(function* () {
449
+ * // Schedule a followup (fire and forget)
450
+ * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });
451
+ *
452
+ * // Invoke another operation
453
+ * return yield* Operation.invoke(OtherOperation, { data: input.data });
454
+ * });
455
+ * ```
456
+ */
457
+ // TODO(dmaretskyi): Rename Operation.Invoker
458
+ export class Service extends Context.Tag('@dxos/operation/Service')<Service, OperationService>() {}
459
+
460
+ //
461
+ // Namespace functions - ergonomic access to Operation.Service methods.
462
+ //
463
+
464
+ /**
465
+ * Invoke an operation as an Effect.
466
+ * Yields the Operation.Service internally.
467
+ *
468
+ * @example
469
+ * ```ts
470
+ * yield* Operation.invoke(MyOperation, { data: 'test' });
471
+ * ```
472
+ */
473
+ export const invoke = <I, O>(
474
+ op: Operation.Definition<I, O>,
475
+ ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]
476
+ ): Effect.Effect<O, NoHandlerError, Service> =>
477
+ Effect.flatMap(Service, (ops) => ops.invoke(op, ...(args as [I, InvokeOptions?]))).pipe(
478
+ Effect.withSpan('Operation.invoke'),
479
+ );
480
+
481
+ /**
482
+ * Schedule an operation to run as a followup.
483
+ * Yields the Operation.Service internally.
484
+ *
485
+ * @example
486
+ * ```ts
487
+ * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });
488
+ * yield* Operation.schedule(VoidOperation); // input optional when void
489
+ * ```
490
+ */
491
+ export const schedule = <I, O>(
492
+ op: Operation.Definition<I, O>,
493
+ ...args: void extends I ? [input?: I] : [input: I]
494
+ ): Effect.Effect<void, never, Service> =>
495
+ Effect.flatMap(Service, (ops) => ops.schedule(op, args[0] as I)).pipe(Effect.withSpan('Operation.schedule'));
496
+
497
+ /**
498
+ * Provides additional invocation options to all invocations.
499
+ */
500
+ export const withInvocationOptions = (options: InvokeOptions): Layer.Layer<Service, never, Service> =>
501
+ Layer.effect(
502
+ Service,
503
+ Effect.gen(function* () {
504
+ const service = yield* Service;
505
+ return Service.of({
506
+ invoke: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>
507
+ service.invoke(op, input, { ...options, ...invocationOptions })) as any,
508
+ invokePromise: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>
509
+ service.invokePromise(op, input, { ...options, ...invocationOptions })) as any,
510
+ schedule: service.schedule,
511
+ });
512
+ }),
513
+ );
@@ -0,0 +1,132 @@
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 Layer from 'effect/Layer';
8
+
9
+ import { assertArgument } from '@dxos/invariant';
10
+
11
+ import { NoHandlerError } from './errors';
12
+ import type * as Operation from './Operation';
13
+
14
+ export const TypeId = '~@dxos/operation/OperationHandlerSet' as const;
15
+ export type TypeId = typeof TypeId;
16
+
17
+ export interface OperationHandlerSet {
18
+ [TypeId]: TypeId;
19
+
20
+ readonly handlers: Effect.Effect<Operation.WithHandler<Operation.Definition.Any>[]>;
21
+
22
+ getHandlers(): Promise<Operation.WithHandler<Operation.Definition.Any>[]>;
23
+ }
24
+
25
+ export const isOperationHandlerSet = (value: unknown): value is OperationHandlerSet => {
26
+ return typeof value === 'object' && value !== null && TypeId in value;
27
+ };
28
+
29
+ export const empty: OperationHandlerSet = {
30
+ [TypeId]: TypeId,
31
+ handlers: Effect.succeed([]),
32
+ getHandlers: () => Promise.resolve([]),
33
+ };
34
+
35
+ /**
36
+ * Creates a new operation handler set from a list of handlers.
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * const set = OperationHandlerSet.make(
41
+ * Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.Void }), (input) => Effect.succeed({})),
42
+ * Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.Void }), (input) => Effect.succeed({})),
43
+ * );
44
+ * ```
45
+ */
46
+ export const make = (...handlers: Operation.WithHandler<Operation.Definition.Any>[]): OperationHandlerSet => {
47
+ return async(() => Promise.resolve(handlers));
48
+ };
49
+
50
+ export const async = (
51
+ getHandlers: () => Promise<Operation.WithHandler<Operation.Definition.Any>[]>,
52
+ ): OperationHandlerSet => {
53
+ // NOTE: Re-runing async module imports has a big performance penalty in Chrome.
54
+ let promise: Promise<Operation.WithHandler<Operation.Definition.Any>[]> | null = null;
55
+ const getHandlersCached = () => {
56
+ if (!promise) {
57
+ promise = getHandlers();
58
+ }
59
+ return promise;
60
+ };
61
+ return {
62
+ [TypeId]: TypeId,
63
+ getHandlers,
64
+ handlers: Effect.promise(getHandlersCached),
65
+ };
66
+ };
67
+
68
+ /**
69
+ * Merges multiple operation handler sets into a single set.
70
+ *
71
+ */
72
+ export const merge = (...sets: OperationHandlerSet[]): OperationHandlerSet => {
73
+ assertArgument(sets.every(isOperationHandlerSet), 'sets', 'sets must be an array of OperationHandlerSet');
74
+ return async(() => Promise.all(sets.map((set) => set.getHandlers())).then((handlers) => handlers.flat()));
75
+ };
76
+
77
+ /**
78
+ * Creates a new operation handler set from a list of lazy-loaded modules.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const set = OperationHandlerSet.lazy(
83
+ * () => import('./my-handler'),
84
+ * () => import('./my-other-handler'),
85
+ * );
86
+ * ```
87
+ */
88
+ export const lazy = (
89
+ ...modules: (() => Promise<{ default: Operation.WithHandler<Operation.Definition.Any> }>)[]
90
+ ): OperationHandlerSet => {
91
+ return async(() => Promise.all(modules.map((module) => module().then(({ default: handler }) => handler))));
92
+ };
93
+
94
+ /**
95
+ * Gets a handler for an operation by definition.
96
+ */
97
+ export const getHandler = <const Op extends Operation.Definition.Any>(
98
+ set: OperationHandlerSet,
99
+ definition: Op,
100
+ ): Effect.Effect<Operation.WithHandler<Op>, NoHandlerError> =>
101
+ Effect.gen(function* () {
102
+ const handlers = yield* set.handlers;
103
+ const handler = handlers.find((handler) => handler.meta.key === definition.meta.key);
104
+ if (!handler) {
105
+ return yield* Effect.fail(new NoHandlerError(definition.meta.key));
106
+ }
107
+ return handler as any;
108
+ });
109
+
110
+ /**
111
+ * Gets a handler for an operation by key.
112
+ */
113
+ export const getHandlerByKey = (
114
+ set: OperationHandlerSet,
115
+ key: string,
116
+ ): Effect.Effect<Operation.WithHandler<Operation.Definition.Any>, NoHandlerError> =>
117
+ Effect.gen(function* () {
118
+ const handlers = yield* set.handlers;
119
+ const handler = handlers.find((handler) => handler.meta.key === key);
120
+ if (!handler) {
121
+ return yield* Effect.fail(new NoHandlerError(key));
122
+ }
123
+ return handler as any;
124
+ });
125
+
126
+ export class OperationHandlerProvider extends Context.Tag('@dxos/operation/OperationHandlerProvider')<
127
+ OperationHandlerProvider,
128
+ OperationHandlerSet
129
+ >() {}
130
+
131
+ export const provide = (handlers: OperationHandlerSet): Layer.Layer<OperationHandlerProvider, never, never> =>
132
+ Layer.succeed(OperationHandlerProvider, handlers);
@@ -0,0 +1,48 @@
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 Layer from 'effect/Layer';
8
+ import * as Option from 'effect/Option';
9
+
10
+ import { Database, Query } from '@dxos/echo';
11
+
12
+ import * as Operation from './Operation';
13
+ import * as OperationHandlerSet from './OperationHandlerSet';
14
+
15
+ export interface OperationRegistry {
16
+ /**
17
+ * Resolve an operation by key.
18
+ */
19
+ resolve(key: string): Effect.Effect<Option.Option<Operation.Definition.Any>>;
20
+ }
21
+
22
+ export class Service extends Context.Tag('@dxos/operation/OperationRegistry')<Service, OperationRegistry>() {}
23
+
24
+ /**
25
+ * Resolve an operation by key.
26
+ */
27
+ export const resolve: (key: string) => Effect.Effect<Option.Option<Operation.Definition.Any>, never, Service> =
28
+ Effect.serviceFunctionEffect(Service, (service) => service.resolve);
29
+
30
+ export const layer: Layer.Layer<Service, never, Database.Service | OperationHandlerSet.OperationHandlerProvider> =
31
+ Layer.effect(
32
+ Service,
33
+ Effect.gen(function* () {
34
+ const database = yield* Database.Service;
35
+ const handlerSet = yield* OperationHandlerSet.OperationHandlerProvider;
36
+ return {
37
+ resolve: (key: string) =>
38
+ Database.runQueryFirst(Query.type(Operation.PersistentOperation, { key }))
39
+ .pipe(
40
+ Effect.flatten,
41
+ Effect.map(Operation.deserialize),
42
+ Effect.catchTag('NoSuchElementException', () => OperationHandlerSet.getHandlerByKey(handlerSet, key)),
43
+ Effect.option,
44
+ )
45
+ .pipe(Effect.provideService(Database.Service, database)),
46
+ };
47
+ }),
48
+ );