@dxos/compute 0.9.1-staging.ee54ba693a → 0.11.0

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 (131) hide show
  1. package/dist/lib/AgentService.mjs +16 -0
  2. package/dist/lib/AgentService.mjs.map +1 -0
  3. package/dist/lib/StorageService.mjs +59 -0
  4. package/dist/lib/StorageService.mjs.map +1 -0
  5. package/dist/lib/chunk-OperationHandlerSet.mjs +660 -0
  6. package/dist/lib/chunk-OperationHandlerSet.mjs.map +1 -0
  7. package/dist/lib/chunk-definitions.mjs +41 -0
  8. package/dist/lib/chunk-definitions.mjs.map +1 -0
  9. package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
  10. package/dist/lib/index.mjs +1576 -0
  11. package/dist/lib/index.mjs.map +1 -0
  12. package/dist/lib/testing.mjs +43 -0
  13. package/dist/lib/testing.mjs.map +1 -0
  14. package/dist/types/src/AgentIdentity.d.ts +27 -0
  15. package/dist/types/src/AgentIdentity.d.ts.map +1 -0
  16. package/dist/types/src/AgentService.d.ts +10 -2
  17. package/dist/types/src/AgentService.d.ts.map +1 -1
  18. package/dist/types/src/Cancellation.d.ts +19 -0
  19. package/dist/types/src/Cancellation.d.ts.map +1 -0
  20. package/dist/types/src/Credential.d.ts +41 -0
  21. package/dist/types/src/Credential.d.ts.map +1 -1
  22. package/dist/types/src/Operation.d.ts +79 -1
  23. package/dist/types/src/Operation.d.ts.map +1 -1
  24. package/dist/types/src/Process.d.ts +15 -3
  25. package/dist/types/src/Process.d.ts.map +1 -1
  26. package/dist/types/src/Trace.d.ts +55 -3
  27. package/dist/types/src/Trace.d.ts.map +1 -1
  28. package/dist/types/src/Trace.test.d.ts +2 -0
  29. package/dist/types/src/Trace.test.d.ts.map +1 -0
  30. package/dist/types/src/errors.d.ts +35 -1
  31. package/dist/types/src/errors.d.ts.map +1 -1
  32. package/dist/types/src/index.d.ts +3 -6
  33. package/dist/types/src/index.d.ts.map +1 -1
  34. package/dist/types/src/testing/index.d.ts +1 -0
  35. package/dist/types/src/testing/index.d.ts.map +1 -1
  36. package/dist/types/src/testing/operation.d.ts +5 -0
  37. package/dist/types/src/testing/operation.d.ts.map +1 -0
  38. package/dist/types/src/{Instructions.d.ts → types/Instructions.d.ts} +14 -1
  39. package/dist/types/src/types/Instructions.d.ts.map +1 -0
  40. package/dist/types/src/types/Instructions.test.d.ts +2 -0
  41. package/dist/types/src/types/Instructions.test.d.ts.map +1 -0
  42. package/dist/types/src/types/Project.d.ts +53 -0
  43. package/dist/types/src/types/Project.d.ts.map +1 -0
  44. package/dist/types/src/types/Project.test.d.ts +2 -0
  45. package/dist/types/src/types/Project.test.d.ts.map +1 -0
  46. package/dist/types/src/types/Routine.d.ts +42 -0
  47. package/dist/types/src/types/Routine.d.ts.map +1 -0
  48. package/dist/types/src/types/Routine.test.d.ts +2 -0
  49. package/dist/types/src/types/Routine.test.d.ts.map +1 -0
  50. package/dist/types/src/types/Script.d.ts.map +1 -0
  51. package/dist/types/src/{Skill.d.ts → types/Skill.d.ts} +1 -1
  52. package/dist/types/src/types/Skill.d.ts.map +1 -0
  53. package/dist/types/src/{Template.d.ts → types/Template.d.ts} +2 -2
  54. package/dist/types/src/types/Template.d.ts.map +1 -0
  55. package/dist/types/src/types/Template.test.d.ts.map +1 -0
  56. package/dist/types/src/types/Trigger.d.ts +249 -0
  57. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  58. package/dist/types/src/{TriggerEvent.d.ts → types/TriggerEvent.d.ts} +19 -6
  59. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  60. package/dist/types/src/types/index.d.ts +9 -0
  61. package/dist/types/src/types/index.d.ts.map +1 -0
  62. package/dist/types/tsconfig.tsbuildinfo +1 -1
  63. package/package.json +18 -17
  64. package/src/AgentIdentity.ts +35 -0
  65. package/src/AgentService.ts +10 -2
  66. package/src/Cancellation.ts +33 -0
  67. package/src/Credential.ts +52 -0
  68. package/src/Operation.ts +92 -2
  69. package/src/Process.ts +21 -4
  70. package/src/Trace.test.ts +155 -0
  71. package/src/Trace.ts +207 -6
  72. package/src/errors.ts +9 -5
  73. package/src/index.ts +3 -6
  74. package/src/testing/index.ts +1 -0
  75. package/src/testing/operation.ts +21 -0
  76. package/src/types/Instructions.test.ts +18 -0
  77. package/src/{Instructions.ts → types/Instructions.ts} +22 -1
  78. package/src/types/Project.test.ts +52 -0
  79. package/src/types/Project.ts +99 -0
  80. package/src/types/Routine.test.ts +18 -0
  81. package/src/types/Routine.ts +85 -0
  82. package/src/{Skill.ts → types/Skill.ts} +2 -2
  83. package/src/{Template.test.ts → types/Template.test.ts} +2 -2
  84. package/src/{Template.ts → types/Template.ts} +2 -2
  85. package/src/{Trigger.ts → types/Trigger.ts} +126 -8
  86. package/src/{TriggerEvent.ts → types/TriggerEvent.ts} +23 -5
  87. package/src/types/index.ts +12 -0
  88. package/dist/lib/neutral/AgentService.mjs +0 -12
  89. package/dist/lib/neutral/AgentService.mjs.map +0 -7
  90. package/dist/lib/neutral/StorageService.mjs +0 -22
  91. package/dist/lib/neutral/StorageService.mjs.map +0 -7
  92. package/dist/lib/neutral/chunk-2ZN64ZS7.mjs +0 -25
  93. package/dist/lib/neutral/chunk-2ZN64ZS7.mjs.map +0 -7
  94. package/dist/lib/neutral/chunk-5VAXF6AH.mjs +0 -53
  95. package/dist/lib/neutral/chunk-5VAXF6AH.mjs.map +0 -7
  96. package/dist/lib/neutral/chunk-EVROJER7.mjs +0 -285
  97. package/dist/lib/neutral/chunk-EVROJER7.mjs.map +0 -7
  98. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
  99. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
  100. package/dist/lib/neutral/chunk-PF7XP7XP.mjs +0 -62
  101. package/dist/lib/neutral/chunk-PF7XP7XP.mjs.map +0 -7
  102. package/dist/lib/neutral/chunk-SJ37RWHU.mjs +0 -21
  103. package/dist/lib/neutral/chunk-SJ37RWHU.mjs.map +0 -7
  104. package/dist/lib/neutral/chunk-VSAZPWSJ.mjs +0 -25
  105. package/dist/lib/neutral/chunk-VSAZPWSJ.mjs.map +0 -7
  106. package/dist/lib/neutral/chunk-WEO4FCQY.mjs +0 -17
  107. package/dist/lib/neutral/chunk-WEO4FCQY.mjs.map +0 -7
  108. package/dist/lib/neutral/chunk-Z3Y7FQGN.mjs +0 -174
  109. package/dist/lib/neutral/chunk-Z3Y7FQGN.mjs.map +0 -7
  110. package/dist/lib/neutral/fib-5XIYECL5.mjs +0 -10
  111. package/dist/lib/neutral/fib-5XIYECL5.mjs.map +0 -7
  112. package/dist/lib/neutral/index.mjs +0 -1232
  113. package/dist/lib/neutral/index.mjs.map +0 -7
  114. package/dist/lib/neutral/meta.json +0 -1
  115. package/dist/lib/neutral/reply-GCBRCUVM.mjs +0 -10
  116. package/dist/lib/neutral/reply-GCBRCUVM.mjs.map +0 -7
  117. package/dist/lib/neutral/sleep-XR6CL6W3.mjs +0 -10
  118. package/dist/lib/neutral/sleep-XR6CL6W3.mjs.map +0 -7
  119. package/dist/lib/neutral/testing/index.mjs +0 -32
  120. package/dist/lib/neutral/testing/index.mjs.map +0 -7
  121. package/dist/types/src/Instructions.d.ts.map +0 -1
  122. package/dist/types/src/Script.d.ts.map +0 -1
  123. package/dist/types/src/Skill.d.ts.map +0 -1
  124. package/dist/types/src/Template.d.ts.map +0 -1
  125. package/dist/types/src/Template.test.d.ts.map +0 -1
  126. package/dist/types/src/Trigger.d.ts +0 -157
  127. package/dist/types/src/Trigger.d.ts.map +0 -1
  128. package/dist/types/src/TriggerEvent.d.ts.map +0 -1
  129. /package/dist/types/src/{Script.d.ts → types/Script.d.ts} +0 -0
  130. /package/dist/types/src/{Template.test.d.ts → types/Template.test.d.ts} +0 -0
  131. /package/src/{Script.ts → types/Script.ts} +0 -0
@@ -0,0 +1,660 @@
1
+ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
2
+ import { BaseError } from "@dxos/errors";
3
+ import * as Schema from "effect/Schema";
4
+ import { Annotation, DXN, JsonSchema, Migration, Obj, Ref, Type } from "@dxos/echo";
5
+ import * as Effect from "effect/Effect";
6
+ import { assertArgument } from "@dxos/invariant";
7
+ import * as Cause from "effect/Cause";
8
+ import * as Context from "effect/Context";
9
+ import * as Layer from "effect/Layer";
10
+ import * as Option from "effect/Option";
11
+ import * as Pipeable from "effect/Pipeable";
12
+ import { pipe } from "effect/Function";
13
+ import { EffectEx } from "@dxos/effect";
14
+ import { DXN as DXN$1 } from "@dxos/keys";
15
+ //#region src/errors.ts
16
+ /**
17
+ * Raised when a function wants to yield to the scheduler to not exceed platform limits.
18
+ * The scheduler will re-run the function after the yield.
19
+ * It is assumed that the function can be retried with the same input.
20
+ * The function might have produced side-effects on the first run.
21
+ */
22
+ var RunAgainError = class extends BaseError.extend("RunAgainError", "Run again") {};
23
+ var InvokerNotInitializedError = class extends BaseError.extend("InvokerNotInitializedError", "Invoker not initialized") {};
24
+ var NoHandlerError = class extends BaseError.extend("NoHandlerError", "No handler found for operation. ") {
25
+ constructor(operationKey) {
26
+ super({ context: { operationKey } });
27
+ }
28
+ };
29
+ var ServiceNotAvailableError = class extends BaseError.extend("ServiceNotAvailable", "Service not available") {
30
+ constructor(service, options) {
31
+ super({
32
+ context: { service },
33
+ message: `Service not available: ${service}`,
34
+ ...options
35
+ });
36
+ }
37
+ };
38
+ var FunctionNotFoundError = class extends BaseError.extend("FunctionNotFound", "Function not found") {
39
+ constructor(functionKey, options) {
40
+ super({
41
+ context: { function: functionKey },
42
+ ...options
43
+ });
44
+ }
45
+ };
46
+ var FunctionError = class extends BaseError.extend("FunctionError", "Function invocation error") {};
47
+ var InvalidOperationInputError = class extends BaseError.extend("InvalidOperationInput", "Operation input did not match schema") {};
48
+ var InvalidOperationOutputError = class extends BaseError.extend("InvalidOperationOutput", "Operation output did not match schema") {};
49
+ var TriggerStateNotFoundError = class extends BaseError.extend("TriggerStateNotFound", "Trigger state not found") {};
50
+ /**
51
+ * Raised when the upstream AI gateway responds with a structured JSON error envelope
52
+ * (`{ "type": "error", "error": { "type": ..., "message": ... } }`). Surfaces as a typed
53
+ * defect from `FunctionsAiHttpClient`, bypassing `@effect/ai`'s generic `HttpResponseError`
54
+ * wrapping so callers can match on the error class directly.
55
+ */
56
+ var FunctionsAiUpstreamError = class extends BaseError.extend("FunctionsAiUpstreamError", "Upstream AI service returned an error") {};
57
+ /**
58
+ * Specialized `FunctionsAiUpstreamError` for the memoization layer: the recorded fixture for a
59
+ * given cache key was not found and `ALLOW_LLM_GENERATION` is unset. The `cacheKey` is exposed
60
+ * via `context.cacheKey` to make regeneration straightforward.
61
+ */
62
+ var FunctionsAiMemoizationMissError = class extends BaseError.extend("FunctionsAiMemoizationMissError", "No memoized AI conversation found for the given cache key") {};
63
+ //#endregion
64
+ //#region src/Operation.ts
65
+ var Operation_exports = /* @__PURE__ */ __exportAll({
66
+ DefinitionTypeId: () => DefinitionTypeId,
67
+ IdempotentAnnotation: () => IdempotentAnnotation,
68
+ Label: () => Label,
69
+ McpTool: () => McpTool,
70
+ McpToolAnnotation: () => McpToolAnnotation,
71
+ NotifyOptions: () => NotifyOptions,
72
+ NotifyOptionsAnnotation: () => NotifyOptionsAnnotation,
73
+ PersistentOperation: () => PersistentOperation,
74
+ PersistentOperation_v0_1_0: () => PersistentOperation_v0_1_0,
75
+ Service: () => Service,
76
+ VisibleAnnotation: () => VisibleAnnotation,
77
+ annotate: () => annotate,
78
+ deserialize: () => deserialize,
79
+ getKey: () => getKey,
80
+ getMcpTool: () => getMcpTool,
81
+ getVersion: () => getVersion,
82
+ idempotent: () => idempotent,
83
+ invoke: () => invoke,
84
+ isIdempotent: () => isIdempotent,
85
+ isOperationDefinition: () => isOperationDefinition,
86
+ isOperationWithHandler: () => isOperationWithHandler,
87
+ isVisible: () => isVisible,
88
+ make: () => make$1,
89
+ mcpTool: () => mcpTool,
90
+ migrations: () => migrations,
91
+ opaqueHandler: () => opaqueHandler,
92
+ prepare: () => prepare,
93
+ runAgain: () => runAgain,
94
+ schedule: () => schedule,
95
+ serialize: () => serialize,
96
+ setFrom: () => setFrom,
97
+ visible: () => visible,
98
+ withHandler: () => withHandler,
99
+ withInvocationOptions: () => withInvocationOptions
100
+ });
101
+ var DefinitionTypeId = "~@dxos/operation/OperationDefinition";
102
+ /**
103
+ * Checks if a value is an operation definition.
104
+ */
105
+ var isOperationDefinition = (value) => {
106
+ return typeof value === "object" && value !== null && "~@dxos/operation/OperationDefinition" in value;
107
+ };
108
+ /**
109
+ * Checks if a value is an operation with a handler.
110
+ */
111
+ var isOperationWithHandler = (value) => {
112
+ return isOperationDefinition(value) && "handler" in value;
113
+ };
114
+ /**
115
+ * Creates a new Operation definition.
116
+ * Applies default executionMode of 'async' if not specified.
117
+ * The returned type preserves the literal types of props (including services).
118
+ */
119
+ var make$1 = (props) => {
120
+ return {
121
+ [DefinitionTypeId]: {},
122
+ ...props,
123
+ executionMode: props.executionMode ?? "async",
124
+ types: props.types ?? [],
125
+ services: props.services ?? [],
126
+ pipe() {
127
+ return Pipeable.pipeArguments(this, arguments);
128
+ }
129
+ };
130
+ };
131
+ /**
132
+ * Attaches a handler to an Operation definition.
133
+ * The handler may use any services declared in the operation, plus Operation.Service (always available).
134
+ * Dual API: can be called directly or used in a pipe.
135
+ *
136
+ * @example
137
+ * ```ts
138
+ * const MyOp = Operation.make({
139
+ * input: Schema.Void,
140
+ * output: Schema.Void,
141
+ * meta: { key: 'my-op' },
142
+ * services: [DatabaseService],
143
+ * });
144
+ *
145
+ * // Direct call - handler can use DatabaseService
146
+ * const op = Operation.withHandler(MyOp, (input) =>
147
+ * Effect.gen(function* () {
148
+ * const db = yield* DatabaseService;
149
+ * return {};
150
+ * }),
151
+ * );
152
+ *
153
+ * // Piped call
154
+ * const op = MyOp.pipe(Operation.withHandler((input) => Effect.succeed({})));
155
+ * ```
156
+ */
157
+ var withHandler = (opOrHandler, handler) => {
158
+ if (handler === void 0) {
159
+ const handlerFn = opOrHandler;
160
+ return ((op) => ({
161
+ ...op,
162
+ handler: handlerFn
163
+ }));
164
+ }
165
+ return {
166
+ ...opOrHandler,
167
+ handler
168
+ };
169
+ };
170
+ /**
171
+ * Helper to make the handler type opaque.
172
+ * Workaround for TypeScript's inability to infer the handler type from the operation definition:
173
+ * ```
174
+ * error TS2742: The inferred type of 'default' cannot be named without a reference.
175
+ * ```
176
+ *
177
+ * Most of the time the exact handler type is not needed.
178
+ *
179
+ * @example
180
+ * ```ts
181
+ * const MyOp = Operation.make({
182
+ * input: Schema.Void,
183
+ * output: Schema.Void,
184
+ * meta: { key: 'my-op' },
185
+ * services: [DatabaseService],
186
+ * });
187
+ *
188
+ * export default MyOp.pipe(
189
+ * Operation.withHandler(
190
+ * Effect.fn(function* (input) {
191
+ * return { result: 'ok' };
192
+ * }),
193
+ * ),
194
+ * Operation.opaqueHandler,
195
+ * );
196
+ * ```
197
+ */
198
+ var opaqueHandler = (handler) => handler;
199
+ /**
200
+ * Database record of an operation.
201
+ * The registry `key` and `version` live in the object meta — access via
202
+ * `Obj.getMeta(record).key` and `Obj.getMeta(record).version`.
203
+ */
204
+ var PersistentOperation = class extends Type.makeObject(DXN.make("org.dxos.type.function", "0.2.0"))(Schema.Struct({
205
+ name: Schema.NonEmptyString,
206
+ description: Schema.optional(Schema.String),
207
+ /**
208
+ * ISO date string of the last deployment.
209
+ */
210
+ updated: Schema.optional(Schema.String),
211
+ source: Schema.optional(Ref.Ref(Obj.Unknown)),
212
+ inputSchema: Schema.optional(JsonSchema.JsonSchema),
213
+ outputSchema: Schema.optional(JsonSchema.JsonSchema),
214
+ /**
215
+ * List of required services.
216
+ * Match the Context.Tag keys of the services the operation handler declares.
217
+ */
218
+ services: Schema.optional(Schema.Array(Schema.String)),
219
+ binding: Schema.optional(Schema.String),
220
+ /**
221
+ * Phosphor icon identifier in `ph--<name>--<variant>` format (e.g. `ph--file-text--regular`).
222
+ */
223
+ icon: Schema.optional(Schema.String)
224
+ }).pipe(Annotation.LabelAnnotation.set(["name"]), Annotation.IconAnnotation.set({
225
+ icon: "ph--function--regular",
226
+ hue: "blue"
227
+ }), Annotation.HiddenAnnotation.set(true))) {};
228
+ var FUNCTION_META_KEY = "org.dxos.service.function";
229
+ /**
230
+ * Get the registry key for a persistent operation record (from the object meta).
231
+ */
232
+ var getKey = (record) => Obj.getMeta(record).key;
233
+ /**
234
+ * Get the registry version for a persistent operation record (from the object meta).
235
+ */
236
+ var getVersion = (record) => Obj.getMeta(record).version;
237
+ /**
238
+ * Serialize an operation definition to a persistent operation record.
239
+ */
240
+ var serialize = (operation) => {
241
+ return Obj.make(PersistentOperation, {
242
+ [Obj.Meta]: {
243
+ key: operation.meta.key,
244
+ version: operation.meta.version ?? "0.0.0",
245
+ keys: operation.meta.deployedId ? [{
246
+ source: FUNCTION_META_KEY,
247
+ id: operation.meta.deployedId
248
+ }] : [],
249
+ annotations: operation.meta.annotations
250
+ },
251
+ name: operation.meta.name ?? "",
252
+ description: operation.meta.description,
253
+ icon: operation.meta.icon,
254
+ updated: void 0,
255
+ source: void 0,
256
+ inputSchema: JsonSchema.toJsonSchema(operation.input),
257
+ outputSchema: JsonSchema.toJsonSchema(operation.output),
258
+ services: operation.services.map((service) => service.key)
259
+ });
260
+ };
261
+ /**
262
+ * Deserialize a persistent operation record to an operation definition.
263
+ */
264
+ var deserialize = (record) => {
265
+ const meta = Obj.getMeta(record);
266
+ const deployedId = meta.keys.find((key) => key.source === FUNCTION_META_KEY)?.id;
267
+ return make$1({
268
+ input: record.inputSchema ? JsonSchema.toEffectSchema(record.inputSchema) : Schema.Unknown,
269
+ output: record.outputSchema ? JsonSchema.toEffectSchema(record.outputSchema) : Schema.Unknown,
270
+ services: record.services?.map((service) => Context.GenericTag(service)) ?? [],
271
+ executionMode: "async",
272
+ types: [],
273
+ meta: {
274
+ key: DXN.tryMake(meta.key ?? record.name) ?? DXN.make(meta.key ?? record.name),
275
+ name: record.name,
276
+ version: meta.version ?? "0.0.0",
277
+ description: record.description,
278
+ icon: record.icon,
279
+ deployedId,
280
+ annotations: meta.annotations ?? {}
281
+ }
282
+ });
283
+ };
284
+ /**
285
+ * Update properties on the target operation record from the source operation record.
286
+ */
287
+ var setFrom = (target, source) => {
288
+ Obj.update(target, (target) => {
289
+ target.name = source.name ?? target.name;
290
+ target.description = source.description;
291
+ target.icon = source.icon;
292
+ target.updated = source.updated;
293
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : void 0;
294
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : void 0;
295
+ const sourceMeta = Obj.getMeta(source);
296
+ const targetMeta = Obj.getMeta(target);
297
+ targetMeta.key = sourceMeta.key ?? targetMeta.key;
298
+ targetMeta.version = sourceMeta.version;
299
+ if (sourceMeta.keys.length > 0) targetMeta.keys = JSON.parse(JSON.stringify(sourceMeta.keys));
300
+ targetMeta.annotations = sourceMeta.annotations ?? targetMeta.annotations;
301
+ });
302
+ };
303
+ /**
304
+ * Translatable label — a plain string or an i18next-style `[key, options]` tuple.
305
+ * Defined locally to avoid a core dependency on UI translation packages; structurally compatible with
306
+ * the app-level `Label` type so values flow into UI toasts unchanged.
307
+ */
308
+ var Label = Schema.Union(Schema.String, Schema.mutable(Schema.Tuple(Schema.String, Schema.mutable(Schema.Struct({
309
+ ns: Schema.String,
310
+ count: Schema.optional(Schema.Number),
311
+ defaultValue: Schema.optional(Schema.String)
312
+ })))));
313
+ /**
314
+ * Per-phase user notification messages for an invocation.
315
+ * A phase is notified to the user iff its message is provided; messages are translatable {@link Label}s.
316
+ */
317
+ var NotifyOptions = Schema.Struct({
318
+ /** Shown when the invocation starts. */
319
+ start: Schema.optional(Label),
320
+ /** Shown when the invocation succeeds. */
321
+ success: Schema.optional(Label),
322
+ /** Shown when the invocation fails. */
323
+ error: Schema.optional(Label)
324
+ });
325
+ /**
326
+ * Annotation that configures the process to notify the user at the given invocation phases.
327
+ */
328
+ var NotifyOptionsAnnotation = Annotation.make({
329
+ id: "org.dxos.operation.notify-options",
330
+ schema: NotifyOptions
331
+ });
332
+ /**
333
+ * Builds a {@link SerializedInvocation} from a live {@link Definition} and its input — the serializable
334
+ * counterpart to a direct `invoke`, for describing an invocation that must cross a serialization
335
+ * boundary (e.g. a deferred toast action). Resolve it later with `OperationHandlerSet.getHandlerByKey`.
336
+ */
337
+ var prepare = (operation, input) => ({
338
+ operation: operation.meta.key,
339
+ input
340
+ });
341
+ /**
342
+ * Annotation that marks an operation as idempotent — safe to retry even if a previous execution
343
+ * was interrupted mid-handler. When absent the operation is treated as non-idempotent, and the
344
+ * process runtime will fail (rather than re-run) any handler that was interrupted.
345
+ */
346
+ var IdempotentAnnotation = Annotation.make({
347
+ id: "org.dxos.operation.idempotent",
348
+ schema: Schema.Boolean
349
+ });
350
+ /**
351
+ * Returns true when the operation is explicitly annotated as idempotent.
352
+ */
353
+ var isIdempotent = (op) => op.meta.annotations ? Option.getOrElse(Annotation.getDictionary(op.meta.annotations, IdempotentAnnotation), () => false) : false;
354
+ /**
355
+ * Attaches an annotation to an operation definition, returning a new definition.
356
+ * Combinators never mutate their input — operation definitions are module-level singletons
357
+ * shared across handler sets, skills, and the registry, so a fresh value keeps the
358
+ * annotated definition distinct from any other reference to the original.
359
+ *
360
+ * Type-preserving: an annotation does not change the operation's input/output/service types, so the
361
+ * returned definition keeps `Def` (preserving `withHandler` inference and downstream usage).
362
+ */
363
+ var annotate = (annotation, value) => (op) => {
364
+ const annotations = { ...op.meta.annotations ?? {} };
365
+ Annotation.setDictionary(annotations, annotation, value);
366
+ return {
367
+ ...op,
368
+ meta: {
369
+ ...op.meta,
370
+ annotations
371
+ }
372
+ };
373
+ };
374
+ /**
375
+ * Marks an operation as visible on user-facing operation surfaces (trigger/automation pickers,
376
+ * manual invocation). Absent ⇒ internal: invoked programmatically by plugins and hidden from pickers.
377
+ *
378
+ * Polarity is inverted from the schema-level `HiddenAnnotation` (default visible): operations are
379
+ * hidden by default, since most are internal plugin machinery and only a minority are user-facing.
380
+ */
381
+ var VisibleAnnotation = Annotation.make({
382
+ id: "org.dxos.operation.visible",
383
+ schema: Schema.Boolean
384
+ });
385
+ /**
386
+ * Pipeable combinator that marks an operation visible. Apply at the definition site:
387
+ * `Operation.make({ ... }).pipe(Operation.visible)`.
388
+ */
389
+ var visible = annotate(VisibleAnnotation, true);
390
+ /**
391
+ * Returns true when an operation is annotated as visible on user-facing surfaces (trigger/automation
392
+ * pickers, manual invocation). Reads from the persisted operation — the form every consumer holds.
393
+ */
394
+ var isVisible = (op) => Option.getOrElse(Annotation.get(op, VisibleAnnotation), () => false);
395
+ /**
396
+ * Projection marker for an operation exposed as an MCP tool to external agents.
397
+ * See plugin-projects `MILESTONE-5.md` §7.4 for the full contract.
398
+ */
399
+ var McpTool = Schema.Struct({
400
+ /** Tool name as exposed to MCP clients; camelCase, domain-prefixed (e.g. `taskCreate`). */
401
+ name: Schema.String,
402
+ /** Model-facing description; falls back to the operation's own description when absent. */
403
+ description: Schema.optional(Schema.String),
404
+ /**
405
+ * Safety class the server maps to MCP tool hints: `read` is side-effect free (readOnlyHint),
406
+ * `write` mutates space data, `destructive` deletes or is otherwise irreversible.
407
+ */
408
+ safety: Schema.Literal("read", "write", "destructive"),
409
+ /** Aspect/toolset, for server-side filtering (e.g. `/mcp?toolsets=tasks`). */
410
+ aspect: Schema.optional(Schema.String)
411
+ });
412
+ /**
413
+ * Annotation that opts an operation into MCP projection. The annotation rides through
414
+ * {@link serialize} into the persisted record, so a remote projector (edge mcp-space-service)
415
+ * discovers tools from the operation registry rather than a hand-maintained table.
416
+ *
417
+ * Projected operations must be remotely invocable: refs (not live objects) in, JSON snapshots
418
+ * out, schemas that survive serialization, and worker-safe handlers — MILESTONE-5.md §7.4.
419
+ */
420
+ var McpToolAnnotation = Annotation.make({
421
+ id: "org.dxos.operation.mcp-tool",
422
+ schema: McpTool
423
+ });
424
+ /**
425
+ * Pipeable combinator that opts an operation into MCP projection. Apply at the definition site:
426
+ * `Operation.make({ ... }).pipe(Operation.mcpTool({ name: 'taskComplete', safety: 'write' }))`.
427
+ */
428
+ var mcpTool = (props) => annotate(McpToolAnnotation, props);
429
+ /**
430
+ * Returns the MCP projection descriptor when the operation is annotated for it, else undefined.
431
+ * Reads from the persisted operation — the form the projector holds.
432
+ */
433
+ var getMcpTool = (op) => Option.getOrUndefined(Annotation.get(op, McpToolAnnotation));
434
+ /**
435
+ * Pipeable combinator that marks an operation idempotent — see {@link IdempotentAnnotation}. Apply at
436
+ * the definition site: `Operation.make({ ... }).pipe(Operation.idempotent)`.
437
+ */
438
+ var idempotent = annotate(IdempotentAnnotation, true);
439
+ /**
440
+ * Context tag for the Operation service.
441
+ * Operation handlers can yield this to invoke other operations or schedule followups.
442
+ *
443
+ * @example
444
+ * ```ts
445
+ * const handler = (input) => Effect.gen(function* () {
446
+ * // Schedule a followup (fire and forget)
447
+ * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });
448
+ *
449
+ * // Invoke another operation
450
+ * return yield* Operation.invoke(OtherOperation, { data: input.data });
451
+ * });
452
+ * ```
453
+ */
454
+ var Service = class extends Context.Tag("@dxos/operation/Service")() {};
455
+ /**
456
+ * Invoke an operation as an Effect.
457
+ * Yields the Operation.Service internally.
458
+ *
459
+ * @example
460
+ * ```ts
461
+ * yield* Operation.invoke(MyOperation, { data: 'test' });
462
+ * ```
463
+ */
464
+ var invoke = (op, ...args) => Effect.flatMap(Service, (ops) => ops.invoke(op, ...args)).pipe(Effect.withSpan("Operation.invoke"));
465
+ /**
466
+ * Schedule an operation to run as a followup.
467
+ * Yields the Operation.Service internally.
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });
472
+ * yield* Operation.schedule(VoidOperation); // input optional when void
473
+ * ```
474
+ */
475
+ var schedule = (op, ...args) => Effect.flatMap(Service, (ops) => ops.schedule(op, ...args)).pipe(Effect.withSpan("Operation.schedule"));
476
+ /**
477
+ * Call inside an operation to stop the current invocation and have the system re-run it (e.g. a capped
478
+ * sync run with more work left). Surfaces as a {@link RunAgainError} defect; the trigger dispatcher
479
+ * re-queues the same event FIFO to continue. A caller invoking via `Operation.invoke` directly gets the
480
+ * defect and does not auto-continue.
481
+ */
482
+ var runAgain = () => Effect.failCauseSync(() => Cause.die(new RunAgainError()));
483
+ /**
484
+ * Provides additional invocation options to all invocations.
485
+ */
486
+ var withInvocationOptions = (options) => Layer.effect(Service, Effect.gen(function* () {
487
+ const service = yield* Service;
488
+ return Service.of({
489
+ invoke: ((op, input, invocationOptions) => service.invoke(op, input, {
490
+ ...options,
491
+ ...invocationOptions
492
+ })),
493
+ invokePromise: ((op, input, invocationOptions) => service.invokePromise(op, input, {
494
+ ...options,
495
+ ...invocationOptions
496
+ })),
497
+ schedule: ((op, input, invocationOptions) => service.schedule(op, input, {
498
+ ...options,
499
+ ...invocationOptions
500
+ }))
501
+ });
502
+ }));
503
+ /**
504
+ * Persistent operation schema v0.1.0 — `key` and `version` are stored as data properties.
505
+ * @deprecated Use {@link PersistentOperation} (v0.2.0) instead; the `key` and `version` now live in the object meta.
506
+ */
507
+ var PersistentOperation_v0_1_0 = class extends Type.makeObject(DXN.make("org.dxos.type.function", "0.1.0"))(Schema.Struct({
508
+ key: Schema.optional(Schema.String),
509
+ name: Schema.NonEmptyString,
510
+ version: Schema.String,
511
+ description: Schema.optional(Schema.String),
512
+ updated: Schema.optional(Schema.String),
513
+ source: Schema.optional(Ref.Ref(Obj.Unknown)),
514
+ inputSchema: Schema.optional(JsonSchema.JsonSchema),
515
+ outputSchema: Schema.optional(JsonSchema.JsonSchema),
516
+ services: Schema.optional(Schema.Array(Schema.String)),
517
+ binding: Schema.optional(Schema.String)
518
+ })) {};
519
+ /**
520
+ * Schema migrations exported by this module.
521
+ * Exported as an array for extensibility — append future versions here.
522
+ */
523
+ var migrations = [Migration.define({
524
+ from: PersistentOperation_v0_1_0,
525
+ to: PersistentOperation,
526
+ transform: async (from) => ({
527
+ [Obj.Meta]: {
528
+ key: from.key,
529
+ version: from.version
530
+ },
531
+ name: from.name,
532
+ description: from.description,
533
+ updated: from.updated,
534
+ source: from.source,
535
+ inputSchema: from.inputSchema,
536
+ outputSchema: from.outputSchema,
537
+ services: from.services,
538
+ binding: from.binding
539
+ })
540
+ })];
541
+ //#endregion
542
+ //#region src/OperationHandlerSet.ts
543
+ var OperationHandlerSet_exports = /* @__PURE__ */ __exportAll({
544
+ OperationHandlerProvider: () => OperationHandlerProvider,
545
+ TypeId: () => TypeId,
546
+ async: () => async,
547
+ empty: () => empty,
548
+ getHandler: () => getHandler,
549
+ getHandlerByKey: () => getHandlerByKey,
550
+ isOperationHandlerSet: () => isOperationHandlerSet,
551
+ lazy: () => lazy,
552
+ make: () => make,
553
+ merge: () => merge,
554
+ provide: () => provide,
555
+ reactive: () => reactive
556
+ });
557
+ var TypeId = "~@dxos/operation/OperationHandlerSet";
558
+ var isOperationHandlerSet = (value) => {
559
+ return typeof value === "object" && value !== null && "~@dxos/operation/OperationHandlerSet" in value;
560
+ };
561
+ var empty = {
562
+ [TypeId]: TypeId,
563
+ handlers: Effect.succeed([]),
564
+ getHandlers: () => Promise.resolve([])
565
+ };
566
+ /**
567
+ * Creates a new operation handler set from a list of handlers.
568
+ *
569
+ * @example
570
+ * ```ts
571
+ * const set = OperationHandlerSet.make(
572
+ * Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.Void }), (input) => Effect.succeed({})),
573
+ * Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.Void }), (input) => Effect.succeed({})),
574
+ * );
575
+ * ```
576
+ */
577
+ var make = (...handlers) => {
578
+ return async(() => Promise.resolve(handlers));
579
+ };
580
+ var async = (getHandlers) => {
581
+ let promise = null;
582
+ const getHandlersCached = () => {
583
+ if (!promise) promise = getHandlers();
584
+ return promise;
585
+ };
586
+ return {
587
+ [TypeId]: TypeId,
588
+ getHandlers,
589
+ handlers: Effect.promise(getHandlersCached)
590
+ };
591
+ };
592
+ /**
593
+ * Builds a set backed by an atom of contributed sets. The merged result is
594
+ * cached and invalidated whenever the atom changes, so most accesses are
595
+ * cheap but newly registered handlers are picked up.
596
+ */
597
+ var reactive = (registry, atom) => {
598
+ let cached = null;
599
+ registry.subscribe(atom, () => {
600
+ cached = null;
601
+ });
602
+ const compute = Effect.suspend(() => pipe(registry.get(atom), Effect.forEach((set) => set.handlers, { concurrency: "unbounded" }), Effect.map((groups) => groups.flat()), Effect.tapErrorCause(() => Effect.sync(() => {
603
+ cached = null;
604
+ }))));
605
+ const getHandlers = () => cached ??= EffectEx.runAndForwardErrors(compute);
606
+ return {
607
+ [TypeId]: TypeId,
608
+ getHandlers,
609
+ handlers: Effect.promise(getHandlers)
610
+ };
611
+ };
612
+ /**
613
+ * Merges multiple operation handler sets into a single set.
614
+ *
615
+ */
616
+ var merge = (...sets) => {
617
+ assertArgument(sets.every(isOperationHandlerSet), "sets", "sets must be an array of OperationHandlerSet");
618
+ return async(() => Promise.all(sets.map((set) => set.getHandlers())).then((handlers) => handlers.flat()));
619
+ };
620
+ /**
621
+ * Creates a new operation handler set from a list of lazy-loaded modules.
622
+ *
623
+ * @example
624
+ * ```ts
625
+ * const set = OperationHandlerSet.lazy(
626
+ * () => import('./my-handler'),
627
+ * () => import('./my-other-handler'),
628
+ * );
629
+ * ```
630
+ */
631
+ var lazy = (...modules) => {
632
+ return async(() => Promise.all(modules.map((module) => module().then(({ default: handler }) => handler))));
633
+ };
634
+ /**
635
+ * Gets a handler for an operation by definition.
636
+ */
637
+ var getHandler = (set, definition) => Effect.gen(function* () {
638
+ const handler = (yield* set.handlers).find((handler) => handler.meta.key === definition.meta.key);
639
+ if (!handler) return yield* Effect.fail(new NoHandlerError(definition.meta.key));
640
+ return handler;
641
+ });
642
+ /**
643
+ * Gets a handler for an operation by key.
644
+ * Accepts either a plain NSID (`org.dxos.function.database.contextAdd`) or a
645
+ * full DXN string (`dxn:org.dxos.function.database.contextAdd`).
646
+ */
647
+ var getHandlerByKey = (set, key) => Effect.gen(function* () {
648
+ const handlers = yield* set.handlers;
649
+ const normalizeKey = (k) => DXN$1.isDXN(k) ? DXN$1.getName(k) : k;
650
+ const normalizedKey = normalizeKey(key);
651
+ const handler = handlers.find((handler) => normalizeKey(handler.meta.key) === normalizedKey);
652
+ if (!handler) return yield* Effect.fail(new NoHandlerError(key));
653
+ return handler;
654
+ });
655
+ var OperationHandlerProvider = class extends Context.Tag("@dxos/operation/OperationHandlerProvider")() {};
656
+ var provide = (handlers) => Layer.succeed(OperationHandlerProvider, handlers);
657
+ //#endregion
658
+ export { RunAgainError as C, NoHandlerError as S, TriggerStateNotFoundError as T, FunctionsAiMemoizationMissError as _, lazy as a, InvalidOperationOutputError as b, PersistentOperation as c, invoke as d, isIdempotent as f, FunctionNotFoundError as g, FunctionError as h, getHandlerByKey as i, Service as l, withHandler as m, OperationHandlerSet_exports as n, NotifyOptions as o, make$1 as p, getHandler as r, Operation_exports as s, OperationHandlerProvider as t, deserialize as u, FunctionsAiUpstreamError as v, ServiceNotAvailableError as w, InvokerNotInitializedError as x, InvalidOperationInputError as y };
659
+
660
+ //# sourceMappingURL=chunk-OperationHandlerSet.mjs.map