@dxos/compute 0.8.4-main.03d5cd7b56 → 0.8.4-main.05e74ebcff
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.
- package/LICENSE +102 -5
- package/dist/lib/neutral/{chunk-EG7VLX2F.mjs → chunk-AKVCVI6N.mjs} +3 -3
- package/dist/lib/neutral/{chunk-JTZYM2QW.mjs → chunk-LF2ANNYW.mjs} +29 -2
- package/dist/lib/neutral/chunk-LF2ANNYW.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-OA7JMLJK.mjs → chunk-LRCABAWU.mjs} +3 -3
- package/dist/lib/neutral/{chunk-YEDUHFRC.mjs → chunk-RCLYF66G.mjs} +3 -3
- package/dist/lib/neutral/{chunk-VIRNEVFD.mjs → chunk-SEBWOTOU.mjs} +58 -22
- package/dist/lib/neutral/chunk-SEBWOTOU.mjs.map +7 -0
- package/dist/lib/neutral/{chunk-CXDV2FPU.mjs → chunk-VSICPGGY.mjs} +2 -2
- package/dist/lib/neutral/fib-ZSJYREBW.mjs +10 -0
- package/dist/lib/neutral/index.mjs +243 -91
- package/dist/lib/neutral/index.mjs.map +4 -4
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/lib/neutral/reply-YH3BVOUT.mjs +10 -0
- package/dist/lib/neutral/sleep-TSPIQ5EY.mjs +10 -0
- package/dist/lib/neutral/testing/index.mjs +7 -7
- package/dist/types/src/Blueprint.d.ts +57 -5
- package/dist/types/src/Blueprint.d.ts.map +1 -1
- package/dist/types/src/LayerSpec.d.ts +56 -0
- package/dist/types/src/LayerSpec.d.ts.map +1 -0
- package/dist/types/src/Operation.d.ts +35 -4
- package/dist/types/src/Operation.d.ts.map +1 -1
- package/dist/types/src/OperationHandlerSet.d.ts +7 -0
- package/dist/types/src/OperationHandlerSet.d.ts.map +1 -1
- package/dist/types/src/OperationHandlerSet.test.d.ts +2 -0
- package/dist/types/src/OperationHandlerSet.test.d.ts.map +1 -0
- package/dist/types/src/OperationRegistry.d.ts.map +1 -1
- package/dist/types/src/Process.d.ts.map +1 -1
- package/dist/types/src/Routine.d.ts +5 -5
- package/dist/types/src/Routine.d.ts.map +1 -1
- package/dist/types/src/ServiceResolver.d.ts +15 -0
- package/dist/types/src/ServiceResolver.d.ts.map +1 -1
- package/dist/types/src/Trace.d.ts +94 -0
- package/dist/types/src/Trace.d.ts.map +1 -1
- package/dist/types/src/Trigger.d.ts +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +13 -12
- package/src/Blueprint.ts +116 -20
- package/src/LayerSpec.ts +91 -0
- package/src/Operation.ts +83 -23
- package/src/OperationHandlerSet.test.ts +92 -0
- package/src/OperationHandlerSet.ts +40 -0
- package/src/OperationRegistry.ts +2 -2
- package/src/Process.ts +14 -0
- package/src/Routine.ts +31 -44
- package/src/ServiceResolver.ts +20 -0
- package/src/Trace.ts +141 -4
- package/src/Trigger.ts +2 -2
- package/src/index.ts +1 -0
- package/dist/lib/neutral/chunk-JTZYM2QW.mjs.map +0 -7
- package/dist/lib/neutral/chunk-VIRNEVFD.mjs.map +0 -7
- package/dist/lib/neutral/fib-WSN4EY7R.mjs +0 -10
- package/dist/lib/neutral/reply-XRLTFNDF.mjs +0 -10
- package/dist/lib/neutral/sleep-7O76LQCA.mjs +0 -10
- /package/dist/lib/neutral/{chunk-EG7VLX2F.mjs.map → chunk-AKVCVI6N.mjs.map} +0 -0
- /package/dist/lib/neutral/{chunk-OA7JMLJK.mjs.map → chunk-LRCABAWU.mjs.map} +0 -0
- /package/dist/lib/neutral/{chunk-YEDUHFRC.mjs.map → chunk-RCLYF66G.mjs.map} +0 -0
- /package/dist/lib/neutral/{chunk-CXDV2FPU.mjs.map → chunk-VSICPGGY.mjs.map} +0 -0
- /package/dist/lib/neutral/{fib-WSN4EY7R.mjs.map → fib-ZSJYREBW.mjs.map} +0 -0
- /package/dist/lib/neutral/{reply-XRLTFNDF.mjs.map → reply-YH3BVOUT.mjs.map} +0 -0
- /package/dist/lib/neutral/{sleep-7O76LQCA.mjs.map → sleep-TSPIQ5EY.mjs.map} +0 -0
package/src/OperationRegistry.ts
CHANGED
|
@@ -9,7 +9,7 @@ import * as Effect from 'effect/Effect';
|
|
|
9
9
|
import * as Layer from 'effect/Layer';
|
|
10
10
|
import * as Option from 'effect/Option';
|
|
11
11
|
|
|
12
|
-
import { Database, Query } from '@dxos/echo';
|
|
12
|
+
import { Database, Filter, Query } from '@dxos/echo';
|
|
13
13
|
|
|
14
14
|
import * as Operation from './Operation';
|
|
15
15
|
import * as OperationHandlerSet from './OperationHandlerSet';
|
|
@@ -37,7 +37,7 @@ export const layer: Layer.Layer<Service, never, Database.Service | OperationHand
|
|
|
37
37
|
const handlerSet = yield* OperationHandlerSet.OperationHandlerProvider;
|
|
38
38
|
return {
|
|
39
39
|
resolve: (key: string) =>
|
|
40
|
-
Database.runQueryFirst(Query.type(Operation.PersistentOperation,
|
|
40
|
+
Database.runQueryFirst(Query.select(Filter.and(Filter.type(Operation.PersistentOperation), Filter.key(key))))
|
|
41
41
|
.pipe(
|
|
42
42
|
Effect.flatten,
|
|
43
43
|
Effect.map(Operation.deserialize),
|
package/src/Process.ts
CHANGED
|
@@ -262,6 +262,13 @@ export const fromOperation = <const Op extends Operation.Definition.Any>(
|
|
|
262
262
|
key: op.meta.key,
|
|
263
263
|
name: op.meta.name,
|
|
264
264
|
});
|
|
265
|
+
// Emit ephemeral operation input event for live subscribers
|
|
266
|
+
// (history tracker, devtools) without persisting raw input.
|
|
267
|
+
yield* Trace.write(Trace.OperationInput, {
|
|
268
|
+
key: op.meta.key,
|
|
269
|
+
name: op.meta.name,
|
|
270
|
+
input,
|
|
271
|
+
});
|
|
265
272
|
|
|
266
273
|
const opHandler = yield* OperationHandlerSet.getHandler(handler, op).pipe(Effect.orDie);
|
|
267
274
|
const output = yield* opHandler
|
|
@@ -275,6 +282,13 @@ export const fromOperation = <const Op extends Operation.Definition.Any>(
|
|
|
275
282
|
ctx.submitOutput(output);
|
|
276
283
|
ctx.succeed();
|
|
277
284
|
|
|
285
|
+
// Emit ephemeral operation output event before the persisted
|
|
286
|
+
// end event so subscribers see output + completion together.
|
|
287
|
+
yield* Trace.write(Trace.OperationOutput, {
|
|
288
|
+
key: op.meta.key,
|
|
289
|
+
name: op.meta.name,
|
|
290
|
+
output,
|
|
291
|
+
});
|
|
278
292
|
// Emit operation end event with success after side-effects complete.
|
|
279
293
|
yield* Trace.write(Trace.OperationEnd, {
|
|
280
294
|
key: op.meta.key,
|
package/src/Routine.ts
CHANGED
|
@@ -12,47 +12,24 @@ import * as Blueprint from './Blueprint';
|
|
|
12
12
|
import * as Template from './Template';
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
16
|
-
* May reference additional context.
|
|
15
|
+
* Prompt-based operation.
|
|
16
|
+
* May reference blueprints and additional context.
|
|
17
17
|
*/
|
|
18
|
-
// TODO(burdon): Name?
|
|
19
18
|
export const Routine = Schema.Struct({
|
|
20
|
-
/**
|
|
21
|
-
* Name of the routine.
|
|
22
|
-
*/
|
|
23
19
|
name: Schema.optional(Schema.String),
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Description of the routine's purpose and functionality.
|
|
27
|
-
* Allows AI agents to execute routines automatically as tools.
|
|
28
|
-
*/
|
|
29
20
|
description: Schema.optional(Schema.String),
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
/**
|
|
37
|
-
* Output schema of the routine.
|
|
38
|
-
*/
|
|
39
|
-
output: JsonSchema.JsonSchema.pipe(Annotation.FormInputAnnotation.set(false)),
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Natural language instructions for the routine.
|
|
43
|
-
* These should provide concrete course of action for the AI to follow.
|
|
44
|
-
*/
|
|
21
|
+
input: JsonSchema.JsonSchema.pipe(Annotation.FormInputAnnotation.set(false)).annotations({
|
|
22
|
+
description: 'Input schema',
|
|
23
|
+
}),
|
|
24
|
+
output: JsonSchema.JsonSchema.pipe(Annotation.FormInputAnnotation.set(false)).annotations({
|
|
25
|
+
description: 'Output schema',
|
|
26
|
+
}),
|
|
45
27
|
// TODO(burdon): Form editor.
|
|
46
|
-
instructions: Template.Template.pipe(Annotation.FormInputAnnotation.set(false))
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
* Blueprints that the routine may utilize.
|
|
50
|
-
*/
|
|
28
|
+
instructions: Template.Template.pipe(Annotation.FormInputAnnotation.set(false)).annotations({
|
|
29
|
+
description: 'Agent instructions',
|
|
30
|
+
}),
|
|
51
31
|
blueprints: Schema.Array(Ref.Ref(Blueprint.Blueprint)),
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Additional context that the routine may utilize.
|
|
55
|
-
*/
|
|
32
|
+
// TODO(burdon): Change to map?
|
|
56
33
|
context: Schema.Array(Schema.Any).pipe(Annotation.FormInputAnnotation.set(false)),
|
|
57
34
|
}).pipe(
|
|
58
35
|
Type.object({
|
|
@@ -68,7 +45,7 @@ export const Routine = Schema.Struct({
|
|
|
68
45
|
|
|
69
46
|
export interface Routine extends Schema.Schema.Type<typeof Routine> {}
|
|
70
47
|
|
|
71
|
-
export
|
|
48
|
+
export type MakeOptions = {
|
|
72
49
|
name?: string;
|
|
73
50
|
description?: string;
|
|
74
51
|
input?: Schema.Schema.AnyNoContext;
|
|
@@ -76,13 +53,23 @@ export const make = (params: {
|
|
|
76
53
|
instructions?: string;
|
|
77
54
|
blueprints?: Ref.Ref<Blueprint.Blueprint>[];
|
|
78
55
|
context?: any[];
|
|
79
|
-
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export const make = ({
|
|
59
|
+
name,
|
|
60
|
+
description,
|
|
61
|
+
input,
|
|
62
|
+
output,
|
|
63
|
+
instructions,
|
|
64
|
+
blueprints = [],
|
|
65
|
+
context = [],
|
|
66
|
+
}: MakeOptions): Routine =>
|
|
80
67
|
Obj.make(Routine, {
|
|
81
|
-
name
|
|
82
|
-
description
|
|
83
|
-
input: JsonSchema.toJsonSchema(
|
|
84
|
-
output: JsonSchema.toJsonSchema(
|
|
85
|
-
instructions: Template.make({ source:
|
|
86
|
-
blueprints
|
|
87
|
-
context
|
|
68
|
+
name,
|
|
69
|
+
description,
|
|
70
|
+
input: JsonSchema.toJsonSchema(input ?? Schema.Void),
|
|
71
|
+
output: JsonSchema.toJsonSchema(output ?? Schema.Void),
|
|
72
|
+
instructions: Template.make({ source: instructions }),
|
|
73
|
+
blueprints,
|
|
74
|
+
context,
|
|
88
75
|
});
|
package/src/ServiceResolver.ts
CHANGED
|
@@ -148,6 +148,26 @@ export const layerRequirements = <const Tags extends readonly Context.Tag<any, a
|
|
|
148
148
|
): Layer.Layer<ServiceResolver, never, Context.Tag.Identifier<Tags[number]>> =>
|
|
149
149
|
Layer.effect(ServiceResolver, fromRequirements(...tags));
|
|
150
150
|
|
|
151
|
+
/**
|
|
152
|
+
* Build a {@link Layer} that materialises the requested services by calling
|
|
153
|
+
* {@link resolveAll} against the {@link ServiceResolver} currently in context.
|
|
154
|
+
*
|
|
155
|
+
* The returned layer manages its own {@link Scope.Scope} and requires only a
|
|
156
|
+
* {@link ServiceResolver} (typically supplied by the process-manager runtime).
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```ts
|
|
160
|
+
* processManagerRuntime.runPromise(
|
|
161
|
+
* myEffect.pipe(Effect.provide(ServiceResolver.provide({ space }, Database.Service, QueueService))),
|
|
162
|
+
* );
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
export const provide = <const Tags extends readonly Context.Tag<any, any>[]>(
|
|
166
|
+
context: ResolutionContext,
|
|
167
|
+
...tags: Tags
|
|
168
|
+
): Layer.Layer<Context.Tag.Identifier<Tags[number]>, ServiceNotAvailableError, ServiceResolver> =>
|
|
169
|
+
Layer.scopedContext(resolveAll(tags, context));
|
|
170
|
+
|
|
151
171
|
/**
|
|
152
172
|
* Compose multiple resolvers left to right. Earlier resolvers take precedence:
|
|
153
173
|
* the first resolver that can satisfy a tag wins.
|
package/src/Trace.ts
CHANGED
|
@@ -76,6 +76,25 @@ export const isOfType = <T, E extends Event>(eventType: EventType<T>, event: E):
|
|
|
76
76
|
return event.type === eventType.key;
|
|
77
77
|
};
|
|
78
78
|
|
|
79
|
+
/**
|
|
80
|
+
* Extensible name informing which runtime executed the code that produced the event.
|
|
81
|
+
*/
|
|
82
|
+
export const RuntimeName = Schema.String.pipe(Schema.brand('@dxos/compute/Trace/RuntimeName'));
|
|
83
|
+
export type RuntimeName = Schema.Schema.Type<typeof RuntimeName>;
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Common runtime names.
|
|
87
|
+
*/
|
|
88
|
+
export const CommonRuntimeName = {
|
|
89
|
+
/**
|
|
90
|
+
* Web app / CLI / Desktop app / Mobile app.
|
|
91
|
+
*/
|
|
92
|
+
local: RuntimeName.make('local'),
|
|
93
|
+
edgeIntrinsic: RuntimeName.make('edge-intrinsic'),
|
|
94
|
+
edgeWorkerLoader: RuntimeName.make('edge-worker-loader'),
|
|
95
|
+
edgeWorkerForPlatforms: RuntimeName.make('edge-worker-for-platforms'),
|
|
96
|
+
};
|
|
97
|
+
|
|
79
98
|
/**
|
|
80
99
|
* Metadata on the context of a trace message.
|
|
81
100
|
*/
|
|
@@ -85,6 +104,12 @@ export const Meta = Schema.Struct({
|
|
|
85
104
|
parentPid: Schema.optional(Schema.String),
|
|
86
105
|
processName: Schema.optional(Schema.String),
|
|
87
106
|
|
|
107
|
+
/**
|
|
108
|
+
* Space the message was produced in.
|
|
109
|
+
* Stored as a string to avoid circular dependency on `@dxos/keys`.
|
|
110
|
+
*/
|
|
111
|
+
space: Schema.optional(Schema.String),
|
|
112
|
+
|
|
88
113
|
/**
|
|
89
114
|
* ID of the conversation feed object if present.
|
|
90
115
|
*/
|
|
@@ -99,9 +124,22 @@ export const Meta = Schema.Struct({
|
|
|
99
124
|
* ID of the tool call that created the current process.
|
|
100
125
|
*/
|
|
101
126
|
toolCallId: Schema.optional(Schema.String),
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Extensible name informing which runtime executed the code that produced the event.
|
|
130
|
+
*/
|
|
131
|
+
runtimeName: Schema.optional(RuntimeName),
|
|
102
132
|
});
|
|
103
133
|
export interface Meta extends Schema.Schema.Type<typeof Meta> {}
|
|
104
134
|
|
|
135
|
+
/**
|
|
136
|
+
* Checks if a runtime is an edge runtime.
|
|
137
|
+
*/
|
|
138
|
+
export const isEdgeRuntime = (name: RuntimeName): boolean =>
|
|
139
|
+
name === CommonRuntimeName.edgeIntrinsic ||
|
|
140
|
+
name === CommonRuntimeName.edgeWorkerLoader ||
|
|
141
|
+
name === CommonRuntimeName.edgeWorkerForPlatforms;
|
|
142
|
+
|
|
105
143
|
/**
|
|
106
144
|
* Envelope for a set of events.
|
|
107
145
|
*/
|
|
@@ -125,6 +163,26 @@ export const Message = MessageData.pipe(
|
|
|
125
163
|
);
|
|
126
164
|
export interface Message extends Schema.Schema.Type<typeof Message> {}
|
|
127
165
|
|
|
166
|
+
/**
|
|
167
|
+
* Flattened representation of a signle event in a trace message.
|
|
168
|
+
* Events are stored in batched messages for efficiency, but flat representation is more convenient for consumption.
|
|
169
|
+
*/
|
|
170
|
+
export interface FlatEvent extends Event {
|
|
171
|
+
readonly meta: Meta;
|
|
172
|
+
readonly isEphemeral: boolean;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Flattens a trace message into a list of flat events.
|
|
177
|
+
*/
|
|
178
|
+
export const flatten = (message: Message): FlatEvent[] => {
|
|
179
|
+
return message.events.map((event) => ({
|
|
180
|
+
...event,
|
|
181
|
+
meta: message.meta,
|
|
182
|
+
isEphemeral: message.isEphemeral,
|
|
183
|
+
}));
|
|
184
|
+
};
|
|
185
|
+
|
|
128
186
|
/**
|
|
129
187
|
* Sink for complete trace messages.
|
|
130
188
|
*/
|
|
@@ -145,9 +203,11 @@ export const noopWriter: TraceWriter = {
|
|
|
145
203
|
|
|
146
204
|
export const writerLayerNoop: Layer.Layer<TraceService> = Layer.succeed(TraceService, noopWriter);
|
|
147
205
|
|
|
148
|
-
export const
|
|
206
|
+
export const noopSink: Sink = {
|
|
149
207
|
write: () => {},
|
|
150
|
-
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
export const layerNoop: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, noopSink);
|
|
151
211
|
|
|
152
212
|
export const layerConsole: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, {
|
|
153
213
|
write: (message) => {
|
|
@@ -155,18 +215,60 @@ export const layerConsole: Layer.Layer<TraceSink> = Layer.succeed(TraceSink, {
|
|
|
155
215
|
},
|
|
156
216
|
});
|
|
157
217
|
|
|
158
|
-
|
|
218
|
+
/**
|
|
219
|
+
* Merge a set of sinks into a single sink.
|
|
220
|
+
*
|
|
221
|
+
* Each message is forwarded to every sink in order. Failures in one sink do not
|
|
222
|
+
* prevent downstream sinks from receiving the message.
|
|
223
|
+
*/
|
|
224
|
+
export const mergeSinks = (sinks: readonly Sink[]): Sink => {
|
|
225
|
+
if (sinks.length === 0) {
|
|
226
|
+
return noopSink;
|
|
227
|
+
}
|
|
228
|
+
// Intentionally no singleton fast path: the guarded wrapper is the
|
|
229
|
+
// contract of `mergeSinks`, so a throwing sink is always caught and
|
|
230
|
+
// logged regardless of how many sinks were passed in.
|
|
231
|
+
return {
|
|
232
|
+
write: (message) => {
|
|
233
|
+
for (const sink of sinks) {
|
|
234
|
+
try {
|
|
235
|
+
sink.write(message);
|
|
236
|
+
} catch (err) {
|
|
237
|
+
// Intentional: do not let one sink break the chain.
|
|
238
|
+
// eslint-disable-next-line no-console
|
|
239
|
+
console.error('[trace] sink.write threw', err);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Builds a {@link TraceService} layer that wraps each `write` into a fresh {@link Message}
|
|
248
|
+
* and forwards it to the provided {@link TraceSink}. Intended for tests and lightweight
|
|
249
|
+
* fixtures.
|
|
250
|
+
*
|
|
251
|
+
* Options:
|
|
252
|
+
* - `meta`: stamped on every emitted message (defaults to `{}`).
|
|
253
|
+
* - `clock`: timestamp source (defaults to {@link Date.now}). Pass a monotonic counter
|
|
254
|
+
* in tests to make event ordering deterministic when many writes happen in the same
|
|
255
|
+
* millisecond.
|
|
256
|
+
*/
|
|
257
|
+
export const testTraceService = (
|
|
258
|
+
opts: { meta?: Meta; clock?: () => number } = {},
|
|
259
|
+
): Layer.Layer<TraceService, never, TraceSink> =>
|
|
159
260
|
Layer.effect(
|
|
160
261
|
TraceService,
|
|
161
262
|
Effect.gen(function* () {
|
|
162
263
|
const sink = yield* TraceSink;
|
|
264
|
+
const clock = opts.clock ?? Date.now;
|
|
163
265
|
return {
|
|
164
266
|
write: (event, data) => {
|
|
165
267
|
sink.write(
|
|
166
268
|
Obj.make(Message, {
|
|
167
269
|
meta: opts.meta ?? {},
|
|
168
270
|
isEphemeral: event.isEphemeral,
|
|
169
|
-
events: [{ type: event.key, timestamp:
|
|
271
|
+
events: [{ type: event.key, timestamp: clock(), data }],
|
|
170
272
|
}),
|
|
171
273
|
);
|
|
172
274
|
},
|
|
@@ -213,6 +315,41 @@ export const OperationEnd = EventType('operation.end', {
|
|
|
213
315
|
isEphemeral: false,
|
|
214
316
|
});
|
|
215
317
|
|
|
318
|
+
/**
|
|
319
|
+
* Operation input. Emitted as an ephemeral event alongside {@link OperationStart}
|
|
320
|
+
* so subscribers (such as the undo/redo history tracker) can observe the raw
|
|
321
|
+
* input payload without persisting it to long-lived sinks.
|
|
322
|
+
*/
|
|
323
|
+
export const OperationInput = EventType('operation.input', {
|
|
324
|
+
schema: Schema.Struct({
|
|
325
|
+
/** Operation key. */
|
|
326
|
+
key: Schema.String,
|
|
327
|
+
/** Human-readable operation name. */
|
|
328
|
+
name: Schema.optional(Schema.String),
|
|
329
|
+
/** Raw operation input. Shape determined by the operation definition. */
|
|
330
|
+
input: Schema.Unknown,
|
|
331
|
+
}),
|
|
332
|
+
isEphemeral: true,
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Operation output. Emitted as an ephemeral event just before
|
|
337
|
+
* {@link OperationEnd} for successful invocations so subscribers (such as the
|
|
338
|
+
* undo/redo history tracker) can observe the raw output payload without
|
|
339
|
+
* persisting it to long-lived sinks.
|
|
340
|
+
*/
|
|
341
|
+
export const OperationOutput = EventType('operation.output', {
|
|
342
|
+
schema: Schema.Struct({
|
|
343
|
+
/** Operation key. */
|
|
344
|
+
key: Schema.String,
|
|
345
|
+
/** Human-readable operation name. */
|
|
346
|
+
name: Schema.optional(Schema.String),
|
|
347
|
+
/** Raw operation output. Shape determined by the operation definition. */
|
|
348
|
+
output: Schema.Unknown,
|
|
349
|
+
}),
|
|
350
|
+
isEphemeral: true,
|
|
351
|
+
});
|
|
352
|
+
|
|
216
353
|
/**
|
|
217
354
|
* Human-readable status update emitted by an agent or operation.
|
|
218
355
|
*/
|
package/src/Trigger.ts
CHANGED
|
@@ -45,9 +45,9 @@ export type QueueSpec = Schema.Schema.Type<typeof QueueSpec>;
|
|
|
45
45
|
/**
|
|
46
46
|
* Construct a Queue trigger spec from a queue DXN string.
|
|
47
47
|
*/
|
|
48
|
-
export const specQueue = (
|
|
48
|
+
export const specQueue = (queueDXN: string): QueueSpec => ({
|
|
49
49
|
kind: 'queue',
|
|
50
|
-
queue:
|
|
50
|
+
queue: queueDXN,
|
|
51
51
|
});
|
|
52
52
|
|
|
53
53
|
/**
|
package/src/index.ts
CHANGED
|
@@ -7,6 +7,7 @@ export * from './errors';
|
|
|
7
7
|
export * as Blueprint from './Blueprint';
|
|
8
8
|
export * as Credential from './Credential';
|
|
9
9
|
export * as McpServer from './McpServer';
|
|
10
|
+
export * as LayerSpec from './LayerSpec';
|
|
10
11
|
export * as Operation from './Operation';
|
|
11
12
|
export * as OperationHandlerSet from './OperationHandlerSet';
|
|
12
13
|
export * as OperationRegistry from './OperationRegistry';
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/errors.ts", "../../../src/OperationHandlerSet.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError, type BaseErrorOptions } from '@dxos/errors';\n\n// Errors from @dxos/operation.\n\nexport class InvokerNotInitializedError extends BaseError.extend(\n 'InvokerNotInitializedError',\n 'Invoker not initialized',\n) {\n constructor() {\n super();\n }\n}\n\nexport class NoHandlerError extends BaseError.extend('NoHandlerError', 'No handler found for operation. ') {\n constructor(operationKey: string) {\n super({ context: { operationKey } });\n }\n}\n\n// Errors from @dxos/functions.\n\nexport class ServiceNotAvailableError extends BaseError.extend('ServiceNotAvailable', 'Service not available') {\n constructor(service: string, options?: Omit<BaseErrorOptions, 'context'>) {\n super({ context: { service }, ...options, message: `Service not available: ${service}` });\n }\n}\n\nexport class FunctionNotFoundError extends BaseError.extend('FunctionNotFound', 'Function not found') {\n constructor(functionKey: string, options?: Omit<BaseErrorOptions, 'context'>) {\n super({ context: { function: functionKey }, ...options });\n }\n}\n\nexport class FunctionError extends BaseError.extend('FunctionError', 'Function invocation error') {}\n\nexport class InvalidOperationInputError extends BaseError.extend(\n 'InvalidOperationInput',\n 'Operation input did not match schema',\n) {}\n\nexport class InvalidOperationOutputError extends BaseError.extend(\n 'InvalidOperationOutput',\n 'Operation output did not match schema',\n) {}\n\nexport class TriggerStateNotFoundError extends BaseError.extend('TriggerStateNotFound', 'Trigger state not found') {}\n\n/**\n * Raised when the upstream AI gateway responds with a structured JSON error envelope\n * (`{ \"type\": \"error\", \"error\": { \"type\": ..., \"message\": ... } }`). Surfaces as a typed\n * defect from `FunctionsAiHttpClient`, bypassing `@effect/ai`'s generic `HttpResponseError`\n * wrapping so callers can match on the error class directly.\n */\nexport class FunctionsAiUpstreamError extends BaseError.extend(\n 'FunctionsAiUpstreamError',\n 'Upstream AI service returned an error',\n) {}\n\n/**\n * Specialized `FunctionsAiUpstreamError` for the memoization layer: the recorded fixture for a\n * given cache key was not found and `ALLOW_LLM_GENERATION` is unset. The `cacheKey` is exposed\n * via `context.cacheKey` to make regeneration straightforward.\n */\nexport class FunctionsAiMemoizationMissError extends BaseError.extend(\n 'FunctionsAiMemoizationMissError',\n 'No memoized AI conversation found for the given cache key',\n) {}\n", "//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { assertArgument } from '@dxos/invariant';\n\nimport { NoHandlerError } from './errors';\nimport type * as Operation from './Operation';\n\nexport const TypeId = '~@dxos/operation/OperationHandlerSet' as const;\nexport type TypeId = typeof TypeId;\n\nexport interface OperationHandlerSet {\n [TypeId]: TypeId;\n\n readonly handlers: Effect.Effect<Operation.WithHandler<Operation.Definition.Any>[]>;\n\n getHandlers(): Promise<Operation.WithHandler<Operation.Definition.Any>[]>;\n}\n\nexport const isOperationHandlerSet = (value: unknown): value is OperationHandlerSet => {\n return typeof value === 'object' && value !== null && TypeId in value;\n};\n\nexport const empty: OperationHandlerSet = {\n [TypeId]: TypeId,\n handlers: Effect.succeed([]),\n getHandlers: () => Promise.resolve([]),\n};\n\n/**\n * Creates a new operation handler set from a list of handlers.\n *\n * @example\n * ```ts\n * const set = OperationHandlerSet.make(\n * Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.Void }), (input) => Effect.succeed({})),\n * Operation.withHandler(Operation.make({ input: Schema.Void, output: Schema.Void }), (input) => Effect.succeed({})),\n * );\n * ```\n */\nexport const make = (...handlers: Operation.WithHandler<Operation.Definition.Any>[]): OperationHandlerSet => {\n return async(() => Promise.resolve(handlers));\n};\n\nexport const async = (\n getHandlers: () => Promise<Operation.WithHandler<Operation.Definition.Any>[]>,\n): OperationHandlerSet => {\n // NOTE: Re-runing async module imports has a big performance penalty in Chrome.\n let promise: Promise<Operation.WithHandler<Operation.Definition.Any>[]> | null = null;\n const getHandlersCached = () => {\n if (!promise) {\n promise = getHandlers();\n }\n return promise;\n };\n return {\n [TypeId]: TypeId,\n getHandlers,\n handlers: Effect.promise(getHandlersCached),\n };\n};\n\n/**\n * Merges multiple operation handler sets into a single set.\n *\n */\nexport const merge = (...sets: OperationHandlerSet[]): OperationHandlerSet => {\n assertArgument(sets.every(isOperationHandlerSet), 'sets', 'sets must be an array of OperationHandlerSet');\n return async(() => Promise.all(sets.map((set) => set.getHandlers())).then((handlers) => handlers.flat()));\n};\n\n/**\n * Creates a new operation handler set from a list of lazy-loaded modules.\n *\n * @example\n * ```ts\n * const set = OperationHandlerSet.lazy(\n * () => import('./my-handler'),\n * () => import('./my-other-handler'),\n * );\n * ```\n */\nexport const lazy = (\n ...modules: (() => Promise<{ default: Operation.WithHandler<Operation.Definition.Any> }>)[]\n): OperationHandlerSet => {\n return async(() => Promise.all(modules.map((module) => module().then(({ default: handler }) => handler))));\n};\n\n/**\n * Gets a handler for an operation by definition.\n */\nexport const getHandler = <const Op extends Operation.Definition.Any>(\n set: OperationHandlerSet,\n definition: Op,\n): Effect.Effect<Operation.WithHandler<Op>, NoHandlerError> =>\n Effect.gen(function* () {\n const handlers = yield* set.handlers;\n const handler = handlers.find((handler) => handler.meta.key === definition.meta.key);\n if (!handler) {\n return yield* Effect.fail(new NoHandlerError(definition.meta.key));\n }\n return handler as any;\n });\n\n/**\n * Gets a handler for an operation by key.\n */\nexport const getHandlerByKey = (\n set: OperationHandlerSet,\n key: string,\n): Effect.Effect<Operation.WithHandler<Operation.Definition.Any>, NoHandlerError> =>\n Effect.gen(function* () {\n const handlers = yield* set.handlers;\n const handler = handlers.find((handler) => handler.meta.key === key);\n if (!handler) {\n return yield* Effect.fail(new NoHandlerError(key));\n }\n return handler as any;\n });\n\nexport class OperationHandlerProvider extends Context.Tag('@dxos/operation/OperationHandlerProvider')<\n OperationHandlerProvider,\n OperationHandlerSet\n>() {}\n\nexport const provide = (handlers: OperationHandlerSet): Layer.Layer<OperationHandlerProvider, never, never> =>\n Layer.succeed(OperationHandlerProvider, handlers);\n"],
|
|
5
|
-
"mappings": ";;;;;AAIA,SAASA,iBAAwC;AAI1C,IAAMC,6BAAN,cAAyCD,UAAUE,OACxD,8BACA,yBAAA,EAAA;EAEA,cAAc;AACZ,UAAK;EACP;AACF;AAEO,IAAMC,iBAAN,cAA6BH,UAAUE,OAAO,kBAAkB,kCAAA,EAAA;EACrE,YAAYE,cAAsB;AAChC,UAAM;MAAEC,SAAS;QAAED;MAAa;IAAE,CAAA;EACpC;AACF;AAIO,IAAME,2BAAN,cAAuCN,UAAUE,OAAO,uBAAuB,uBAAA,EAAA;EACpF,YAAYK,SAAiBC,SAA6C;AACxE,UAAM;MAAEH,SAAS;QAAEE;MAAQ;MAAG,GAAGC;MAASC,SAAS,0BAA0BF,OAAAA;IAAU,CAAA;EACzF;AACF;AAEO,IAAMG,wBAAN,cAAoCV,UAAUE,OAAO,oBAAoB,oBAAA,EAAA;EAC9E,YAAYS,aAAqBH,SAA6C;AAC5E,UAAM;MAAEH,SAAS;QAAEO,UAAUD;MAAY;MAAG,GAAGH;IAAQ,CAAA;EACzD;AACF;AAEO,IAAMK,gBAAN,cAA4Bb,UAAUE,OAAO,iBAAiB,2BAAA,EAAA;AAA8B;AAE5F,IAAMY,6BAAN,cAAyCd,UAAUE,OACxD,yBACA,sCAAA,EAAA;AACC;AAEI,IAAMa,8BAAN,cAA0Cf,UAAUE,OACzD,0BACA,uCAAA,EAAA;AACC;AAEI,IAAMc,4BAAN,cAAwChB,UAAUE,OAAO,wBAAwB,yBAAA,EAAA;AAA4B;AAQ7G,IAAMe,2BAAN,cAAuCjB,UAAUE,OACtD,4BACA,uCAAA,EAAA;AACC;AAOI,IAAMgB,kCAAN,cAA8ClB,UAAUE,OAC7D,mCACA,2DA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SAAS0B,KAAK,CAACJ,aAAYA,SAAQK,KAAKC,QAAQJ,WAAWG,KAAKC,GAAG;AACnF,MAAI,CAACN,SAAS;AACZ,WAAO,OAAcO,YAAK,IAAIC,eAAeN,WAAWG,KAAKC,GAAG,CAAA;EAClE;AACA,SAAON;AACT,CAAA;AAKK,IAAMS,kBAAkB,CAC7BhB,KACAa,QAEOH,WAAI,aAAA;AACT,QAAMzB,WAAW,OAAOe,IAAIf;AAC5B,QAAMsB,UAAUtB,SAAS0B,KAAK,CAACJ,aAAYA,SAAQK,KAAKC,QAAQA,GAAAA;AAChE,MAAI,CAACN,SAAS;AACZ,WAAO,OAAcO,YAAK,IAAIC,eAAeF,GAAAA,CAAAA;EAC/C;AACA,SAAON;AACT,CAAA;AAEK,IAAMU,2BAAN,cAA+CC,YAAI,0CAAA,EAAA,EAAA;AAGrD;AAEE,IAAMC,UAAU,CAAClC,aAChBC,cAAQ+B,0BAA0BhC,QAAAA;",
|
|
6
|
-
"names": ["BaseError", "InvokerNotInitializedError", "extend", "NoHandlerError", "operationKey", "context", "ServiceNotAvailableError", "service", "options", "message", "FunctionNotFoundError", "functionKey", "function", "FunctionError", "InvalidOperationInputError", "InvalidOperationOutputError", "TriggerStateNotFoundError", "FunctionsAiUpstreamError", "FunctionsAiMemoizationMissError", "Context", "Effect", "Layer", "assertArgument", "TypeId", "isOperationHandlerSet", "value", "empty", "handlers", "succeed", "getHandlers", "Promise", "resolve", "make", "async", "promise", "getHandlersCached", "merge", "sets", "assertArgument", "every", "all", "map", "set", "then", "flat", "lazy", "modules", "module", "default", "handler", "getHandler", "definition", "gen", "find", "meta", "key", "fail", "NoHandlerError", "getHandlerByKey", "OperationHandlerProvider", "Tag", "provide"]
|
|
7
|
-
}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../src/Operation.ts"],
|
|
4
|
-
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Pipeable from 'effect/Pipeable';\nimport * as Schema$ from 'effect/Schema';\nimport type * as Types from 'effect/Types';\n\nimport { Annotation, JsonSchema, Obj, Ref, Type, type DXN, type Key } from '@dxos/echo';\n\nimport type { NoHandlerError } from './errors';\nimport type { Operation } from './index';\n\n/**\n * Schema type that accepts any Encoded form but requires no Context.\n * This allows ECHO object schemas where Type !== Encoded due to [KindId] symbol.\n */\ntype Schema<T> = Schema$.Schema<T, any, never>;\n\nexport const DefinitionTypeId = '~@dxos/operation/OperationDefinition' as const;\nexport type DefinitionTypeId = typeof DefinitionTypeId;\n\n/**\n * Serializable definition of an Operation.\n * Contains schema and metadata, but no runtime logic.\n */\nexport interface Definition<I, O, S = any> extends Pipeable.Pipeable, Definition.Variance<I, O, S> {\n /**\n * Input schema for the operation.\n */\n readonly input: Schema<I>;\n /**\n * Output schema for the operation.\n */\n readonly output: Schema<O>;\n\n readonly meta: {\n readonly key: string;\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n /**\n * Deployment ID for remote invocation.\n * Assigned by the EDGE function service when deployed.\n */\n readonly deployedId?: string;\n };\n\n /**\n * Execution mode for the operation.\n * - 'sync': Operation completes synchronously (fast, UI-blocking acceptable).\n * - 'async': Operation may take time (should not block UI).\n */\n readonly executionMode: 'sync' | 'async';\n\n /**\n * ECHO types the operation uses.\n * Ensures types are available when the operation is executed remotely.\n */\n readonly types: readonly Type.AnyEntity[];\n\n /**\n * Effect services required by this operation.\n * These services will be automatically provided to the handler at invocation time.\n */\n readonly services: readonly Context.Tag<any, any>[];\n}\n\n/**\n * Namespace for OperationDefinition helper types.\n */\nexport declare namespace Definition {\n export interface Variance<I, O, S> {\n [DefinitionTypeId]: {\n readonly _Input: Types.Contravariant<I>;\n readonly _Output: Types.Covariant<O>;\n readonly _Services: Types.Covariant<S>;\n };\n }\n\n /**\n * Any operation definition, regardless of input/output types.\n */\n export type Any = Definition<any, any, any>;\n\n /**\n * Extract the input type from an operation definition.\n */\n export type Input<T extends Any> = T extends Variance<infer I, infer _O, infer _S> ? I : never;\n\n /**\n * Extract the output type from an operation definition.\n */\n export type Output<T extends Any> = T extends Variance<infer _I, infer O, infer _S> ? O : never;\n\n /**\n * Extract the service identifier types from an operation's services array.\n * Returns `never` if the operation has no services declared.\n */\n export type Services<T extends Any> = T extends Variance<infer _I, infer _O, infer S> ? S : never;\n\n export type HandlerType<T extends Any> =\n T extends Variance<infer I, infer O, infer S> ? Handler<I, O, any, S> : never;\n}\n\n/**\n * Runtime handler for an Operation.\n */\nexport type Handler<I, O, E = Error, R = never> = (input: I) => Effect.Effect<O, E, R>;\n\nexport type WithHandler<T extends Definition.Any> = T & {\n handler: Definition.HandlerType<T>;\n};\n\n/**\n * Checks if a value is an operation definition.\n */\nexport const isOperationDefinition = (value: unknown): value is Definition.Any => {\n return typeof value === 'object' && value !== null && DefinitionTypeId in value;\n};\n\n/**\n * Checks if a value is an operation with a handler.\n */\nexport const isOperationWithHandler = (value: unknown): value is WithHandler<Definition.Any> => {\n return isOperationDefinition(value) && 'handler' in value;\n};\n\n/**a\n * Props for creating an Operation definition.\n * Derived from OperationDefinition with executionMode made optional (defaults to 'async').\n */\nexport type Props<I, O> = Omit<Definition<I, O>, DefinitionTypeId | 'pipe' | 'executionMode' | 'types' | 'services'> & {\n readonly executionMode?: 'sync' | 'async';\n readonly types?: Definition<I, O>['types'];\n readonly services?: Definition<I, O>['services'];\n};\n\n/**\n * Creates a new Operation definition.\n * Applies default executionMode of 'async' if not specified.\n * The returned type preserves the literal types of props (including services).\n */\nexport const make = <const P extends Types.NoExcessProperties<Props<any, any>, P>>(\n props: P,\n): Definition<\n Schema$.Schema.Type<P['input']>,\n Schema$.Schema.Type<P['output']>,\n Context.Tag.Identifier<NonNullable<P['services']>[number]>\n> => {\n return {\n [DefinitionTypeId]: {},\n ...props,\n executionMode: props.executionMode ?? 'async',\n types: props.types ?? [],\n services: props.services ?? [],\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n },\n } as any;\n};\n\n/**\n * Marks an operation as intrinsic — provided directly by the DXOS platform runtime rather than\n * deployed as a user function. The `intrinsic:<key>` deployedId routes invocations to the\n * built-in implementation registered with the runtime.\n */\nexport const intrinsic = <const O extends Operation.Definition.Any>(op: O): O => {\n return {\n ...op,\n meta: {\n ...op.meta,\n deployedId: `intrinsic:${op.meta.key}`,\n },\n };\n};\n\n/**\n * Attaches a handler to an Operation definition.\n * The handler may use any services declared in the operation, plus Operation.Service (always available).\n * Dual API: can be called directly or used in a pipe.\n *\n * @example\n * ```ts\n * const MyOp = Operation.make({\n * input: Schema.Void,\n * output: Schema.Void,\n * meta: { key: 'my-op' },\n * services: [DatabaseService],\n * });\n *\n * // Direct call - handler can use DatabaseService\n * const op = Operation.withHandler(MyOp, (input) =>\n * Effect.gen(function* () {\n * const db = yield* DatabaseService;\n * return {};\n * }),\n * );\n *\n * // Piped call\n * const op = MyOp.pipe(Operation.withHandler((input) => Effect.succeed({})));\n * ```\n */\nexport const withHandler: {\n <Def extends Definition<any, any>, E = never>(\n handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n ): (op: Def) => WithHandler<Def>;\n <Def extends Definition<any, any>, E = never>(\n op: Def,\n handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n ): WithHandler<Def>;\n} = <Def extends Definition<any, any>, E = never>(\n opOrHandler: Def | Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n handler?: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n): WithHandler<Def> => {\n // If called with just handler (piped usage).\n if (handler === undefined) {\n const handlerFn = opOrHandler as Handler<\n Definition.Input<Def>,\n Definition.Output<Def>,\n E,\n Definition.Services<Def> | Service\n >;\n return ((op: Def) => ({\n ...op,\n handler: handlerFn,\n })) as any;\n }\n\n // If called with both op and handler (direct usage).\n const op = opOrHandler as Def;\n return {\n ...op,\n handler,\n } as any;\n};\n\n/**\n * Helper to make the handler type opaque.\n * Workaround for TypeScript's inability to infer the handler type from the operation definition:\n * ```\n * error TS2742: The inferred type of 'default' cannot be named without a reference.\n * ```\n *\n * Most of the time the exact handler type is not needed.\n *\n * @example\n * ```ts\n * const MyOp = Operation.make({\n * input: Schema.Void,\n * output: Schema.Void,\n * meta: { key: 'my-op' },\n * services: [DatabaseService],\n * });\n *\n * export default MyOp.pipe(\n * Operation.withHandler(\n * Effect.fn(function* (input) {\n * return { result: 'ok' };\n * }),\n * ),\n * Operation.opaqueHandler,\n * );\n * ```\n */\nexport const opaqueHandler = <T extends Operation.Definition.Any>(\n handler: Operation.WithHandler<T>,\n): Operation.WithHandler<Operation.Definition.Any> => handler;\n\n//\n// Invocation Interfaces\n//\n\n/**\n * Local invocation of an operation.\n */\nexport type Invoke = <I, O, E>(op: Definition<I, O>, input: I) => Effect.Effect<O, E>;\n\n/**\n * Remote invocation of an operation.\n */\nexport type InvokeRemote = <I, O, E>(\n op: Definition<I, O>,\n input: I,\n options?: { timeout?: number },\n) => Effect.Effect<O, E>;\n\n/**\n * Database record of an operation.\n */\nexport const PersistentOperation = Schema$.Struct({\n /**\n * Global registry ID.\n * NOTE: The `key` property refers to the original registry entry.\n */\n // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.\n // TODO(dmaretskyi): Consider making it part of ECHO meta.\n // TODO(dmaretskyi): Make required.\n key: Schema$.optional(Schema$.String).annotations({\n description: 'Unique registration key for the blueprint',\n }),\n\n name: Schema$.NonEmptyString,\n version: Schema$.String,\n\n description: Schema$.optional(Schema$.String),\n\n /**\n * ISO date string of the last deployment.\n */\n updated: Schema$.optional(Schema$.String),\n\n // Reference to a source script if it exists within ECHO.\n // TODO(burdon): Don't ref ScriptType directly (core).\n source: Schema$.optional(Ref.Ref(Obj.Unknown)),\n\n inputSchema: Schema$.optional(JsonSchema.JsonSchema),\n outputSchema: Schema$.optional(JsonSchema.JsonSchema),\n\n /**\n * List of required services.\n * Match the Context.Tag keys of the FunctionServices variants.\n */\n services: Schema$.optional(Schema$.Array(Schema$.String)),\n\n // Local binding to a function name.\n // TODO(dmaretskyi): Add this field to Operation.Definition.\n binding: Schema$.optional(Schema$.String),\n}).pipe(\n // TODO(dmaretskyi): Keep typename as 'org.dxos.type.function' (not 'operation') to maintain\n // backward compatibility with existing data and avoid requiring data migration.\n Type.object({\n typename: 'org.dxos.type.function',\n version: '0.1.0',\n }),\n Annotation.LabelAnnotation.set(['name']),\n Annotation.IconAnnotation.set({ icon: 'ph--function--regular', hue: 'blue' }),\n Annotation.SystemTypeAnnotation.set(true),\n);\nexport interface PersistentOperation extends Schema$.Schema.Type<typeof PersistentOperation> {}\n\nconst FUNCTION_META_KEY = 'org.dxos.service.function';\n\n/**\n * Serialize an operation definition to a persistent operation record.\n */\nexport const serialize = (operation: Definition.Any): PersistentOperation => {\n return Obj.make(PersistentOperation, {\n [Obj.Meta]: {\n keys: operation.meta.deployedId ? [{ source: FUNCTION_META_KEY, id: operation.meta.deployedId }] : [],\n },\n key: operation.meta.key,\n name: operation.meta.name ?? '',\n version: operation.meta.version ?? '0.0.0',\n description: operation.meta.description,\n updated: undefined,\n source: undefined,\n inputSchema: JsonSchema.toJsonSchema(operation.input),\n outputSchema: JsonSchema.toJsonSchema(operation.output),\n services: operation.services.map((service) => service.key),\n });\n};\n\n/**\n * Deserialize a persistent operation record to an operation definition.\n */\nexport const deserialize = (record: PersistentOperation): Definition.Any => {\n // Extract deployed function ID from ECHO meta keys (matches FUNCTIONS_META_KEY in @dxos/functions).\n const deployedId = Obj.getMeta(record).keys.find((key) => key.source === FUNCTION_META_KEY)?.id;\n return make({\n input: record.inputSchema ? JsonSchema.toEffectSchema(record.inputSchema) : Schema$.Unknown,\n output: record.outputSchema ? JsonSchema.toEffectSchema(record.outputSchema) : Schema$.Unknown,\n services: record.services?.map((service) => Context.GenericTag(service)) ?? [],\n executionMode: 'async',\n types: [],\n meta: {\n key: record.key ?? record.name,\n name: record.name,\n version: record.version,\n description: record.description,\n deployedId,\n },\n });\n};\n\n/**\n * Update properties on the target operation record from the source operation record.\n */\nexport const setFrom = (target: PersistentOperation, source: PersistentOperation) => {\n Obj.update(target, (target) => {\n target.key = source.key ?? target.key;\n target.name = source.name ?? target.name;\n target.version = source.version;\n target.description = source.description;\n target.updated = source.updated;\n // TODO(dmaretskyi): A workaround for an ECHO bug.\n target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;\n target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;\n Obj.getMeta(target).keys = JSON.parse(JSON.stringify(Obj.getMeta(source).keys));\n });\n};\n\n/**\n * Options for operation invocation.\n */\nexport interface InvokeOptions {\n /**\n * Space ID to provide database context for the handler.\n */\n spaceId?: Key.SpaceId;\n /**\n * DXN string of the conversation feed (queue).\n * Passed to the process environment so nested operations can resolve AiContextService and related services.\n */\n conversation?: DXN.String;\n /**\n * Optional process-runtime tracing metadata (consumed by `@dxos/functions-runtime` when wired).\n */\n tracing?: unknown;\n}\n\n/**\n * Operation service interface - provides unified access to operation invocation and scheduling.\n * This service is automatically provided to operation handlers.\n */\nexport interface OperationService {\n /**\n * Invoke an operation as an Effect.\n * Returns an Effect that resolves to the operation output.\n */\n invoke: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Effect.Effect<O, NoHandlerError>;\n\n /**\n * Schedule an operation to run as a followup.\n * The followup is tracked and won't be cancelled when the parent operation completes.\n * Returns an Effect that completes immediately after scheduling.\n */\n schedule: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I] : [input: I]\n ) => Effect.Effect<void>;\n\n /**\n * Invoke an operation and return a Promise.\n * Useful for async contexts where Effect is not available.\n */\n invokePromise: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Promise<{ data?: O; error?: Error }>;\n}\n\n/**\n * Context tag for the Operation service.\n * Operation handlers can yield this to invoke other operations or schedule followups.\n *\n * @example\n * ```ts\n * const handler = (input) => Effect.gen(function* () {\n * // Schedule a followup (fire and forget)\n * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });\n *\n * // Invoke another operation\n * return yield* Operation.invoke(OtherOperation, { data: input.data });\n * });\n * ```\n */\n// TODO(dmaretskyi): Rename Operation.Invoker\nexport class Service extends Context.Tag('@dxos/operation/Service')<Service, OperationService>() {}\n\n//\n// Namespace functions - ergonomic access to Operation.Service methods.\n//\n\n/**\n * Invoke an operation as an Effect.\n * Yields the Operation.Service internally.\n *\n * @example\n * ```ts\n * yield* Operation.invoke(MyOperation, { data: 'test' });\n * ```\n */\nexport const invoke = <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n): Effect.Effect<O, NoHandlerError, Service> =>\n Effect.flatMap(Service, (ops) => ops.invoke(op, ...(args as [I, InvokeOptions?]))).pipe(\n Effect.withSpan('Operation.invoke'),\n );\n\n/**\n * Schedule an operation to run as a followup.\n * Yields the Operation.Service internally.\n *\n * @example\n * ```ts\n * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });\n * yield* Operation.schedule(VoidOperation); // input optional when void\n * ```\n */\nexport const schedule = <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I] : [input: I]\n): Effect.Effect<void, never, Service> =>\n Effect.flatMap(Service, (ops) => ops.schedule(op, args[0] as I)).pipe(Effect.withSpan('Operation.schedule'));\n\n/**\n * Provides additional invocation options to all invocations.\n */\nexport const withInvocationOptions = (options: InvokeOptions): Layer.Layer<Service, never, Service> =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const service = yield* Service;\n return Service.of({\n invoke: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.invoke(op, input, { ...options, ...invocationOptions })) as any,\n invokePromise: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.invokePromise(op, input, { ...options, ...invocationOptions })) as any,\n schedule: service.schedule,\n });\n }),\n );\n"],
|
|
5
|
-
"mappings": ";;;;;AAAA;;;;;;;;;;;;;;;;;;AAMA,YAAYA,aAAa;AACzB,YAAYC,YAAY;AACxB,YAAYC,WAAW;AACvB,YAAYC,cAAc;AAC1B,YAAYC,aAAa;AAGzB,SAASC,YAAYC,YAAYC,KAAKC,KAAKC,YAAgC;AAWpE,IAAMC,mBAAmB;AAkGzB,IAAMC,wBAAwB,CAACC,UAAAA;AACpC,SAAO,OAAOA,UAAU,YAAYA,UAAU,QAAQF,oBAAoBE;AAC5E;AAKO,IAAMC,yBAAyB,CAACD,UAAAA;AACrC,SAAOD,sBAAsBC,KAAAA,KAAU,aAAaA;AACtD;AAiBO,IAAME,OAAO,CAClBC,UAAAA;AAMA,SAAO;IACL,CAACL,gBAAAA,GAAmB,CAAC;IACrB,GAAGK;IACHC,eAAeD,MAAMC,iBAAiB;IACtCC,OAAOF,MAAME,SAAS,CAAA;IACtBC,UAAUH,MAAMG,YAAY,CAAA;IAC5BC,OAAAA;AAEE,aAAgBC,uBAAc,MAAMC,SAAAA;IACtC;EACF;AACF;AAOO,IAAMC,YAAY,CAA2CC,OAAAA;AAClE,SAAO;IACL,GAAGA;IACHC,MAAM;MACJ,GAAGD,GAAGC;MACNC,YAAY,aAAaF,GAAGC,KAAKE,GAAG;IACtC;EACF;AACF;AA4BO,IAAMC,cAQT,CACFC,aACAC,YAAAA;AAGA,MAAIA,YAAYC,QAAW;AACzB,UAAMC,YAAYH;AAMlB,WAAQ,CAACL,SAAa;MACpB,GAAGA;MACHM,SAASE;IACX;EACF;AAGA,QAAMR,KAAKK;AACX,SAAO;IACL,GAAGL;IACHM;EACF;AACF;AA8B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KE,UAAUxE,IAAI+D,QAAQ3B,MAAAA,EAAQkB,IAAI,CAAA;EAC/E,CAAA;AACF;AAuEO,IAAMmB,UAAN,cAA8BC,YAAI,yBAAA,EAAA,EAAA;AAAyD;AAe3F,IAAMC,SAAS,CACpB3D,OACG4D,SAEIC,eAAQJ,SAAS,CAACK,QAAQA,IAAIH,OAAO3D,IAAAA,GAAQ4D,IAAAA,CAAAA,EAA+BhE,KAC1EmE,gBAAS,kBAAA,CAAA;AAab,IAAMC,WAAW,CACtBhE,OACG4D,SAEIC,eAAQJ,SAAS,CAACK,QAAQA,IAAIE,SAAShE,IAAI4D,KAAK,CAAA,CAAE,CAAA,EAAQhE,KAAYmE,gBAAS,oBAAA,CAAA;AAKjF,IAAME,wBAAwB,CAACC,YAC9BC,aACJV,SACOW,WAAI,aAAA;AACT,QAAMxB,UAAU,OAAOa;AACvB,SAAOA,QAAQY,GAAG;IAChBV,QAAS,CAAC3D,IAA8ByC,OAAY6B,sBAClD1B,QAAQe,OAAO3D,IAAIyC,OAAO;MAAE,GAAGyB;MAAS,GAAGI;IAAkB,CAAA;IAC/DC,eAAgB,CAACvE,IAA8ByC,OAAY6B,sBACzD1B,QAAQ2B,cAAcvE,IAAIyC,OAAO;MAAE,GAAGyB;MAAS,GAAGI;IAAkB,CAAA;IACtEN,UAAUpB,QAAQoB;EACpB,CAAA;AACF,CAAA,CAAA;",
|
|
6
|
-
"names": ["Context", "Effect", "Layer", "Pipeable", "Schema$", "Annotation", "JsonSchema", "Obj", "Ref", "Type", "DefinitionTypeId", "isOperationDefinition", "value", "isOperationWithHandler", "make", "props", "executionMode", "types", "services", "pipe", "pipeArguments", "arguments", "intrinsic", "op", "meta", "deployedId", "key", "withHandler", "opOrHandler", "handler", "undefined", "handlerFn", "opaqueHandler", "PersistentOperation", "Struct", "optional", "String", "annotations", "description", "name", "NonEmptyString", "version", "updated", "source", "Unknown", "inputSchema", "outputSchema", "Array", "binding", "object", "typename", "LabelAnnotation", "set", "IconAnnotation", "icon", "hue", "SystemTypeAnnotation", "FUNCTION_META_KEY", "serialize", "operation", "Meta", "keys", "id", "toJsonSchema", "input", "output", "map", "service", "deserialize", "record", "getMeta", "find", "toEffectSchema", "GenericTag", "setFrom", "target", "update", "JSON", "parse", "stringify", "Service", "Tag", "invoke", "args", "flatMap", "ops", "withSpan", "schedule", "withInvocationOptions", "options", "effect", "gen", "of", "invocationOptions", "invokePromise"]
|
|
7
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|