@dxos/compute 0.8.4-main.ead640a → 0.8.4-main.f466a3d56e

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 (180) hide show
  1. package/LICENSE +102 -5
  2. package/README.md +36 -1
  3. package/dist/lib/neutral/StorageService.mjs +22 -0
  4. package/dist/lib/neutral/chunk-AKVCVI6N.mjs +25 -0
  5. package/dist/lib/neutral/chunk-AKVCVI6N.mjs.map +7 -0
  6. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  7. package/dist/lib/neutral/chunk-LF2ANNYW.mjs +171 -0
  8. package/dist/lib/neutral/chunk-LF2ANNYW.mjs.map +7 -0
  9. package/dist/lib/neutral/chunk-LRCABAWU.mjs +17 -0
  10. package/dist/lib/neutral/chunk-LRCABAWU.mjs.map +7 -0
  11. package/dist/lib/neutral/chunk-RCLYF66G.mjs +21 -0
  12. package/dist/lib/neutral/chunk-RCLYF66G.mjs.map +7 -0
  13. package/dist/lib/neutral/chunk-SEBWOTOU.mjs +235 -0
  14. package/dist/lib/neutral/chunk-SEBWOTOU.mjs.map +7 -0
  15. package/dist/lib/neutral/chunk-VSICPGGY.mjs +53 -0
  16. package/dist/lib/neutral/chunk-VSICPGGY.mjs.map +7 -0
  17. package/dist/lib/neutral/chunk-XEVFBI6S.mjs +62 -0
  18. package/dist/lib/neutral/chunk-XEVFBI6S.mjs.map +7 -0
  19. package/dist/lib/neutral/fib-ZSJYREBW.mjs +10 -0
  20. package/dist/lib/neutral/fib-ZSJYREBW.mjs.map +7 -0
  21. package/dist/lib/neutral/index.mjs +1225 -0
  22. package/dist/lib/neutral/index.mjs.map +7 -0
  23. package/dist/lib/neutral/meta.json +1 -0
  24. package/dist/lib/neutral/reply-YH3BVOUT.mjs +10 -0
  25. package/dist/lib/neutral/reply-YH3BVOUT.mjs.map +7 -0
  26. package/dist/lib/neutral/sleep-TSPIQ5EY.mjs +10 -0
  27. package/dist/lib/neutral/sleep-TSPIQ5EY.mjs.map +7 -0
  28. package/dist/lib/neutral/testing/index.mjs +32 -0
  29. package/dist/lib/neutral/testing/index.mjs.map +7 -0
  30. package/dist/types/src/Blueprint.d.ts +192 -0
  31. package/dist/types/src/Blueprint.d.ts.map +1 -0
  32. package/dist/types/src/Credential.d.ts +27 -0
  33. package/dist/types/src/Credential.d.ts.map +1 -0
  34. package/dist/types/src/LayerSpec.d.ts +56 -0
  35. package/dist/types/src/LayerSpec.d.ts.map +1 -0
  36. package/dist/types/src/McpServer.d.ts +27 -0
  37. package/dist/types/src/McpServer.d.ts.map +1 -0
  38. package/dist/types/src/Operation.d.ts +340 -0
  39. package/dist/types/src/Operation.d.ts.map +1 -0
  40. package/dist/types/src/OperationHandlerSet.d.ts +67 -0
  41. package/dist/types/src/OperationHandlerSet.d.ts.map +1 -0
  42. package/dist/types/src/OperationHandlerSet.test.d.ts +2 -0
  43. package/dist/types/src/OperationHandlerSet.test.d.ts.map +1 -0
  44. package/dist/types/src/OperationRegistry.d.ts +23 -0
  45. package/dist/types/src/OperationRegistry.d.ts.map +1 -0
  46. package/dist/types/src/Process.d.ts +247 -0
  47. package/dist/types/src/Process.d.ts.map +1 -0
  48. package/dist/types/src/Routine.d.ts +63 -0
  49. package/dist/types/src/Routine.d.ts.map +1 -0
  50. package/dist/types/src/Script.d.ts +22 -0
  51. package/dist/types/src/Script.d.ts.map +1 -0
  52. package/dist/types/src/ServiceResolver.d.ts +89 -0
  53. package/dist/types/src/ServiceResolver.d.ts.map +1 -0
  54. package/dist/types/src/StorageService.d.ts +58 -0
  55. package/dist/types/src/StorageService.d.ts.map +1 -0
  56. package/dist/types/src/Template.d.ts +62 -0
  57. package/dist/types/src/Template.d.ts.map +1 -0
  58. package/dist/types/src/Template.test.d.ts +2 -0
  59. package/dist/types/src/Template.test.d.ts.map +1 -0
  60. package/dist/types/src/Trace.d.ts +268 -0
  61. package/dist/types/src/Trace.d.ts.map +1 -0
  62. package/dist/types/src/Trigger.d.ts +150 -0
  63. package/dist/types/src/Trigger.d.ts.map +1 -0
  64. package/dist/types/src/TriggerEvent.d.ts +75 -0
  65. package/dist/types/src/TriggerEvent.d.ts.map +1 -0
  66. package/dist/types/src/errors.d.ts +308 -0
  67. package/dist/types/src/errors.d.ts.map +1 -0
  68. package/dist/types/src/index.d.ts +17 -5
  69. package/dist/types/src/index.d.ts.map +1 -1
  70. package/dist/types/src/testing/definitions.d.ts +11 -0
  71. package/dist/types/src/testing/definitions.d.ts.map +1 -0
  72. package/dist/types/src/testing/fib.d.ts +8 -0
  73. package/dist/types/src/testing/fib.d.ts.map +1 -0
  74. package/dist/types/src/testing/index.d.ts +6 -4
  75. package/dist/types/src/testing/index.d.ts.map +1 -1
  76. package/dist/types/src/testing/reply.d.ts +4 -0
  77. package/dist/types/src/testing/reply.d.ts.map +1 -0
  78. package/dist/types/src/testing/sleep.d.ts +6 -0
  79. package/dist/types/src/testing/sleep.d.ts.map +1 -0
  80. package/dist/types/src/umbrella.test.d.ts +2 -0
  81. package/dist/types/src/umbrella.test.d.ts.map +1 -0
  82. package/dist/types/tsconfig.tsbuildinfo +1 -1
  83. package/package.json +29 -40
  84. package/src/Blueprint.ts +303 -0
  85. package/src/Credential.ts +53 -0
  86. package/src/LayerSpec.ts +91 -0
  87. package/src/McpServer.ts +44 -0
  88. package/src/Operation.ts +593 -0
  89. package/src/OperationHandlerSet.test.ts +92 -0
  90. package/src/OperationHandlerSet.ts +174 -0
  91. package/src/OperationRegistry.ts +50 -0
  92. package/src/Process.ts +504 -0
  93. package/src/Routine.ts +75 -0
  94. package/src/Script.ts +40 -0
  95. package/src/ServiceResolver.ts +194 -0
  96. package/src/StorageService.ts +101 -0
  97. package/src/Template.test.ts +151 -0
  98. package/src/Template.ts +122 -0
  99. package/src/Trace.ts +368 -0
  100. package/src/Trigger.ts +209 -0
  101. package/src/TriggerEvent.ts +64 -0
  102. package/src/errors.ts +71 -0
  103. package/src/index.ts +18 -32
  104. package/src/testing/definitions.ts +49 -0
  105. package/src/testing/fib.ts +22 -0
  106. package/src/testing/index.ts +13 -5
  107. package/src/testing/reply.ts +18 -0
  108. package/src/testing/sleep.ts +16 -0
  109. package/src/umbrella.test.ts +51 -0
  110. package/dist/lib/browser/chunk-C7KLV2IU.mjs +0 -3144
  111. package/dist/lib/browser/chunk-C7KLV2IU.mjs.map +0 -7
  112. package/dist/lib/browser/index.mjs +0 -55
  113. package/dist/lib/browser/meta.json +0 -1
  114. package/dist/lib/browser/testing/index.mjs +0 -206
  115. package/dist/lib/browser/testing/index.mjs.map +0 -7
  116. package/dist/lib/node-esm/chunk-K37OSZ5O.mjs +0 -3146
  117. package/dist/lib/node-esm/chunk-K37OSZ5O.mjs.map +0 -7
  118. package/dist/lib/node-esm/index.mjs +0 -56
  119. package/dist/lib/node-esm/meta.json +0 -1
  120. package/dist/lib/node-esm/testing/index.mjs +0 -207
  121. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  122. package/dist/types/src/compute-graph-registry.d.ts +0 -37
  123. package/dist/types/src/compute-graph-registry.d.ts.map +0 -1
  124. package/dist/types/src/compute-graph-registry.test.d.ts +0 -2
  125. package/dist/types/src/compute-graph-registry.test.d.ts.map +0 -1
  126. package/dist/types/src/compute-graph.d.ts +0 -67
  127. package/dist/types/src/compute-graph.d.ts.map +0 -1
  128. package/dist/types/src/compute-graph.test.d.ts +0 -2
  129. package/dist/types/src/compute-graph.test.d.ts.map +0 -1
  130. package/dist/types/src/compute-node.d.ts +0 -24
  131. package/dist/types/src/compute-node.d.ts.map +0 -1
  132. package/dist/types/src/functions/async-function.d.ts +0 -68
  133. package/dist/types/src/functions/async-function.d.ts.map +0 -1
  134. package/dist/types/src/functions/edge-function.d.ts +0 -20
  135. package/dist/types/src/functions/edge-function.d.ts.map +0 -1
  136. package/dist/types/src/functions/function-defs.d.ts +0 -11
  137. package/dist/types/src/functions/function-defs.d.ts.map +0 -1
  138. package/dist/types/src/functions/index.d.ts +0 -4
  139. package/dist/types/src/functions/index.d.ts.map +0 -1
  140. package/dist/types/src/hyperformula.test.d.ts +0 -2
  141. package/dist/types/src/hyperformula.test.d.ts.map +0 -1
  142. package/dist/types/src/testing/test-builder.d.ts +0 -15
  143. package/dist/types/src/testing/test-builder.d.ts.map +0 -1
  144. package/dist/types/src/testing/test-plugin.d.ts +0 -35
  145. package/dist/types/src/testing/test-plugin.d.ts.map +0 -1
  146. package/dist/types/src/testing/test-runtime.d.ts +0 -10
  147. package/dist/types/src/testing/test-runtime.d.ts.map +0 -1
  148. package/dist/types/src/testing/util.d.ts +0 -2
  149. package/dist/types/src/testing/util.d.ts.map +0 -1
  150. package/dist/types/src/types/hyperformula.d.ts +0 -8
  151. package/dist/types/src/types/hyperformula.d.ts.map +0 -1
  152. package/dist/types/src/types/index.d.ts +0 -3
  153. package/dist/types/src/types/index.d.ts.map +0 -1
  154. package/dist/types/src/types/types.d.ts +0 -20
  155. package/dist/types/src/types/types.d.ts.map +0 -1
  156. package/dist/types/src/types/types.test.d.ts +0 -2
  157. package/dist/types/src/types/types.test.d.ts.map +0 -1
  158. package/dist/types/src/util.d.ts +0 -2
  159. package/dist/types/src/util.d.ts.map +0 -1
  160. package/src/compute-graph-registry.test.ts +0 -138
  161. package/src/compute-graph-registry.ts +0 -97
  162. package/src/compute-graph.test.ts +0 -88
  163. package/src/compute-graph.ts +0 -261
  164. package/src/compute-node.ts +0 -59
  165. package/src/functions/async-function.ts +0 -184
  166. package/src/functions/edge-function.ts +0 -114
  167. package/src/functions/function-defs.ts +0 -2427
  168. package/src/functions/index.ts +0 -7
  169. package/src/hyperformula.test.ts +0 -14
  170. package/src/testing/test-builder.ts +0 -60
  171. package/src/testing/test-plugin.ts +0 -98
  172. package/src/testing/test-runtime.ts +0 -38
  173. package/src/testing/util.ts +0 -9
  174. package/src/types/hyperformula.ts +0 -19
  175. package/src/types/index.ts +0 -6
  176. package/src/types/types.test.ts +0 -91
  177. package/src/types/types.ts +0 -80
  178. package/src/util.ts +0 -8
  179. /package/dist/lib/{browser/index.mjs.map → neutral/StorageService.mjs.map} +0 -0
  180. /package/dist/lib/{node-esm/index.mjs.map → neutral/chunk-J5LGTIGS.mjs.map} +0 -0
@@ -0,0 +1,593 @@
1
+ //
2
+ // Copyright 2025 DXOS.org
3
+ //
4
+
5
+ // @import-as-namespace
6
+
7
+ import * as Context from 'effect/Context';
8
+ import * as Effect from 'effect/Effect';
9
+ import * as Layer from 'effect/Layer';
10
+ import * as Pipeable from 'effect/Pipeable';
11
+ import * as Schema$ from 'effect/Schema';
12
+ import type * as Types from 'effect/Types';
13
+
14
+ import { Annotation, JsonSchema, Migration, Obj, Ref, Type, type DXN, type Key } from '@dxos/echo';
15
+
16
+ import type { NoHandlerError } from './errors';
17
+ import type { Operation } from './index';
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
+ * Marks an operation as intrinsic — provided directly by the DXOS platform runtime rather than
171
+ * deployed as a user function. The `intrinsic:<key>` deployedId routes invocations to the
172
+ * built-in implementation registered with the runtime.
173
+ */
174
+ export const intrinsic = <const O extends Operation.Definition.Any>(op: O): O => {
175
+ return {
176
+ ...op,
177
+ meta: {
178
+ ...op.meta,
179
+ deployedId: `intrinsic:${op.meta.key}`,
180
+ },
181
+ };
182
+ };
183
+
184
+ /**
185
+ * Attaches a handler to an Operation definition.
186
+ * The handler may use any services declared in the operation, plus Operation.Service (always available).
187
+ * Dual API: can be called directly or used in a pipe.
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * const MyOp = Operation.make({
192
+ * input: Schema.Void,
193
+ * output: Schema.Void,
194
+ * meta: { key: 'my-op' },
195
+ * services: [DatabaseService],
196
+ * });
197
+ *
198
+ * // Direct call - handler can use DatabaseService
199
+ * const op = Operation.withHandler(MyOp, (input) =>
200
+ * Effect.gen(function* () {
201
+ * const db = yield* DatabaseService;
202
+ * return {};
203
+ * }),
204
+ * );
205
+ *
206
+ * // Piped call
207
+ * const op = MyOp.pipe(Operation.withHandler((input) => Effect.succeed({})));
208
+ * ```
209
+ */
210
+ export const withHandler: {
211
+ <Def extends Definition<any, any>, E = never>(
212
+ handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
213
+ ): (op: Def) => WithHandler<Def>;
214
+ <Def extends Definition<any, any>, E = never>(
215
+ op: Def,
216
+ handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
217
+ ): WithHandler<Def>;
218
+ } = <Def extends Definition<any, any>, E = never>(
219
+ opOrHandler: Def | Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
220
+ handler?: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,
221
+ ): WithHandler<Def> => {
222
+ // If called with just handler (piped usage).
223
+ if (handler === undefined) {
224
+ const handlerFn = opOrHandler as Handler<
225
+ Definition.Input<Def>,
226
+ Definition.Output<Def>,
227
+ E,
228
+ Definition.Services<Def> | Service
229
+ >;
230
+ return ((op: Def) => ({
231
+ ...op,
232
+ handler: handlerFn,
233
+ })) as any;
234
+ }
235
+
236
+ // If called with both op and handler (direct usage).
237
+ const op = opOrHandler as Def;
238
+ return {
239
+ ...op,
240
+ handler,
241
+ } as any;
242
+ };
243
+
244
+ /**
245
+ * Helper to make the handler type opaque.
246
+ * Workaround for TypeScript's inability to infer the handler type from the operation definition:
247
+ * ```
248
+ * error TS2742: The inferred type of 'default' cannot be named without a reference.
249
+ * ```
250
+ *
251
+ * Most of the time the exact handler type is not needed.
252
+ *
253
+ * @example
254
+ * ```ts
255
+ * const MyOp = Operation.make({
256
+ * input: Schema.Void,
257
+ * output: Schema.Void,
258
+ * meta: { key: 'my-op' },
259
+ * services: [DatabaseService],
260
+ * });
261
+ *
262
+ * export default MyOp.pipe(
263
+ * Operation.withHandler(
264
+ * Effect.fn(function* (input) {
265
+ * return { result: 'ok' };
266
+ * }),
267
+ * ),
268
+ * Operation.opaqueHandler,
269
+ * );
270
+ * ```
271
+ */
272
+ export const opaqueHandler = <T extends Operation.Definition.Any>(
273
+ handler: Operation.WithHandler<T>,
274
+ ): Operation.WithHandler<Operation.Definition.Any> => handler;
275
+
276
+ //
277
+ // Invocation Interfaces
278
+ //
279
+
280
+ /**
281
+ * Local invocation of an operation.
282
+ */
283
+ export type Invoke = <I, O, E>(op: Definition<I, O>, input: I) => Effect.Effect<O, E>;
284
+
285
+ /**
286
+ * Remote invocation of an operation.
287
+ */
288
+ export type InvokeRemote = <I, O, E>(
289
+ op: Definition<I, O>,
290
+ input: I,
291
+ options?: { timeout?: number },
292
+ ) => Effect.Effect<O, E>;
293
+
294
+ /**
295
+ * Database record of an operation.
296
+ * The registry `key` and `version` live in the object meta — access via
297
+ * `Obj.getMeta(record).key` and `Obj.getMeta(record).version`.
298
+ */
299
+ export const PersistentOperation = Schema$.Struct({
300
+ name: Schema$.NonEmptyString,
301
+
302
+ description: Schema$.optional(Schema$.String),
303
+
304
+ /**
305
+ * ISO date string of the last deployment.
306
+ */
307
+ updated: Schema$.optional(Schema$.String),
308
+
309
+ // Reference to a source script if it exists within ECHO.
310
+ // TODO(burdon): Don't ref ScriptType directly (core).
311
+ source: Schema$.optional(Ref.Ref(Obj.Unknown)),
312
+
313
+ inputSchema: Schema$.optional(JsonSchema.JsonSchema),
314
+ outputSchema: Schema$.optional(JsonSchema.JsonSchema),
315
+
316
+ /**
317
+ * List of required services.
318
+ * Match the Context.Tag keys of the FunctionServices variants.
319
+ */
320
+ services: Schema$.optional(Schema$.Array(Schema$.String)),
321
+
322
+ // Local binding to a function name.
323
+ // TODO(dmaretskyi): Add this field to Operation.Definition.
324
+ binding: Schema$.optional(Schema$.String),
325
+ }).pipe(
326
+ // TODO(dmaretskyi): Keep typename as 'org.dxos.type.function' (not 'operation') to maintain
327
+ // backward compatibility with existing data and avoid requiring data migration.
328
+ Type.object({
329
+ typename: 'org.dxos.type.function',
330
+ version: '0.2.0',
331
+ }),
332
+ Annotation.LabelAnnotation.set(['name']),
333
+ Annotation.IconAnnotation.set({ icon: 'ph--function--regular', hue: 'blue' }),
334
+ Annotation.SystemTypeAnnotation.set(true),
335
+ );
336
+ export interface PersistentOperation extends Schema$.Schema.Type<typeof PersistentOperation> {}
337
+
338
+ const FUNCTION_META_KEY = 'org.dxos.service.function';
339
+
340
+ /**
341
+ * Get the registry key for a persistent operation record (from the object meta).
342
+ */
343
+ export const getKey = (record: PersistentOperation): string | undefined => Obj.getMeta(record).key;
344
+
345
+ /**
346
+ * Get the registry version for a persistent operation record (from the object meta).
347
+ */
348
+ export const getVersion = (record: PersistentOperation): string | undefined => Obj.getMeta(record).version;
349
+
350
+ /**
351
+ * Serialize an operation definition to a persistent operation record.
352
+ */
353
+ export const serialize = (operation: Definition.Any): PersistentOperation => {
354
+ return Obj.make(PersistentOperation, {
355
+ [Obj.Meta]: {
356
+ key: operation.meta.key,
357
+ version: operation.meta.version ?? '0.0.0',
358
+ keys: operation.meta.deployedId ? [{ source: FUNCTION_META_KEY, id: operation.meta.deployedId }] : [],
359
+ },
360
+ name: operation.meta.name ?? '',
361
+ description: operation.meta.description,
362
+ updated: undefined,
363
+ source: undefined,
364
+ inputSchema: JsonSchema.toJsonSchema(operation.input),
365
+ outputSchema: JsonSchema.toJsonSchema(operation.output),
366
+ services: operation.services.map((service) => service.key),
367
+ });
368
+ };
369
+
370
+ /**
371
+ * Deserialize a persistent operation record to an operation definition.
372
+ */
373
+ export const deserialize = (record: PersistentOperation): Definition.Any => {
374
+ const meta = Obj.getMeta(record);
375
+ // Extract deployed function ID from ECHO meta keys (matches FUNCTIONS_META_KEY in @dxos/functions).
376
+ const deployedId = meta.keys.find((key) => key.source === FUNCTION_META_KEY)?.id;
377
+ return make({
378
+ input: record.inputSchema ? JsonSchema.toEffectSchema(record.inputSchema) : Schema$.Unknown,
379
+ output: record.outputSchema ? JsonSchema.toEffectSchema(record.outputSchema) : Schema$.Unknown,
380
+ services: record.services?.map((service) => Context.GenericTag(service)) ?? [],
381
+ executionMode: 'async',
382
+ types: [],
383
+ meta: {
384
+ key: meta.key ?? record.name,
385
+ name: record.name,
386
+ version: meta.version ?? '0.0.0',
387
+ description: record.description,
388
+ deployedId,
389
+ },
390
+ });
391
+ };
392
+
393
+ /**
394
+ * Update properties on the target operation record from the source operation record.
395
+ */
396
+ export const setFrom = (target: PersistentOperation, source: PersistentOperation) => {
397
+ Obj.update(target, (target) => {
398
+ target.name = source.name ?? target.name;
399
+ target.description = source.description;
400
+ target.updated = source.updated;
401
+ // TODO(dmaretskyi): A workaround for an ECHO bug.
402
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;
403
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;
404
+ const sourceMeta = Obj.getMeta(source);
405
+ const targetMeta = Obj.getMeta(target);
406
+ targetMeta.key = sourceMeta.key ?? targetMeta.key;
407
+ targetMeta.version = sourceMeta.version;
408
+ // Only overwrite foreign keys when the source actually carries them; otherwise we'd wipe
409
+ // bindings (e.g. the deployedId set by `deserialize`) on records produced by `serialize`.
410
+ if (sourceMeta.keys.length > 0) {
411
+ targetMeta.keys = JSON.parse(JSON.stringify(sourceMeta.keys));
412
+ }
413
+ });
414
+ };
415
+
416
+ /**
417
+ * Options for operation invocation.
418
+ */
419
+ export interface InvokeOptions {
420
+ /**
421
+ * Space ID to provide database context for the handler.
422
+ */
423
+ spaceId?: Key.SpaceId;
424
+ /**
425
+ * DXN string of the conversation feed (queue).
426
+ * Passed to the process environment so nested operations can resolve AiContext.Service and related services.
427
+ */
428
+ conversation?: DXN.String;
429
+ /**
430
+ * Optional process-runtime tracing metadata (consumed by `@dxos/functions-runtime` when wired).
431
+ */
432
+ tracing?: unknown;
433
+ }
434
+
435
+ /**
436
+ * Operation service interface - provides unified access to operation invocation and scheduling.
437
+ * This service is automatically provided to operation handlers.
438
+ */
439
+ export interface OperationService {
440
+ /**
441
+ * Invoke an operation as an Effect.
442
+ * Returns an Effect that resolves to the operation output.
443
+ */
444
+ invoke: <I, O>(
445
+ op: Operation.Definition<I, O>,
446
+ ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]
447
+ ) => Effect.Effect<O, NoHandlerError>;
448
+
449
+ /**
450
+ * Schedule an operation to run as a followup.
451
+ * The followup is tracked and won't be cancelled when the parent operation completes.
452
+ * Returns an Effect that completes immediately after scheduling.
453
+ */
454
+ schedule: <I, O>(
455
+ op: Operation.Definition<I, O>,
456
+ ...args: void extends I ? [input?: I] : [input: I]
457
+ ) => Effect.Effect<void>;
458
+
459
+ /**
460
+ * Invoke an operation and return a Promise.
461
+ * Useful for async contexts where Effect is not available.
462
+ */
463
+ invokePromise: <I, O>(
464
+ op: Operation.Definition<I, O>,
465
+ ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]
466
+ ) => Promise<{ data?: O; error?: Error }>;
467
+ }
468
+
469
+ /**
470
+ * Context tag for the Operation service.
471
+ * Operation handlers can yield this to invoke other operations or schedule followups.
472
+ *
473
+ * @example
474
+ * ```ts
475
+ * const handler = (input) => Effect.gen(function* () {
476
+ * // Schedule a followup (fire and forget)
477
+ * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });
478
+ *
479
+ * // Invoke another operation
480
+ * return yield* Operation.invoke(OtherOperation, { data: input.data });
481
+ * });
482
+ * ```
483
+ */
484
+ // TODO(dmaretskyi): Rename Operation.Invoker
485
+ export class Service extends Context.Tag('@dxos/operation/Service')<Service, OperationService>() {}
486
+
487
+ //
488
+ // Namespace functions - ergonomic access to Operation.Service methods.
489
+ //
490
+
491
+ /**
492
+ * Invoke an operation as an Effect.
493
+ * Yields the Operation.Service internally.
494
+ *
495
+ * @example
496
+ * ```ts
497
+ * yield* Operation.invoke(MyOperation, { data: 'test' });
498
+ * ```
499
+ */
500
+ export const invoke = <I, O>(
501
+ op: Operation.Definition<I, O>,
502
+ ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]
503
+ ): Effect.Effect<O, NoHandlerError, Service> =>
504
+ Effect.flatMap(Service, (ops) => ops.invoke(op, ...(args as [I, InvokeOptions?]))).pipe(
505
+ Effect.withSpan('Operation.invoke'),
506
+ );
507
+
508
+ /**
509
+ * Schedule an operation to run as a followup.
510
+ * Yields the Operation.Service internally.
511
+ *
512
+ * @example
513
+ * ```ts
514
+ * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });
515
+ * yield* Operation.schedule(VoidOperation); // input optional when void
516
+ * ```
517
+ */
518
+ export const schedule = <I, O>(
519
+ op: Operation.Definition<I, O>,
520
+ ...args: void extends I ? [input?: I] : [input: I]
521
+ ): Effect.Effect<void, never, Service> =>
522
+ Effect.flatMap(Service, (ops) => ops.schedule(op, args[0] as I)).pipe(Effect.withSpan('Operation.schedule'));
523
+
524
+ /**
525
+ * Provides additional invocation options to all invocations.
526
+ */
527
+ export const withInvocationOptions = (options: InvokeOptions): Layer.Layer<Service, never, Service> =>
528
+ Layer.effect(
529
+ Service,
530
+ Effect.gen(function* () {
531
+ const service = yield* Service;
532
+ return Service.of({
533
+ invoke: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>
534
+ service.invoke(op, input, { ...options, ...invocationOptions })) as any,
535
+ invokePromise: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>
536
+ service.invokePromise(op, input, { ...options, ...invocationOptions })) as any,
537
+ schedule: service.schedule,
538
+ });
539
+ }),
540
+ );
541
+
542
+ //
543
+ // Legacy schemas and migrations.
544
+ //
545
+
546
+ /**
547
+ * Persistent operation schema v0.1.0 — `key` and `version` are stored as data properties.
548
+ * @deprecated Use {@link PersistentOperation} (v0.2.0) instead; the `key` and `version` now live in the object meta.
549
+ */
550
+ export const PersistentOperation_v0_1_0 = Schema$.Struct({
551
+ key: Schema$.optional(Schema$.String),
552
+ name: Schema$.NonEmptyString,
553
+ version: Schema$.String,
554
+ description: Schema$.optional(Schema$.String),
555
+ updated: Schema$.optional(Schema$.String),
556
+ source: Schema$.optional(Ref.Ref(Obj.Unknown)),
557
+ inputSchema: Schema$.optional(JsonSchema.JsonSchema),
558
+ outputSchema: Schema$.optional(JsonSchema.JsonSchema),
559
+ services: Schema$.optional(Schema$.Array(Schema$.String)),
560
+ binding: Schema$.optional(Schema$.String),
561
+ }).pipe(
562
+ Type.object({
563
+ typename: 'org.dxos.type.function',
564
+ version: '0.1.0',
565
+ }),
566
+ );
567
+ export interface PersistentOperation_v0_1_0 extends Schema$.Schema.Type<typeof PersistentOperation_v0_1_0> {}
568
+
569
+ /**
570
+ * Migration from {@link PersistentOperation_v0_1_0} (v0.1.0) to {@link PersistentOperation} (v0.2.0).
571
+ * Moves `key` and `version` from the data section into the object meta.
572
+ */
573
+ const _migration = Migration.define({
574
+ from: PersistentOperation_v0_1_0,
575
+ to: PersistentOperation,
576
+ transform: async (from) => ({
577
+ [Obj.Meta]: { key: from.key, version: from.version },
578
+ name: from.name,
579
+ description: from.description,
580
+ updated: from.updated,
581
+ source: from.source as any,
582
+ inputSchema: from.inputSchema,
583
+ outputSchema: from.outputSchema,
584
+ services: from.services,
585
+ binding: from.binding,
586
+ }),
587
+ });
588
+
589
+ /**
590
+ * Schema migrations exported by this module.
591
+ * Exported as an array for extensibility — append future versions here.
592
+ */
593
+ export const migrations = [_migration];
@@ -0,0 +1,92 @@
1
+ //
2
+ // Copyright 2026 DXOS.org
3
+ //
4
+
5
+ import { Atom, Registry } from '@effect-atom/atom';
6
+ import * as Effect from 'effect/Effect';
7
+ import * as Schema from 'effect/Schema';
8
+ import { describe, test } from 'vitest';
9
+
10
+ import * as Operation from './Operation';
11
+ import * as OperationHandlerSet from './OperationHandlerSet';
12
+
13
+ const makeHandler = (key: string, output: string) =>
14
+ Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.String, meta: { key } }), () =>
15
+ Effect.succeed(output),
16
+ );
17
+
18
+ describe('OperationHandlerSet.reactive', () => {
19
+ test('merges handlers from contributed sets', async ({ expect }) => {
20
+ const registry = Registry.make();
21
+ const setA = OperationHandlerSet.make(makeHandler('a', 'A'));
22
+ const setB = OperationHandlerSet.make(makeHandler('b', 'B'));
23
+ const atom = Atom.make<readonly OperationHandlerSet.OperationHandlerSet[]>([setA, setB]).pipe(Atom.keepAlive);
24
+ registry.mount(atom);
25
+
26
+ const reactive = OperationHandlerSet.reactive(registry, atom);
27
+ const handlers = await reactive.getHandlers();
28
+ expect(handlers.map((handler) => handler.meta.key).sort()).toEqual(['a', 'b']);
29
+ });
30
+
31
+ test('caches the merged result across calls', async ({ expect }) => {
32
+ const registry = Registry.make();
33
+ let resolveCount = 0;
34
+ const trackingSet: OperationHandlerSet.OperationHandlerSet = {
35
+ [OperationHandlerSet.TypeId]: OperationHandlerSet.TypeId,
36
+ getHandlers: () => Promise.resolve([makeHandler('a', 'A')]),
37
+ handlers: Effect.sync(() => {
38
+ resolveCount++;
39
+ return [makeHandler('a', 'A')];
40
+ }),
41
+ };
42
+ const atom = Atom.make<readonly OperationHandlerSet.OperationHandlerSet[]>([trackingSet]).pipe(Atom.keepAlive);
43
+ registry.mount(atom);
44
+
45
+ const reactive = OperationHandlerSet.reactive(registry, atom);
46
+ await reactive.getHandlers();
47
+ await reactive.getHandlers();
48
+ await reactive.getHandlers();
49
+ expect(resolveCount).toBe(1);
50
+ });
51
+
52
+ test('retries after a rejection rather than caching the failure', async ({ expect }) => {
53
+ const registry = Registry.make();
54
+ let callCount = 0;
55
+ const flakySet: OperationHandlerSet.OperationHandlerSet = {
56
+ [OperationHandlerSet.TypeId]: OperationHandlerSet.TypeId,
57
+ getHandlers: () => Promise.resolve([]),
58
+ handlers: Effect.suspend(() => {
59
+ callCount++;
60
+ if (callCount === 1) {
61
+ return Effect.promise(() => Promise.reject(new Error('transient')));
62
+ }
63
+ return Effect.succeed([makeHandler('a', 'A')]);
64
+ }),
65
+ };
66
+ const atom = Atom.make<readonly OperationHandlerSet.OperationHandlerSet[]>([flakySet]).pipe(Atom.keepAlive);
67
+ registry.mount(atom);
68
+
69
+ const reactive = OperationHandlerSet.reactive(registry, atom);
70
+ await expect(reactive.getHandlers()).rejects.toThrow('transient');
71
+ const retried = await reactive.getHandlers();
72
+ expect(retried.map((handler) => handler.meta.key)).toEqual(['a']);
73
+ expect(callCount).toBe(2);
74
+ });
75
+
76
+ test('invalidates and re-resolves when the atom changes', async ({ expect }) => {
77
+ const registry = Registry.make();
78
+ const setA = OperationHandlerSet.make(makeHandler('a', 'A'));
79
+ const setB = OperationHandlerSet.make(makeHandler('b', 'B'));
80
+ const atom = Atom.make<readonly OperationHandlerSet.OperationHandlerSet[]>([setA]).pipe(Atom.keepAlive);
81
+ registry.mount(atom);
82
+
83
+ const reactive = OperationHandlerSet.reactive(registry, atom);
84
+ expect((await reactive.getHandlers()).map((handler) => handler.meta.key)).toEqual(['a']);
85
+
86
+ registry.set(atom, [setA, setB]);
87
+ expect((await reactive.getHandlers()).map((handler) => handler.meta.key).sort()).toEqual(['a', 'b']);
88
+
89
+ registry.set(atom, []);
90
+ expect(await reactive.getHandlers()).toEqual([]);
91
+ });
92
+ });