@dxos/functions 0.8.4-main.69d29f4 → 0.8.4-main.6fa680abb7
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/README.md +4 -6
- package/dist/lib/{browser → neutral}/index.mjs +58 -47
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/types/src/example/index.d.ts +5 -5
- package/dist/types/src/example/index.d.ts.map +1 -1
- package/dist/types/src/protocol/protocol.d.ts.map +1 -1
- package/dist/types/src/sdk.d.ts +11 -8
- package/dist/types/src/sdk.d.ts.map +1 -1
- package/dist/types/src/services/event-logger.d.ts +2 -2
- package/dist/types/src/services/event-logger.d.ts.map +1 -1
- package/dist/types/src/types/Function.d.ts +1 -1
- package/dist/types/src/types/Function.d.ts.map +1 -1
- package/dist/types/src/types/Trigger.d.ts +5 -4
- package/dist/types/src/types/Trigger.d.ts.map +1 -1
- package/dist/types/src/types/TriggerEvent.d.ts +3 -2
- package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
- package/dist/types/src/types/url.d.ts +2 -2
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +19 -20
- package/src/example/forex-effect.ts +1 -1
- package/src/example/index.ts +8 -8
- package/src/protocol/protocol.ts +11 -15
- package/src/sdk.ts +20 -12
- package/src/services/event-logger.ts +1 -1
- package/src/types/Function.ts +4 -3
- package/src/types/Script.ts +2 -2
- package/src/types/Trigger.ts +14 -3
- package/src/types/TriggerEvent.ts +2 -2
- package/src/types/url.ts +2 -2
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/node-esm/index.mjs +0 -1230
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
package/README.md
CHANGED
|
@@ -27,11 +27,9 @@ import { FunctionContext } from '@dxos/functions';
|
|
|
27
27
|
|
|
28
28
|
export default (event: any, context: FunctionContext) => {
|
|
29
29
|
const identity = context.client.halo.identity.get();
|
|
30
|
-
return context
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
message: `Hello ${identity?.profile?.displayName}`
|
|
34
|
-
});
|
|
30
|
+
return context.status(200).succeed({
|
|
31
|
+
message: `Hello ${identity?.profile?.displayName}`,
|
|
32
|
+
});
|
|
35
33
|
};
|
|
36
34
|
```
|
|
37
35
|
|
|
@@ -69,7 +67,7 @@ nodemon -w ./src -e ts --exec $(git rev-parse --show-toplevel)/packages/devtools
|
|
|
69
67
|
> NOTE: The port (7001) must match the one in config.
|
|
70
68
|
|
|
71
69
|
```bash
|
|
72
|
-
curl http://localhost:7001/dev/hello -X POST -H 'Content-Type: application/json' -w '\n' --data '{ "message": "Hello World!" }'
|
|
70
|
+
curl http://localhost:7001/dev/hello -X POST -H 'Content-Type: application/json' -w '\n' --data '{ "message": "Hello World!" }'
|
|
73
71
|
```
|
|
74
72
|
|
|
75
73
|
## DXOS Resources
|
|
@@ -38,7 +38,7 @@ import * as Schema6 from "effect/Schema";
|
|
|
38
38
|
// src/sdk.ts
|
|
39
39
|
import * as Effect from "effect/Effect";
|
|
40
40
|
import * as Schema5 from "effect/Schema";
|
|
41
|
-
import {
|
|
41
|
+
import { JsonSchema as JsonSchema2, Obj as Obj5 } from "@dxos/echo";
|
|
42
42
|
import { assertArgument, failedInvariant } from "@dxos/invariant";
|
|
43
43
|
import { Operation } from "@dxos/operation";
|
|
44
44
|
|
|
@@ -50,7 +50,7 @@ __export(Function_exports, {
|
|
|
50
50
|
setFrom: () => setFrom
|
|
51
51
|
});
|
|
52
52
|
import * as Schema2 from "effect/Schema";
|
|
53
|
-
import { Annotation as Annotation2, JsonSchema, Obj as Obj2, Type as Type2 } from "@dxos/echo";
|
|
53
|
+
import { Annotation as Annotation2, JsonSchema, Obj as Obj2, Ref as Ref2, Type as Type2 } from "@dxos/echo";
|
|
54
54
|
import { SystemTypeAnnotation } from "@dxos/echo/internal";
|
|
55
55
|
|
|
56
56
|
// src/types/Script.ts
|
|
@@ -69,9 +69,9 @@ var Script = Schema.Struct({
|
|
|
69
69
|
// TODO(burdon): Change to hash of deployed content.
|
|
70
70
|
// Whether source has changed since last deploy.
|
|
71
71
|
changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),
|
|
72
|
-
source:
|
|
72
|
+
source: Ref.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
|
|
73
73
|
}).pipe(Type.object({
|
|
74
|
-
typename: "dxos.
|
|
74
|
+
typename: "org.dxos.type.script",
|
|
75
75
|
version: "0.1.0"
|
|
76
76
|
}), Annotation.LabelAnnotation.set([
|
|
77
77
|
"name"
|
|
@@ -102,7 +102,7 @@ var Function = Schema2.Struct({
|
|
|
102
102
|
updated: Schema2.optional(Schema2.String),
|
|
103
103
|
// Reference to a source script if it exists within ECHO.
|
|
104
104
|
// TODO(burdon): Don't ref ScriptType directly (core).
|
|
105
|
-
source: Schema2.optional(
|
|
105
|
+
source: Schema2.optional(Ref2.Ref(Script)),
|
|
106
106
|
inputSchema: Schema2.optional(JsonSchema.JsonSchema),
|
|
107
107
|
outputSchema: Schema2.optional(JsonSchema.JsonSchema),
|
|
108
108
|
/**
|
|
@@ -113,11 +113,14 @@ var Function = Schema2.Struct({
|
|
|
113
113
|
// Local binding to a function name.
|
|
114
114
|
binding: Schema2.optional(Schema2.String)
|
|
115
115
|
}).pipe(Type2.object({
|
|
116
|
-
typename: "dxos.
|
|
116
|
+
typename: "org.dxos.type.function",
|
|
117
117
|
version: "0.1.0"
|
|
118
118
|
}), Annotation2.LabelAnnotation.set([
|
|
119
119
|
"name"
|
|
120
|
-
]),
|
|
120
|
+
]), Annotation2.IconAnnotation.set({
|
|
121
|
+
icon: "ph--function--regular",
|
|
122
|
+
hue: "blue"
|
|
123
|
+
}), SystemTypeAnnotation.set(true));
|
|
121
124
|
var make2 = (props) => Obj2.make(Function, props);
|
|
122
125
|
var setFrom = (target, source) => {
|
|
123
126
|
Obj2.change(target, (t) => {
|
|
@@ -147,7 +150,7 @@ __export(Trigger_exports, {
|
|
|
147
150
|
});
|
|
148
151
|
import * as Schema3 from "effect/Schema";
|
|
149
152
|
import * as SchemaAST from "effect/SchemaAST";
|
|
150
|
-
import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
|
|
153
|
+
import { Annotation as Annotation3, Obj as Obj3, QueryAST, Ref as Ref3, Type as Type3 } from "@dxos/echo";
|
|
151
154
|
import { OptionsAnnotationId, SystemTypeAnnotation as SystemTypeAnnotation2 } from "@dxos/echo/internal";
|
|
152
155
|
import { DXN } from "@dxos/keys";
|
|
153
156
|
import { Expando } from "@dxos/schema";
|
|
@@ -220,7 +223,7 @@ var TriggerSchema = Schema3.Struct({
|
|
|
220
223
|
* Function or workflow to invoke.
|
|
221
224
|
*/
|
|
222
225
|
// TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
|
|
223
|
-
function: Schema3.optional(
|
|
226
|
+
function: Schema3.optional(Ref3.Ref(Expando.Expando).annotations({
|
|
224
227
|
title: "Function"
|
|
225
228
|
})),
|
|
226
229
|
/**
|
|
@@ -237,6 +240,11 @@ var TriggerSchema = Schema3.Struct({
|
|
|
237
240
|
title: "Enabled"
|
|
238
241
|
})),
|
|
239
242
|
spec: Schema3.optional(Spec),
|
|
243
|
+
concurrency: Schema3.optional(Schema3.Number.annotations({
|
|
244
|
+
title: "Concurrency",
|
|
245
|
+
default: 1,
|
|
246
|
+
description: "Maximum number of concurrent invocations of the trigger. For queue triggers, this will process queue items in parallel."
|
|
247
|
+
})),
|
|
240
248
|
/**
|
|
241
249
|
* Passed as the input data to the function.
|
|
242
250
|
* Must match the function's input schema.
|
|
@@ -253,8 +261,11 @@ var TriggerSchema = Schema3.Struct({
|
|
|
253
261
|
value: Schema3.Any
|
|
254
262
|
}))
|
|
255
263
|
}).pipe(Type3.object({
|
|
256
|
-
typename: "dxos.
|
|
264
|
+
typename: "org.dxos.type.trigger",
|
|
257
265
|
version: "0.1.0"
|
|
266
|
+
}), Annotation3.IconAnnotation.set({
|
|
267
|
+
icon: "ph--lightning--regular",
|
|
268
|
+
hue: "yellow"
|
|
258
269
|
}), SystemTypeAnnotation2.set(true));
|
|
259
270
|
var Trigger = TriggerSchema;
|
|
260
271
|
var make3 = (props) => Obj3.make(Trigger, props);
|
|
@@ -270,7 +281,7 @@ __export(TriggerEvent_exports, {
|
|
|
270
281
|
WebhookEvent: () => WebhookEvent
|
|
271
282
|
});
|
|
272
283
|
import * as Schema4 from "effect/Schema";
|
|
273
|
-
import { DXN as DXN2,
|
|
284
|
+
import { DXN as DXN2, Obj as Obj4, Ref as Ref4 } from "@dxos/echo";
|
|
274
285
|
var EmailEvent = Schema4.Struct({
|
|
275
286
|
from: Schema4.String,
|
|
276
287
|
to: Schema4.String,
|
|
@@ -292,7 +303,7 @@ var SubscriptionEvent = Schema4.Struct({
|
|
|
292
303
|
/**
|
|
293
304
|
* Reference to the object that was changed or created.
|
|
294
305
|
*/
|
|
295
|
-
subject:
|
|
306
|
+
subject: Ref4.Ref(Obj4.Unknown),
|
|
296
307
|
/**
|
|
297
308
|
* @deprecated
|
|
298
309
|
*/
|
|
@@ -313,8 +324,8 @@ var WebhookEvent = Schema4.Struct({
|
|
|
313
324
|
var TriggerEvent = Schema4.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);
|
|
314
325
|
|
|
315
326
|
// src/types/url.ts
|
|
316
|
-
var FUNCTIONS_META_KEY = "dxos.
|
|
317
|
-
var FUNCTIONS_PRESET_META_KEY = "dxos.
|
|
327
|
+
var FUNCTIONS_META_KEY = "org.dxos.service.function";
|
|
328
|
+
var FUNCTIONS_PRESET_META_KEY = "org.dxos.service.function-preset";
|
|
318
329
|
var getUserFunctionIdInMetadata = (meta) => {
|
|
319
330
|
return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
|
|
320
331
|
};
|
|
@@ -333,7 +344,7 @@ var setUserFunctionIdInMetadata = (meta, functionId) => {
|
|
|
333
344
|
};
|
|
334
345
|
|
|
335
346
|
// src/sdk.ts
|
|
336
|
-
var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
|
|
347
|
+
var typeId = /* @__PURE__ */ Symbol.for("@dxos/functions/FunctionDefinition");
|
|
337
348
|
var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, types, services }) => {
|
|
338
349
|
if (!Schema5.isSchema(inputSchema)) {
|
|
339
350
|
throw new Error("Input schema must be a valid schema");
|
|
@@ -420,14 +431,14 @@ var toOperation = (functionDef) => {
|
|
|
420
431
|
var FunctionDefinition = {
|
|
421
432
|
make: defineFunction,
|
|
422
433
|
isFunction: (value2) => {
|
|
423
|
-
return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
|
|
434
|
+
return typeof value2 === "object" && value2 !== null && /* @__PURE__ */ Symbol.for("@dxos/functions/FunctionDefinition") in value2;
|
|
424
435
|
},
|
|
425
436
|
serialize: (functionDef) => {
|
|
426
437
|
assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
|
|
427
438
|
return serializeFunction(functionDef);
|
|
428
439
|
},
|
|
429
440
|
deserialize: (functionObj) => {
|
|
430
|
-
assertArgument(
|
|
441
|
+
assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
|
|
431
442
|
return deserializeFunction(functionObj);
|
|
432
443
|
},
|
|
433
444
|
toOperation
|
|
@@ -438,12 +449,12 @@ var serializeFunction = (functionDef) => {
|
|
|
438
449
|
name: functionDef.name,
|
|
439
450
|
version: "0.1.0",
|
|
440
451
|
description: functionDef.description,
|
|
441
|
-
inputSchema:
|
|
442
|
-
outputSchema: !functionDef.outputSchema ? void 0 :
|
|
452
|
+
inputSchema: JsonSchema2.toJsonSchema(functionDef.inputSchema),
|
|
453
|
+
outputSchema: !functionDef.outputSchema ? void 0 : JsonSchema2.toJsonSchema(functionDef.outputSchema),
|
|
443
454
|
services: functionDef.services
|
|
444
455
|
});
|
|
445
456
|
if (functionDef.meta?.deployedFunctionId) {
|
|
446
|
-
|
|
457
|
+
Obj5.change(fn4, (fn5) => setUserFunctionIdInMetadata(Obj5.getMeta(fn5), functionDef.meta.deployedFunctionId));
|
|
447
458
|
}
|
|
448
459
|
return fn4;
|
|
449
460
|
};
|
|
@@ -454,15 +465,15 @@ var deserializeFunction = (functionObj) => {
|
|
|
454
465
|
key: functionObj.key ?? functionObj.name,
|
|
455
466
|
name: functionObj.name,
|
|
456
467
|
description: functionObj.description,
|
|
457
|
-
inputSchema: !functionObj.inputSchema ? Schema5.Unknown :
|
|
458
|
-
outputSchema: !functionObj.outputSchema ? void 0 :
|
|
468
|
+
inputSchema: !functionObj.inputSchema ? Schema5.Unknown : JsonSchema2.toEffectSchema(functionObj.inputSchema),
|
|
469
|
+
outputSchema: !functionObj.outputSchema ? void 0 : JsonSchema2.toEffectSchema(functionObj.outputSchema),
|
|
459
470
|
// TODO(dmaretskyi): This should throw error.
|
|
460
471
|
handler: () => {
|
|
461
472
|
},
|
|
462
473
|
services: functionObj.services ?? [],
|
|
463
474
|
types: [],
|
|
464
475
|
meta: {
|
|
465
|
-
deployedFunctionId: getUserFunctionIdInMetadata(
|
|
476
|
+
deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
|
|
466
477
|
}
|
|
467
478
|
};
|
|
468
479
|
};
|
|
@@ -532,12 +543,11 @@ var sleep_default = defineFunction({
|
|
|
532
543
|
});
|
|
533
544
|
|
|
534
545
|
// src/example/index.ts
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
}
|
|
540
|
-
var Example;
|
|
546
|
+
var ExampleFunctions = {
|
|
547
|
+
Fibonacci: fib_default,
|
|
548
|
+
Reply: reply_default,
|
|
549
|
+
Sleep: sleep_default
|
|
550
|
+
};
|
|
541
551
|
|
|
542
552
|
// src/services/credentials.ts
|
|
543
553
|
import * as HttpClient from "@effect/platform/HttpClient";
|
|
@@ -633,7 +643,7 @@ import * as Context3 from "effect/Context";
|
|
|
633
643
|
import * as Effect7 from "effect/Effect";
|
|
634
644
|
import * as Layer3 from "effect/Layer";
|
|
635
645
|
import * as Schema9 from "effect/Schema";
|
|
636
|
-
import { Obj as
|
|
646
|
+
import { Obj as Obj7, Type as Type4 } from "@dxos/echo";
|
|
637
647
|
import { invariant } from "@dxos/invariant";
|
|
638
648
|
import { LogLevel, log as log2 } from "@dxos/log";
|
|
639
649
|
|
|
@@ -642,7 +652,7 @@ import * as Context2 from "effect/Context";
|
|
|
642
652
|
import * as Effect6 from "effect/Effect";
|
|
643
653
|
import * as Layer2 from "effect/Layer";
|
|
644
654
|
import { AgentStatus } from "@dxos/ai";
|
|
645
|
-
import { Obj as
|
|
655
|
+
import { Obj as Obj6 } from "@dxos/echo";
|
|
646
656
|
import { ObjectId } from "@dxos/keys";
|
|
647
657
|
import { Message } from "@dxos/types";
|
|
648
658
|
var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
|
|
@@ -685,7 +695,7 @@ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions
|
|
|
685
695
|
*/
|
|
686
696
|
static emitStatus = Effect6.fnUntraced(function* (data) {
|
|
687
697
|
const tracing = yield* _TracingService;
|
|
688
|
-
tracing.write(
|
|
698
|
+
tracing.write(Obj6.make(AgentStatus, {
|
|
689
699
|
parentMessage: tracing.getTraceContext().parentMessage,
|
|
690
700
|
toolCallId: tracing.getTraceContext().toolCallId,
|
|
691
701
|
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -694,7 +704,7 @@ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions
|
|
|
694
704
|
});
|
|
695
705
|
static emitConverationMessage = Effect6.fnUntraced(function* (data) {
|
|
696
706
|
const tracing = yield* _TracingService;
|
|
697
|
-
tracing.write(
|
|
707
|
+
tracing.write(Obj6.make(Message.Message, {
|
|
698
708
|
parentMessage: tracing.getTraceContext().parentMessage,
|
|
699
709
|
...data,
|
|
700
710
|
properties: {
|
|
@@ -739,8 +749,8 @@ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
|
|
|
739
749
|
}));
|
|
740
750
|
var ComputeEvent = Schema9.Struct({
|
|
741
751
|
payload: ComputeEventPayload
|
|
742
|
-
}).pipe(
|
|
743
|
-
typename: "dxos.
|
|
752
|
+
}).pipe(Type4.object({
|
|
753
|
+
typename: "org.dxos.type.compute-event",
|
|
744
754
|
version: "0.1.0"
|
|
745
755
|
}));
|
|
746
756
|
var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
|
|
@@ -756,7 +766,7 @@ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/f
|
|
|
756
766
|
const tracing = yield* TracingService;
|
|
757
767
|
return {
|
|
758
768
|
log: (event) => {
|
|
759
|
-
tracing.write(
|
|
769
|
+
tracing.write(Obj7.make(ComputeEvent, {
|
|
760
770
|
payload: event
|
|
761
771
|
}), tracing.getTraceContext());
|
|
762
772
|
},
|
|
@@ -872,9 +882,9 @@ import * as SchemaAST2 from "effect/SchemaAST";
|
|
|
872
882
|
import { AiModelResolver, AiService } from "@dxos/ai";
|
|
873
883
|
import { AnthropicResolver } from "@dxos/ai/resolvers";
|
|
874
884
|
import { LifecycleState, Resource } from "@dxos/context";
|
|
875
|
-
import { Database as Database2,
|
|
885
|
+
import { Database as Database2, Feed, JsonSchema as JsonSchema3, Ref as Ref5 } from "@dxos/echo";
|
|
876
886
|
import { refFromEncodedReference } from "@dxos/echo/internal";
|
|
877
|
-
import { EchoClient } from "@dxos/echo-db";
|
|
887
|
+
import { EchoClient, createFeedServiceLayer } from "@dxos/echo-db";
|
|
878
888
|
import { runAndForwardErrors } from "@dxos/effect";
|
|
879
889
|
import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
|
|
880
890
|
import { PublicKey } from "@dxos/keys";
|
|
@@ -1010,12 +1020,12 @@ var wrapFunctionHandler = (func) => {
|
|
|
1010
1020
|
key: func.key,
|
|
1011
1021
|
name: func.name,
|
|
1012
1022
|
description: func.description,
|
|
1013
|
-
inputSchema:
|
|
1014
|
-
outputSchema: func.outputSchema === void 0 ? void 0 :
|
|
1023
|
+
inputSchema: JsonSchema3.toJsonSchema(func.inputSchema),
|
|
1024
|
+
outputSchema: func.outputSchema === void 0 ? void 0 : JsonSchema3.toJsonSchema(func.outputSchema),
|
|
1015
1025
|
services: func.services
|
|
1016
1026
|
},
|
|
1017
1027
|
handler: async ({ data, context }) => {
|
|
1018
|
-
if ((func.services.includes(Database2.Service.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
|
|
1028
|
+
if ((func.services.includes(Database2.Service.key) || func.services.includes(QueueService.key) || func.services.includes(Feed.Service.key)) && (!context.services.dataService || !context.services.queryService)) {
|
|
1019
1029
|
throw new FunctionError({
|
|
1020
1030
|
message: "Services not provided: dataService, queryService"
|
|
1021
1031
|
});
|
|
@@ -1041,7 +1051,7 @@ var wrapFunctionHandler = (func) => {
|
|
|
1041
1051
|
if (func.types.length > 0) {
|
|
1042
1052
|
invariant2(funcContext.db, "Database is required for functions with types", {
|
|
1043
1053
|
F: __dxlog_file3,
|
|
1044
|
-
L:
|
|
1054
|
+
L: 70,
|
|
1045
1055
|
S: void 0,
|
|
1046
1056
|
A: [
|
|
1047
1057
|
"funcContext.db",
|
|
@@ -1110,8 +1120,9 @@ var FunctionContext = class extends Resource {
|
|
|
1110
1120
|
}
|
|
1111
1121
|
createLayer() {
|
|
1112
1122
|
assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
|
|
1113
|
-
const dbLayer = this.db ? Database2.
|
|
1123
|
+
const dbLayer = this.db ? Database2.layer(this.db) : Database2.notAvailable;
|
|
1114
1124
|
const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
|
|
1125
|
+
const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
|
|
1115
1126
|
const credentials = dbLayer ? CredentialsService.layerFromDatabase({
|
|
1116
1127
|
caching: true
|
|
1117
1128
|
}).pipe(Layer7.provide(dbLayer)) : CredentialsService.configuredLayer([]);
|
|
@@ -1121,7 +1132,7 @@ var FunctionContext = class extends Resource {
|
|
|
1121
1132
|
// Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
|
|
1122
1133
|
apiUrl: "http://internal/provider/anthropic"
|
|
1123
1134
|
}).pipe(Layer7.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))))))) : AiService.notAvailable;
|
|
1124
|
-
return Layer7.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiLayer, tracing);
|
|
1135
|
+
return Layer7.mergeAll(dbLayer, queuesLayer, feedLayer, credentials, functionInvocationService, aiLayer, tracing);
|
|
1125
1136
|
}
|
|
1126
1137
|
};
|
|
1127
1138
|
var MockedFunctionInvocationService = Layer7.succeed(FunctionInvocationService, {
|
|
@@ -1133,8 +1144,8 @@ var decodeRefsFromSchema = (ast, value2, db) => {
|
|
|
1133
1144
|
return value2;
|
|
1134
1145
|
}
|
|
1135
1146
|
const encoded = SchemaAST2.encodedBoundAST(ast);
|
|
1136
|
-
if (
|
|
1137
|
-
if (
|
|
1147
|
+
if (Ref5.isRefType(encoded)) {
|
|
1148
|
+
if (Ref5.isRef(value2)) {
|
|
1138
1149
|
return value2;
|
|
1139
1150
|
}
|
|
1140
1151
|
if (typeof value2 === "object" && value2 !== null && typeof value2["/"] === "string") {
|
|
@@ -1198,7 +1209,7 @@ export {
|
|
|
1198
1209
|
ConfiguredCredentialsService,
|
|
1199
1210
|
ContextQueueService,
|
|
1200
1211
|
CredentialsService,
|
|
1201
|
-
|
|
1212
|
+
ExampleFunctions,
|
|
1202
1213
|
FUNCTIONS_META_KEY,
|
|
1203
1214
|
FUNCTIONS_PRESET_META_KEY,
|
|
1204
1215
|
Function_exports as Function,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/errors.ts", "../../../src/example/fib.ts", "../../../src/sdk.ts", "../../../src/types/Function.ts", "../../../src/types/Script.ts", "../../../src/types/Trigger.ts", "../../../src/types/TriggerEvent.ts", "../../../src/types/url.ts", "../../../src/example/reply.ts", "../../../src/example/sleep.ts", "../../../src/example/index.ts", "../../../src/services/credentials.ts", "../../../src/services/event-logger.ts", "../../../src/services/tracing.ts", "../../../src/services/function-invocation-service.ts", "../../../src/services/queues.ts", "../../../src/protocol/protocol.ts", "../../../src/protocol/functions-ai-http-client.ts"],
|
|
4
|
+
"sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError, type BaseErrorOptions } from '@dxos/errors';\n\nexport class ServiceNotAvailableError extends BaseError.extend('ServiceNotAvailable', 'Service not available') {\n constructor(service: string, options?: Omit<BaseErrorOptions, 'context'>) {\n super({ context: { service }, ...options });\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 TriggerStateNotFoundError extends BaseError.extend('TriggerStateNotFound', 'Trigger state not found') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../sdk';\n\nexport default defineFunction({\n key: 'example.org/function/fib',\n name: 'Fibonacci',\n description: 'Function that calculates a Fibonacci number',\n inputSchema: Schema.Struct({\n iterations: Schema.optional(Schema.Number).annotations({\n description: 'Number of iterations',\n default: 100_000,\n }),\n }),\n outputSchema: Schema.Struct({\n result: Schema.String,\n }),\n handler: Effect.fn(function* ({ data: { iterations = 100_000 } }) {\n let a = 0n;\n let b = 1n;\n for (let i = 0; i < iterations; i++) {\n a += b;\n b = a - b;\n }\n return { result: a.toString() };\n }),\n});\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { type AiService } from '@dxos/ai';\nimport { type Feed, JsonSchema, Obj, type Type } from '@dxos/echo';\nimport { type Database } from '@dxos/echo';\nimport { assertArgument, failedInvariant } from '@dxos/invariant';\nimport { Operation } from '@dxos/operation';\n\nimport {\n type CredentialsService,\n type FunctionInvocationService,\n type QueueService,\n type TracingService,\n} from './services';\nimport { Function } from './types';\nimport { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './types';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Services that are provided at the function call site by the caller.\n */\nexport type InvocationServices = TracingService;\n\n/**\n * Services that are available to invoked functions.\n */\nexport type FunctionServices =\n | InvocationServices\n | AiService.AiService\n | CredentialsService\n | Database.Service\n // TODO(wittjosiah): Remove QueueService — use Feed.Service instead.\n | QueueService\n | Feed.Service\n | FunctionInvocationService;\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TOutput = any, S extends FunctionServices = FunctionServices> = (params: {\n /**\n * Context available to the function.\n */\n context: FunctionContext;\n\n /**\n * Data passed as the input to the function.\n * Must match the function's input schema.\n * This will be the payload from the trigger or other data passed into the function in a workflow.\n */\n data: TData;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, S>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(dmaretskyi): Consider what we should put into context.\n}\n\nconst typeId = Symbol.for('@dxos/functions/FunctionDefinition');\n\n/**\n * Deployable function definition.\n */\nexport type FunctionDefinition<TInput = any, TOutput = any, S extends FunctionServices = FunctionServices> = {\n [typeId]: true;\n\n key: string;\n name: string;\n description?: string;\n inputSchema: Schema.Schema<TInput, any>;\n outputSchema?: Schema.Schema<TOutput, any>;\n\n /**\n * List of types the function uses.\n * This is used to ensure that the types are available when the function is executed.\n */\n types: readonly Type.AnyEntity[];\n\n /**\n * Keys of the required services.\n */\n services: readonly string[];\n\n meta?: {\n /**\n * Tools that are projected from functions have this annotation.\n *\n * deployedFunctionId:\n * - Backend deployment ID assigned by the EDGE function service (typically a UUID).\n * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.\n * - Persisted on the corresponding ECHO `Function.Function` object's metadata under the\n * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.\n */\n deployedFunctionId?: string;\n };\n\n handler: FunctionHandler<TInput, TOutput, S>;\n};\n\nexport declare namespace FunctionDefinition {\n export type Any = FunctionDefinition<any, any, any>;\n export type Input<T extends Any> = T extends FunctionDefinition<infer I, infer _O, infer _S> ? I : never;\n export type Output<T extends Any> = T extends FunctionDefinition<infer _I, infer O, infer _S> ? O : never;\n export type Services<T extends Any> = T extends FunctionDefinition<infer _I, infer _O, infer S> ? S : never;\n}\n\nexport type FunctionProps<T, O> = {\n key: string;\n name: string;\n description?: string;\n inputSchema: Schema.Schema<T, any>;\n outputSchema?: Schema.Schema<O, any>;\n\n /**\n * List of types the function uses.\n * This is used to ensure that the types are available when the function is executed.\n */\n types?: readonly Type.AnyEntity[];\n\n // TODO(dmaretskyi): This currently doesn't cause a compile-time error if the handler requests a service that is not specified\n services?: readonly Context.Tag<any, any>[];\n\n handler: FunctionHandler<T, O, FunctionServices>;\n};\n\n// TODO(dmaretskyi): Output type doesn't get typechecked.\nexport const defineFunction: {\n <I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O, FunctionServices>;\n} = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler, types, services }) => {\n if (!Schema.isSchema(inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n // Captures the function definition location.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 2;\n const traceError = new Error();\n Error.stackTraceLimit = limit;\n let cache: false | string = false;\n const captureStackTrace = () => {\n if (cache !== false) {\n return cache;\n }\n if (traceError.stack !== undefined) {\n const stack = traceError.stack.split('\\n');\n if (stack[2] !== undefined) {\n cache = stack[2].trim();\n return cache;\n }\n }\n };\n\n const handlerWithSpan = (...args: any[]) => {\n const result = (handler as any)(...args);\n if (Effect.isEffect(result)) {\n return Effect.withSpan(result, `${key ?? name}`, {\n captureStackTrace,\n });\n }\n return result;\n };\n\n return {\n [typeId]: true,\n key,\n name,\n description,\n inputSchema,\n outputSchema,\n handler: handlerWithSpan,\n types: types ?? [],\n services: !services ? [] : getServiceKeys(services),\n };\n};\n\nconst getServiceKeys = (services: readonly Context.Tag<any, any>[]) => {\n return services.map((tag: any) => {\n if (typeof tag.key === 'string') {\n return tag.key;\n }\n failedInvariant();\n });\n};\n\n/**\n * Converts a FunctionDefinition to an OperationDefinition with handler.\n * The function handler is adapted to the OperationHandler format.\n *\n * Note: FunctionDefinition stores service keys as strings, not Tag types,\n * so we can't use Operation.withHandler's type inference here.\n */\nexport const toOperation = <T, O, S extends FunctionServices = FunctionServices>(\n functionDef: FunctionDefinition<T, O, S>,\n): Operation.Definition<T, O> & { handler: Operation.Handler<T, O, any, S> } => {\n const op = Operation.make({\n schema: {\n input: functionDef.inputSchema,\n output: functionDef.outputSchema ?? Schema.Any,\n },\n meta: {\n key: functionDef.key,\n name: functionDef.name,\n description: functionDef.description,\n },\n });\n\n // Adapt FunctionHandler signature to OperationHandler format.\n // FunctionHandler expects { context, data }, OperationHandler expects just input.\n const operationHandler: Operation.Handler<T, O, any, S> = (input: T) => {\n const result = functionDef.handler({\n context: {} as FunctionContext,\n data: input,\n });\n\n // Convert Promise or plain value to Effect.\n if (Effect.isEffect(result)) {\n return result;\n }\n if (result instanceof Promise) {\n return Effect.tryPromise(() => result);\n }\n return Effect.succeed(result as O);\n };\n\n // Manually attach handler since FunctionDefinition stores service keys as strings,\n // not Tag types, so withHandler's type inference doesn't apply.\n return {\n ...op,\n handler: operationHandler,\n };\n};\n\nexport const FunctionDefinition = {\n make: defineFunction,\n isFunction: (value: unknown): value is FunctionDefinition.Any => {\n return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;\n },\n serialize: (functionDef: FunctionDefinition.Any): Function.Function => {\n assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');\n return serializeFunction(functionDef);\n },\n deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {\n assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');\n return deserializeFunction(functionObj);\n },\n toOperation,\n};\n\nexport const serializeFunction = (functionDef: FunctionDefinition.Any): Function.Function => {\n const fn = Function.make({\n key: functionDef.key,\n name: functionDef.name,\n version: '0.1.0',\n description: functionDef.description,\n inputSchema: JsonSchema.toJsonSchema(functionDef.inputSchema),\n outputSchema: !functionDef.outputSchema ? undefined : JsonSchema.toJsonSchema(functionDef.outputSchema),\n services: functionDef.services,\n });\n if (functionDef.meta?.deployedFunctionId) {\n Obj.change(fn, (fn) => setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta!.deployedFunctionId!));\n }\n return fn;\n};\n\nexport const deserializeFunction = (functionObj: Function.Function): FunctionDefinition<unknown, unknown> => {\n return {\n [typeId]: true,\n // TODO(dmaretskyi): Fix key.\n key: functionObj.key ?? functionObj.name,\n name: functionObj.name,\n description: functionObj.description,\n inputSchema: !functionObj.inputSchema ? Schema.Unknown : JsonSchema.toEffectSchema(functionObj.inputSchema),\n outputSchema: !functionObj.outputSchema ? undefined : JsonSchema.toEffectSchema(functionObj.outputSchema),\n // TODO(dmaretskyi): This should throw error.\n handler: () => {},\n services: functionObj.services ?? [],\n types: [],\n meta: {\n deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),\n },\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, JsonSchema, Obj, Ref, Type } from '@dxos/echo';\nimport { SystemTypeAnnotation } from '@dxos/echo/internal';\n\nimport { Script } from './Script';\n\n/**\n * Function deployment.\n */\nexport const Function = 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(Script)),\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 binding: Schema.optional(Schema.String),\n}).pipe(\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 SystemTypeAnnotation.set(true),\n);\n\nexport interface Function extends Schema.Schema.Type<typeof Function> {}\n\nexport const make = (props: Obj.MakeProps<typeof Function>) => Obj.make(Function, props);\n\n/**\n * Copies properties from source to target.\n * @param target - Target object to copy properties to.\n * @param source - Source object to copy properties from.\n */\nexport const setFrom = (target: Function, source: Function) => {\n Obj.change(target, (t) => {\n t.key = source.key ?? target.key;\n t.name = source.name ?? target.name;\n t.version = source.version;\n t.description = source.description;\n t.updated = source.updated;\n // TODO(dmaretskyi): A workaround for an ECHO bug.\n t.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;\n t.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;\n Obj.getMeta(t).keys = JSON.parse(JSON.stringify(Obj.getMeta(source).keys));\n });\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, Obj, Ref, Type } from '@dxos/echo';\nimport { FormInputAnnotation } from '@dxos/echo/internal';\nimport { Text } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const Script = Schema.Struct({\n name: Schema.String.pipe(Schema.optional),\n description: Schema.String.pipe(Schema.optional),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),\n source: Ref.Ref(Text.Text).pipe(FormInputAnnotation.set(false)),\n}).pipe(\n Type.object({\n typename: 'org.dxos.type.script',\n version: '0.1.0',\n }),\n Annotation.LabelAnnotation.set(['name']),\n);\n\nexport interface Script extends Schema.Schema.Type<typeof Script> {}\n\ntype Props = Omit<Obj.MakeProps<typeof Script>, 'source'> & { source?: string };\n\nexport const make = ({ source = '', ...props }: Props = {}): Script =>\n Obj.make(Script, { ...props, source: Ref.make(Text.make(source)) });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { Annotation, Obj, QueryAST, Ref, Type } from '@dxos/echo';\nimport { OptionsAnnotationId, SystemTypeAnnotation } from '@dxos/echo/internal';\nimport { DXN } from '@dxos/keys';\nimport { Expando } from '@dxos/schema';\n\n/**\n * Type discriminator for TriggerType.\n * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport const Kinds = ['email', 'queue', 'subscription', 'timer', 'webhook'] as const;\nexport type Kind = (typeof Kinds)[number];\n\nconst kindLiteralAnnotations = { title: 'Kind' };\n\nexport const EmailSpec = Schema.Struct({\n kind: Schema.Literal('email').annotations(kindLiteralAnnotations),\n});\nexport type EmailSpec = Schema.Schema.Type<typeof EmailSpec>;\n\n// TODO(wittjosiah): Remove. Migrate to Subscription triggers once EDGE supports them for feed queries.\nexport const QueueSpec = Schema.Struct({\n kind: Schema.Literal('queue').annotations(kindLiteralAnnotations),\n\n // TODO(dmaretskyi): Change to a reference.\n queue: DXN.Schema,\n});\nexport type QueueSpec = Schema.Schema.Type<typeof QueueSpec>;\n\n/**\n * Subscription.\n */\nexport const SubscriptionSpec = Schema.Struct({\n kind: Schema.Literal('subscription').annotations(kindLiteralAnnotations),\n query: Schema.Struct({\n raw: Schema.optional(Schema.String.annotations({ title: 'Query' })),\n ast: QueryAST.Query,\n }),\n options: Schema.optional(\n Schema.Struct({\n // Watch changes to object (not just creation).\n deep: Schema.optional(Schema.Boolean.annotations({ title: 'Nested' })),\n // Debounce changes (delay in ms).\n delay: Schema.optional(Schema.Number.annotations({ title: 'Delay' })),\n }).annotations({ title: 'Options' }),\n ),\n});\nexport type SubscriptionSpec = Schema.Schema.Type<typeof SubscriptionSpec>;\n\n/**\n * Cron timer.\n */\nexport const TimerSpec = Schema.Struct({\n kind: Schema.Literal('timer').annotations(kindLiteralAnnotations),\n cron: Schema.String.annotations({\n title: 'Cron',\n [SchemaAST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n});\nexport type TimerSpec = Schema.Schema.Type<typeof TimerSpec>;\n\n/**\n * Webhook.\n */\nexport const WebhookSpec = Schema.Struct({\n kind: Schema.Literal('webhook').annotations(kindLiteralAnnotations),\n method: Schema.optional(\n Schema.String.annotations({\n title: 'Method',\n [OptionsAnnotationId]: ['GET', 'POST'],\n }),\n ),\n port: Schema.optional(\n Schema.Number.annotations({\n title: 'Port',\n }),\n ),\n});\nexport type WebhookSpec = Schema.Schema.Type<typeof WebhookSpec>;\n\n/**\n * Trigger schema.\n */\nexport const Spec = Schema.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({\n title: 'Trigger',\n});\nexport type Spec = Schema.Schema.Type<typeof Spec>;\n\n/**\n * Function trigger.\n * Function is invoked with the `payload` passed as input data.\n * The event that triggers the function is available in the function context.\n */\nconst TriggerSchema = Schema.Struct({\n /**\n * Function or workflow to invoke.\n */\n // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).\n function: Schema.optional(Ref.Ref(Expando.Expando).annotations({ title: 'Function' })),\n\n /**\n * Only used for workflowSchema.\n * Specifies the input node in the circuit.\n * @deprecated Remove and enforce a single input node in all compute graphSchema.\n */\n inputNodeId: Schema.optional(Schema.String.annotations({ title: 'Input Node ID' })),\n\n // TODO(burdon): NO BOOLEAN PROPERTIES (enabld/disabled/paused, etc.)\n // Need lint rule; or agent rule to require PR review for \"boolean\" key word.\n enabled: Schema.optional(Schema.Boolean.annotations({ title: 'Enabled' })),\n\n spec: Schema.optional(Spec),\n\n concurrency: Schema.optional(\n Schema.Number.annotations({\n title: 'Concurrency',\n default: 1,\n description:\n 'Maximum number of concurrent invocations of the trigger. For queue triggers, this will process queue items in parallel.',\n }),\n ),\n\n /**\n * Passed as the input data to the function.\n * Must match the function's input schema.\n *\n * @example\n * {\n * item: '{{$.trigger.event}}',\n * instructions: 'Summarize and perform entity-extraction'\n * mailbox: { '/': 'dxn:echo:AAA:ZZZ' }\n * }\n */\n input: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Any })),\n}).pipe(\n Type.object({\n typename: 'org.dxos.type.trigger',\n version: '0.1.0',\n }),\n Annotation.IconAnnotation.set({ icon: 'ph--lightning--regular', hue: 'yellow' }),\n SystemTypeAnnotation.set(true),\n);\n\nexport interface Trigger extends Schema.Schema.Type<typeof TriggerSchema> {}\nexport const Trigger: Type.Obj<Trigger> = TriggerSchema as any;\n\nexport const make = (props: Obj.MakeProps<typeof Trigger>) => Obj.make(Trigger, props);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { DXN, Obj, Ref } from '@dxos/echo';\n\n// TODO(wittjosiah): Review this type.\n// - Should be discriminated union.\n// - Should be more consistent (e.g. subject vs item).\n// - Should re-use schemas if possible.\n\n// TODO(burdon): Reuse trigger schema from @dxos/functions (TriggerType).\nexport const EmailEvent = Schema.Struct({\n from: Schema.String,\n to: Schema.String,\n subject: Schema.String,\n created: Schema.String,\n body: Schema.String,\n});\nexport type EmailEvent = Schema.Schema.Type<typeof EmailEvent>;\n\nexport const QueueEvent = Schema.Struct({\n queue: DXN.Schema,\n item: Schema.Any,\n cursor: Schema.String,\n});\nexport type QueueEvent = Schema.Schema.Type<typeof QueueEvent>;\n\nexport const SubscriptionEvent = Schema.Struct({\n /**\n * Type of the mutation.\n */\n // TODO(dmaretskyi): Specify enum.\n type: Schema.String,\n\n /**\n * Reference to the object that was changed or created.\n */\n subject: Ref.Ref(Obj.Unknown),\n\n /**\n * @deprecated\n */\n changedObjectId: Schema.optional(Schema.String),\n});\nexport type SubscriptionEvent = Schema.Schema.Type<typeof SubscriptionEvent>;\n\nexport const TimerEvent = Schema.Struct({ tick: Schema.Number });\nexport type TimerEvent = Schema.Schema.Type<typeof TimerEvent>;\n\nexport const WebhookEvent = Schema.Struct({\n url: Schema.String,\n method: Schema.Literal('GET', 'POST'),\n headers: Schema.Record({ key: Schema.String, value: Schema.String }),\n bodyText: Schema.String,\n});\nexport type WebhookEvent = Schema.Schema.Type<typeof WebhookEvent>;\n\nexport const TriggerEvent = Schema.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);\nexport type TriggerEvent = Schema.Schema.Type<typeof TriggerEvent>;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Obj } from '@dxos/echo';\n\n// TODO: use URL scheme for source?\nexport const FUNCTIONS_META_KEY = 'org.dxos.service.function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'org.dxos.service.function-preset';\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const getUserFunctionIdInMetadata = (meta: Obj.ReadonlyMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n * Must be called inside Obj.changeMeta() since it mutates the meta.\n */\nexport const setUserFunctionIdInMetadata = (meta: Obj.Meta, functionId: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionId) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionId });\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../sdk';\n\nexport default defineFunction({\n key: 'example.org/function/reply',\n name: 'Reply',\n description: 'Function that echoes the input',\n inputSchema: Schema.Any,\n outputSchema: Schema.Any,\n handler: Effect.fn(function* ({ data }) {\n yield* Console.log('reply', { data });\n return data;\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../sdk';\n\nexport default defineFunction({\n key: 'example.org/function/sleep',\n name: 'Sleep',\n description: 'Function that sleeps for a given amount of time',\n inputSchema: Schema.Struct({\n duration: Schema.optional(Schema.Number).annotations({\n description: 'Milliseconds to sleep',\n default: 100_000,\n }),\n }),\n outputSchema: Schema.Void,\n handler: Effect.fn(function* ({ data: { duration = 100_000 } }) {\n yield* Effect.sleep(duration);\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport Fibonacci from './fib';\nimport Reply from './reply';\nimport Sleep from './sleep';\n\nexport const ExampleFunctions = {\n Fibonacci,\n Reply,\n Sleep,\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest';\nimport type * as Config from 'effect/Config';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Redacted from 'effect/Redacted';\n\nimport { Query } from '@dxos/echo';\nimport { Database } from '@dxos/echo';\nimport { AccessToken } from '@dxos/types';\n\nexport type CredentialQuery = {\n service?: string;\n};\n\n// TODO(dmaretskyi): Unify with other apis.\n// packages/sdk/schema/src/common/access-token.ts\nexport type ServiceCredential = {\n service: string;\n\n // TODO(dmaretskyi): Build out.\n apiKey?: string;\n};\n\nexport class CredentialsService extends Context.Tag('@dxos/functions/CredentialsService')<\n CredentialsService,\n {\n /**\n * Query all.\n */\n queryCredentials: (query: CredentialQuery) => Promise<ServiceCredential[]>;\n\n /**\n * Get a single credential.\n * @throws {Error} If no credential is found.\n */\n getCredential: (query: CredentialQuery) => Promise<ServiceCredential>;\n }\n>() {\n static getCredential = (query: CredentialQuery): Effect.Effect<ServiceCredential, never, CredentialsService> =>\n Effect.gen(function* () {\n const credentials = yield* CredentialsService;\n return yield* Effect.promise(() => credentials.getCredential(query));\n });\n\n static getApiKey = (query: CredentialQuery): Effect.Effect<Redacted.Redacted<string>, never, CredentialsService> =>\n Effect.gen(function* () {\n const credential = yield* CredentialsService.getCredential(query);\n if (!credential.apiKey) {\n throw new Error(`API key not found for service: ${query.service}`);\n }\n return Redacted.make(credential.apiKey);\n });\n\n static configuredLayer = (credentials: ServiceCredential[]) =>\n Layer.succeed(CredentialsService, new ConfiguredCredentialsService(credentials));\n\n static layerConfig = (\n credentials: {\n service: string;\n apiKey: Config.Config<Redacted.Redacted<string>>;\n }[],\n ) =>\n Layer.effect(\n CredentialsService,\n Effect.gen(function* () {\n const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>\n Effect.gen(function* () {\n return {\n service,\n apiKey: Redacted.value(yield* apiKey),\n };\n }),\n );\n\n return new ConfiguredCredentialsService(serviceCredentials);\n }),\n );\n\n static layerFromDatabase = ({ caching = false }: { caching?: boolean } = {}) =>\n Layer.effect(\n CredentialsService,\n Effect.gen(function* () {\n const dbService = yield* Database.Service;\n const cache = new Map<string, ServiceCredential[]>();\n\n const queryCredentials = async (query: CredentialQuery): Promise<ServiceCredential[]> => {\n const cacheKey = JSON.stringify(query);\n if (caching && cache.has(cacheKey)) {\n return cache.get(cacheKey)!;\n }\n\n const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();\n const credentials = accessTokens\n .filter((accessToken) => accessToken.source === query.service)\n .map((accessToken) => ({\n service: accessToken.source,\n apiKey: accessToken.token,\n }));\n\n if (caching) {\n cache.set(cacheKey, credentials);\n }\n\n return credentials;\n };\n\n return {\n getCredential: async (query) => {\n const credentials = await queryCredentials(query);\n if (credentials.length === 0) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credentials[0];\n },\n queryCredentials: async (query) => {\n return queryCredentials(query);\n },\n };\n }),\n );\n}\n\nexport class ConfiguredCredentialsService implements Context.Tag.Service<CredentialsService> {\n constructor(private readonly credentials: ServiceCredential[] = []) {}\n\n addCredentials(credentials: ServiceCredential[]): ConfiguredCredentialsService {\n this.credentials.push(...credentials);\n return this;\n }\n\n async queryCredentials(query: CredentialQuery): Promise<ServiceCredential[]> {\n return this.credentials.filter((credential) => credential.service === query.service);\n }\n\n async getCredential(query: CredentialQuery): Promise<ServiceCredential> {\n const credential = this.credentials.find((credential) => credential.service === query.service);\n if (!credential) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credential;\n }\n}\n\n/**\n * Maps the request to include the given token in the Authorization header.\n */\nexport const withAuthorization = (token: string, kind?: 'Bearer' | 'Basic') =>\n HttpClient.mapRequest((request) => {\n const authorization = kind ? `${kind} ${token}` : token;\n return HttpClientRequest.setHeader(request, 'Authorization', authorization);\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\n\nimport { Obj, Type } from '@dxos/echo';\nimport { invariant } from '@dxos/invariant';\nimport { LogLevel, log } from '@dxos/log';\n\nimport { TracingService } from './tracing';\n\nexport const ComputeEventPayload = Schema.Union(\n Schema.Struct({\n type: Schema.Literal('begin-compute'),\n nodeId: Schema.String,\n /**\n * Names of the inputs begin computed.\n */\n inputs: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal('end-compute'),\n nodeId: Schema.String,\n /**\n * Names of the outputs computed.\n */\n outputs: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal('compute-input'),\n nodeId: Schema.String,\n property: Schema.String,\n value: Schema.Any,\n }),\n Schema.Struct({\n type: Schema.Literal('compute-output'),\n nodeId: Schema.String,\n property: Schema.String,\n value: Schema.Any,\n }),\n Schema.Struct({\n type: Schema.Literal('custom'),\n nodeId: Schema.String,\n event: Schema.Any,\n }),\n);\nexport type ComputeEventPayload = Schema.Schema.Type<typeof ComputeEventPayload>;\n\nexport const ComputeEvent = Schema.Struct({\n payload: ComputeEventPayload,\n}).pipe(Type.object({ typename: 'org.dxos.type.compute-event', version: '0.1.0' }));\n\n/**\n * Logs event for the compute workflows.\n */\nexport class ComputeEventLogger extends Context.Tag('@dxos/functions/ComputeEventLogger')<\n ComputeEventLogger,\n { readonly log: (event: ComputeEventPayload) => void; readonly nodeId: string | undefined }\n>() {\n static noop: Context.Tag.Service<ComputeEventLogger> = {\n log: () => {},\n nodeId: undefined,\n };\n\n /**\n * Implements ComputeEventLogger using TracingService.\n */\n static layerFromTracing = Layer.effect(\n ComputeEventLogger,\n Effect.gen(function* () {\n const tracing = yield* TracingService;\n return {\n log: (event: ComputeEventPayload) => {\n tracing.write(Obj.make(ComputeEvent, { payload: event }), tracing.getTraceContext());\n },\n nodeId: undefined,\n };\n }),\n );\n}\n\nexport const logCustomEvent = (data: any) =>\n Effect.gen(function* () {\n const logger = yield* ComputeEventLogger;\n if (!logger.nodeId) {\n throw new Error('logCustomEvent must be called within a node compute function');\n }\n logger.log({\n type: 'custom',\n nodeId: logger.nodeId,\n event: data,\n });\n });\n\nexport const createDefectLogger = <A, E, R>(): ((self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>\n Effect.catchAll((error) =>\n Effect.gen(function* () {\n log.error('unhandled effect error', { error });\n throw error;\n }),\n );\n\nexport const createEventLogger = (\n level: LogLevel,\n message: string = 'event',\n): Context.Tag.Service<ComputeEventLogger> => {\n const logFunction = (\n {\n [LogLevel.WARN]: log.warn,\n [LogLevel.VERBOSE]: log.verbose,\n [LogLevel.DEBUG]: log.debug,\n [LogLevel.INFO]: log.info,\n [LogLevel.ERROR]: log.error,\n } as any\n )[level];\n invariant(logFunction);\n return {\n log: (event: ComputeEventPayload) => {\n logFunction(message, event);\n },\n nodeId: undefined,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { AgentStatus } from '@dxos/ai';\nimport { type DXN, Obj } from '@dxos/echo';\nimport { ObjectId } from '@dxos/keys';\nimport { Message } from '@dxos/types';\n\nimport type { Trigger } from '../types';\n\n/**\n * Provides a way for compute primitives (functions, workflows, tools)\n * to emit an execution trace as a series of structured ECHO objects.\n */\nexport class TracingService extends Context.Tag('@dxos/functions/TracingService')<\n TracingService,\n {\n /**\n * Gets the parent message ID.\n */\n getTraceContext: () => TracingService.TraceContext;\n\n /**\n * Write an event to the tracing queue.\n * @param event - The event to write. Must be an a typed object.\n */\n write: (event: Obj.Unknown, traceContext: TracingService.TraceContext) => void;\n\n traceInvocationStart({\n payload,\n target,\n }: {\n payload: TracingService.FunctionInvocationPayload;\n target?: DXN;\n }): Effect.Effect<TracingService.InvocationTraceData>;\n\n traceInvocationEnd({\n trace,\n exception,\n }: {\n trace: TracingService.InvocationTraceData;\n exception?: any;\n }): Effect.Effect<void>;\n }\n>() {\n static noop: Context.Tag.Service<TracingService> = {\n getTraceContext: () => ({}),\n write: () => {},\n traceInvocationStart: () =>\n Effect.sync(() => ({ invocationId: ObjectId.random(), invocationTraceQueue: undefined })),\n traceInvocationEnd: () => Effect.sync(() => {}),\n };\n\n static layerNoop: Layer.Layer<TracingService> = Layer.succeed(TracingService, TracingService.noop);\n\n /**\n * Creates a TracingService layer that emits events to the parent tracing service.\n */\n static layerSubframe = (mapContext: (currentContext: TracingService.TraceContext) => TracingService.TraceContext) =>\n Layer.effect(\n TracingService,\n Effect.gen(function* () {\n const tracing = yield* TracingService;\n const context = mapContext(tracing.getTraceContext());\n return {\n write: (event, context) => tracing.write(event, context),\n getTraceContext: () => context,\n traceInvocationStart: () => Effect.die('Tracing invocation inside another invocation is not supported.'),\n traceInvocationEnd: () => Effect.die('Tracing invocation inside another invocation is not supported.'),\n };\n }),\n );\n\n /**\n * Create sublayer to trace an invocation.\n * @param data\n * @returns\n */\n static layerInvocation = (data: TracingService.InvocationTraceData) =>\n TracingService.layerSubframe((context) => ({\n ...context,\n currentInvocation: data,\n }));\n\n /**\n * Emit the current human-readable execution status.\n */\n static emitStatus: (\n data: Omit<Obj.MakeProps<typeof AgentStatus>, 'created'>,\n ) => Effect.Effect<void, never, TracingService> = Effect.fnUntraced(function* (data) {\n const tracing = yield* TracingService;\n tracing.write(\n Obj.make(AgentStatus, {\n parentMessage: tracing.getTraceContext().parentMessage,\n toolCallId: tracing.getTraceContext().toolCallId,\n created: new Date().toISOString(),\n ...data,\n }),\n tracing.getTraceContext(),\n );\n });\n\n static emitConverationMessage: (\n data: Obj.MakeProps<typeof Message.Message>,\n ) => Effect.Effect<void, never, TracingService> = Effect.fnUntraced(function* (data) {\n const tracing = yield* TracingService;\n tracing.write(\n Obj.make(Message.Message, {\n parentMessage: tracing.getTraceContext().parentMessage,\n ...data,\n properties: {\n [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,\n ...data.properties,\n },\n }),\n tracing.getTraceContext(),\n );\n });\n}\n\nexport namespace TracingService {\n export interface TraceContext {\n currentInvocation?: InvocationTraceData;\n\n /**\n * If this thread sprung from a tool call, this is the ID of the message containing the tool call.\n */\n parentMessage?: ObjectId;\n\n /**\n * If the current thread is a byproduct of a tool call, this is the ID of the tool call.\n */\n toolCallId?: string;\n\n debugInfo?: unknown;\n }\n\n /**\n * Trace data for a function/trigger invocation.\n */\n export interface InvocationTraceData {\n invocationId: ObjectId;\n invocationTraceQueue?: DXN.String;\n }\n\n /**\n * Payload for a function/trigger invocation.\n */\n export interface FunctionInvocationPayload {\n data?: any;\n inputNodeId?: string;\n trigger?: {\n id: string;\n kind: Trigger.Kind;\n };\n }\n}\n\n/**\n * Goes into {@link Message['properties']}\n */\nexport const MESSAGE_PROPERTY_TOOL_CALL_ID = 'toolCallId' as const;\n", "//\n// Copyright 2025 DXOS.org\n//\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport type { FunctionNotFoundError } from '../errors';\nimport { type FunctionDefinition, type InvocationServices } from '../sdk';\n\nexport class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<\n FunctionInvocationService,\n {\n invokeFunction<I, O>(\n functionDef: FunctionDefinition<I, O, any>,\n input: I,\n ): Effect.Effect<O, never, InvocationServices>;\n\n resolveFunction(key: string): Effect.Effect<FunctionDefinition.Any, FunctionNotFoundError>;\n }\n>() {\n static layerNotAvailable = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('FunctionInvocationService is not avaialble.'),\n resolveFunction: () => Effect.die('FunctionInvocationService is not available.'),\n });\n\n static invokeFunction = <I, O>(\n functionDef: FunctionDefinition<I, O, any>,\n input: I,\n ): Effect.Effect<O, never, FunctionInvocationService | InvocationServices> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);\n\n static resolveFunction = (\n key: string,\n ): Effect.Effect<FunctionDefinition.Any, FunctionNotFoundError, FunctionInvocationService> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.resolveFunction)(key);\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport type { Entity } from '@dxos/echo';\nimport type { Queue, QueueAPI, QueueFactory } from '@dxos/echo-db';\nimport type { DXN, QueueSubspaceTag } from '@dxos/keys';\n\n/**\n * Gives access to all queues.\n */\nexport class QueueService extends Context.Tag('@dxos/functions/QueueService')<\n QueueService,\n {\n /**\n * API to access the queues.\n */\n readonly queues: QueueAPI;\n\n /**\n * The queue that is used to store the context of the current research.\n * @deprecated Use `ContextQueueService` instead.\n */\n readonly queue: Queue | undefined;\n }\n>() {\n static notAvailable = Layer.succeed(QueueService, {\n queues: {\n get(_dxn) {\n throw new Error('Queues not available');\n },\n create() {\n throw new Error('Queues not available');\n },\n },\n queue: undefined,\n });\n\n static make = (queues: QueueFactory, queue?: Queue): Context.Tag.Service<QueueService> => {\n return {\n queues,\n queue,\n };\n };\n\n static layer = (queues: QueueFactory, queue?: Queue): Layer.Layer<QueueService> =>\n Layer.succeed(QueueService, QueueService.make(queues, queue));\n\n /**\n * Gets a queue by its DXN.\n */\n static getQueue = <T extends Entity.Unknown = Entity.Unknown>(\n dxn: DXN,\n ): Effect.Effect<Queue<T>, never, QueueService> => QueueService.pipe(Effect.map(({ queues }) => queues.get<T>(dxn)));\n\n /**\n * Creates a new queue.\n */\n static createQueue = <T extends Entity.Unknown = Entity.Unknown>(options?: {\n subspaceTag?: QueueSubspaceTag;\n }): Effect.Effect<Queue<T>, never, QueueService> =>\n QueueService.pipe(Effect.map(({ queues }) => queues.create<T>(options)));\n\n static append = <T extends Entity.Unknown = Entity.Unknown>(queue: Queue<T>, objects: T[]): Effect.Effect<void> =>\n Effect.promise(() => queue.append(objects));\n}\n\n/**\n * Gives access to a specific queue passed as a context.\n */\nexport class ContextQueueService extends Context.Tag('@dxos/functions/ContextQueueService')<\n ContextQueueService,\n {\n readonly queue: Queue;\n }\n>() {\n static layer = (queue: Queue) => Layer.succeed(ContextQueueService, { queue });\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { AiModelResolver, AiService } from '@dxos/ai';\nimport { AnthropicResolver } from '@dxos/ai/resolvers';\nimport { LifecycleState, Resource } from '@dxos/context';\nimport { Database, Feed, JsonSchema, Ref, type Type } from '@dxos/echo';\nimport { refFromEncodedReference } from '@dxos/echo/internal';\nimport { EchoClient, type EchoDatabaseImpl, type QueueFactory, createFeedServiceLayer } from '@dxos/echo-db';\nimport { runAndForwardErrors } from '@dxos/effect';\nimport { assertState, failedInvariant, invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { type FunctionProtocol } from '@dxos/protocols';\n\nimport { FunctionError } from '../errors';\nimport { FunctionDefinition, type FunctionServices } from '../sdk';\nimport { CredentialsService, FunctionInvocationService, QueueService, TracingService } from '../services';\n\nimport { FunctionsAiHttpClient } from './functions-ai-http-client';\n\n/**\n * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.\n */\nexport const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.Func => {\n if (!FunctionDefinition.isFunction(func)) {\n throw new TypeError('Invalid function definition');\n }\n\n return {\n meta: {\n key: func.key,\n name: func.name,\n description: func.description,\n inputSchema: JsonSchema.toJsonSchema(func.inputSchema),\n outputSchema: func.outputSchema === undefined ? undefined : JsonSchema.toJsonSchema(func.outputSchema),\n services: func.services,\n },\n handler: async ({ data, context }) => {\n if (\n (func.services.includes(Database.Service.key) ||\n func.services.includes(QueueService.key) ||\n func.services.includes(Feed.Service.key)) &&\n (!context.services.dataService || !context.services.queryService)\n ) {\n throw new FunctionError({\n message: 'Services not provided: dataService, queryService',\n });\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (!SchemaAST.isAnyKeyword(func.inputSchema.ast)) {\n try {\n Schema.validateSync(func.inputSchema)(data);\n } catch (error) {\n throw new FunctionError({ message: 'Invalid input schema', cause: error });\n }\n }\n\n await using funcContext = await new FunctionContext(context).open();\n\n if (func.types.length > 0) {\n invariant(funcContext.db, 'Database is required for functions with types');\n await funcContext.db.graph.schemaRegistry.register(func.types as Type.AnyEntity[]);\n }\n\n const dataWithDecodedRefs =\n funcContext.db && !SchemaAST.isAnyKeyword(func.inputSchema.ast)\n ? decodeRefsFromSchema(func.inputSchema.ast, data, funcContext.db)\n : data;\n\n let result = await func.handler({\n // TODO(dmaretskyi): Fix the types.\n context: context as any,\n data: dataWithDecodedRefs,\n });\n\n if (Effect.isEffect(result)) {\n result = await runAndForwardErrors(\n (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(\n Effect.orDie,\n Effect.provide(funcContext.createLayer()),\n ),\n );\n }\n\n if (func.outputSchema && !SchemaAST.isAnyKeyword(func.outputSchema.ast)) {\n Schema.validateSync(func.outputSchema)(result);\n }\n\n return result;\n } catch (error) {\n // TODO(dmaretskyi): We might do error wrapping here and add extra context.\n throw error;\n }\n },\n };\n};\n\n/**\n * Container for services and context for a function.\n */\nclass FunctionContext extends Resource {\n readonly context: FunctionProtocol.Context;\n readonly client: EchoClient | undefined;\n db: EchoDatabaseImpl | undefined;\n queues: QueueFactory | undefined;\n\n constructor(context: FunctionProtocol.Context) {\n super();\n this.context = context;\n if (context.services.dataService && context.services.queryService) {\n this.client = new EchoClient().connectToService({\n dataService: context.services.dataService,\n queryService: context.services.queryService,\n queueService: context.services.queueService,\n });\n }\n }\n\n override async _open() {\n await this.client?.open();\n this.db =\n this.client && this.context.spaceId\n ? this.client.constructDatabase({\n spaceId: this.context.spaceId ?? failedInvariant(),\n spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),\n reactiveSchemaQuery: false,\n preloadSchemaOnOpen: false,\n })\n : undefined;\n\n await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context'));\n await this.db?.open();\n this.queues =\n this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : undefined;\n }\n\n override async _close() {\n await this.db?.close();\n await this.client?.close();\n }\n\n createLayer(): Layer.Layer<FunctionServices> {\n assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');\n\n const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;\n const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;\n const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;\n const credentials = dbLayer\n ? CredentialsService.layerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))\n : CredentialsService.configuredLayer([]);\n const functionInvocationService = MockedFunctionInvocationService;\n const tracing = TracingService.layerNoop;\n\n const aiLayer = this.context.services.functionsAiService\n ? AiModelResolver.AiModelResolver.buildAiService.pipe(\n Layer.provide(\n AnthropicResolver.make().pipe(\n Layer.provide(\n AnthropicClient.layer({\n // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.\n apiUrl: 'http://internal/provider/anthropic',\n }).pipe(Layer.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))),\n ),\n ),\n ),\n )\n : AiService.notAvailable;\n\n return Layer.mergeAll(dbLayer, queuesLayer, feedLayer, credentials, functionInvocationService, aiLayer, tracing);\n }\n}\n\nconst MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),\n resolveFunction: () => Effect.die('Not implemented.'),\n});\n\nconst decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {\n if (value == null) {\n return value;\n }\n\n const encoded = SchemaAST.encodedBoundAST(ast);\n if (Ref.isRefType(encoded)) {\n if (Ref.isRef(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {\n const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });\n return refFromEncodedReference(value as any, resolver);\n }\n\n return value;\n }\n\n switch (encoded._tag) {\n case 'TypeLiteral': {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return value;\n }\n const result: Record<string, unknown> = { ...(value as any) };\n for (const prop of SchemaAST.getPropertySignatures(encoded)) {\n const key = prop.name.toString();\n if (key in result) {\n result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);\n }\n }\n return result;\n }\n\n case 'TupleType': {\n if (!Array.isArray(value)) {\n return value;\n }\n\n // For arrays, effect uses TupleType with empty elements and a single rest element.\n if (encoded.elements.length === 0 && encoded.rest.length === 1) {\n const elementType = encoded.rest[0].type;\n return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));\n }\n\n return value;\n }\n\n case 'Union': {\n // Optional values are represented as union with undefined.\n const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));\n if (nonUndefined.length === 1) {\n return decodeRefsFromSchema(nonUndefined[0], value, db);\n }\n\n // For other unions we can't safely pick a branch without validating.\n return value;\n }\n\n case 'Suspend': {\n return decodeRefsFromSchema(encoded.f(), value, db);\n }\n\n case 'Refinement': {\n return decodeRefsFromSchema(encoded.from, value, db);\n }\n\n default: {\n return value;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Headers from '@effect/platform/Headers';\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientError from '@effect/platform/HttpClientError';\nimport * as HttpClientResponse from '@effect/platform/HttpClientResponse';\nimport * as Effect from 'effect/Effect';\nimport * as FiberRef from 'effect/FiberRef';\nimport * as Layer from 'effect/Layer';\nimport * as Stream from 'effect/Stream';\n\nimport { log } from '@dxos/log';\nimport { type EdgeFunctionEnv, ErrorCodec } from '@dxos/protocols';\n/**\n * Copy pasted from https://github.com/Effect-TS/effect/blob/main/packages/platform/src/internal/fetchHttpClient.ts\n */\nexport const requestInitTagKey = '@effect/platform/FetchHttpClient/FetchOptions';\n\nexport class FunctionsAiHttpClient {\n static make = (service: EdgeFunctionEnv.FunctionsAiService) =>\n HttpClient.make((request, url, signal, fiber) => {\n const context = fiber.getFiberRef(FiberRef.currentContext);\n const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {};\n const headers = options.headers\n ? Headers.merge(Headers.fromInput(options.headers), request.headers)\n : request.headers;\n\n const send = (body: BodyInit | undefined) =>\n Effect.tryPromise({\n try: () =>\n service.fetch(\n new Request(url, {\n ...options,\n method: request.method,\n headers,\n body,\n // Note: Don't pass signal - it can't be serialized through RPC\n }),\n ),\n catch: (cause) => {\n log.error('Failed to fetch', { errorSerialized: ErrorCodec.encode(cause as Error) });\n return new HttpClientError.RequestError({\n request,\n reason: 'Transport',\n cause,\n });\n },\n }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response)));\n\n switch (request.body._tag) {\n case 'Raw':\n case 'Uint8Array':\n return send(request.body.body as any);\n case 'FormData':\n return send(request.body.formData);\n case 'Stream':\n return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect.flatMap(send));\n }\n\n return send(undefined);\n });\n\n static layer = (service: EdgeFunctionEnv.FunctionsAiService) =>\n Layer.succeed(HttpClient.HttpClient, FunctionsAiHttpClient.make(service));\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;AAIA,SAASA,iBAAwC;AAE1C,IAAMC,2BAAN,cAAuCC,UAAUC,OAAO,uBAAuB,uBAAA,EAAA;EACpF,YAAYC,SAAiBC,SAA6C;AACxE,UAAM;MAAEC,SAAS;QAAEF;MAAQ;MAAG,GAAGC;IAAQ,CAAA;EAC3C;AACF;AAEO,IAAME,wBAAN,cAAoCL,UAAUC,OAAO,oBAAoB,oBAAA,EAAA;EAC9E,YAAYK,aAAqBH,SAA6C;AAC5E,UAAM;MAAEC,SAAS;QAAEG,UAAUD;MAAY;MAAG,GAAGH;IAAQ,CAAA;EACzD;AACF;AAEO,IAAMK,gBAAN,cAA4BR,UAAUC,OAAO,iBAAiB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B,eAAOA;MACT;AAGA,UAAIC,QAAQgB,SAASvF,WAAW,KAAKuE,QAAQiB,KAAKxF,WAAW,GAAG;AAC9D,cAAMyF,cAAclB,QAAQiB,KAAK,CAAA,EAAGF;AACpC,eAAQhB,OAAoBoB,IAAI,CAACC,SAASpF,qBAAqBkF,aAAaE,MAAMzF,EAAAA,CAAAA;MACpF;AAEA,aAAOoE;IACT;IAEA,KAAK,SAAS;AAEZ,YAAMsB,eAAerB,QAAQxE,MAAM8F,OAAO,CAACC,MAAM,CAAWC,8BAAmBD,CAAAA,CAAAA;AAC/E,UAAIF,aAAa5F,WAAW,GAAG;AAC7B,eAAOO,qBAAqBqF,aAAa,CAAA,GAAItB,QAAOpE,EAAAA;MACtD;AAGA,aAAOoE;IACT;IAEA,KAAK,WAAW;AACd,aAAO/D,qBAAqBgE,QAAQyB,EAAC,GAAI1B,QAAOpE,EAAAA;IAClD;IAEA,KAAK,cAAc;AACjB,aAAOK,qBAAqBgE,QAAQ0B,MAAM3B,QAAOpE,EAAAA;IACnD;IAEA,SAAS;AACP,aAAOoE;IACT;EACF;AACF;",
|
|
6
|
+
"names": ["BaseError", "ServiceNotAvailableError", "BaseError", "extend", "service", "options", "context", "FunctionNotFoundError", "functionKey", "function", "FunctionError", "TriggerStateNotFoundError", "Effect", "Schema", "Effect", "Schema", "JsonSchema", "Obj", "assertArgument", "failedInvariant", "Operation", "make", "Schema", "Annotation", "JsonSchema", "Obj", "Ref", "Type", "SystemTypeAnnotation", "Schema", "Annotation", "Obj", "Ref", "Type", "FormInputAnnotation", "Text", "Script", "Struct", "name", "String", "pipe", "optional", "description", "changed", "Boolean", "FormInputAnnotation", "set", "source", "Ref", "Text", "Type", "object", "typename", "version", "Annotation", "LabelAnnotation", "make", "props", "Obj", "Function", "Struct", "key", "optional", "String", "annotations", "description", "name", "NonEmptyString", "version", "updated", "source", "Ref", "Script", "inputSchema", "JsonSchema", "outputSchema", "services", "Array", "binding", "pipe", "Type", "object", "typename", "Annotation", "LabelAnnotation", "set", "IconAnnotation", "icon", "hue", "SystemTypeAnnotation", "make", "props", "Obj", "setFrom", "target", "change", "t", "JSON", "parse", "stringify", "undefined", "getMeta", "keys", "make", "Schema", "SchemaAST", "Annotation", "Obj", "QueryAST", "Ref", "Type", "OptionsAnnotationId", "SystemTypeAnnotation", "DXN", "Expando", "Kinds", "kindLiteralAnnotations", "title", "EmailSpec", "Struct", "kind", "Literal", "annotations", "QueueSpec", "queue", "DXN", "Schema", "SubscriptionSpec", "query", "raw", "optional", "String", "ast", "QueryAST", "Query", "options", "deep", "Boolean", "delay", "Number", "TimerSpec", "cron", "ExamplesAnnotationId", "WebhookSpec", "method", "OptionsAnnotationId", "port", "Spec", "Union", "TriggerSchema", "function", "Ref", "Expando", "inputNodeId", "enabled", "spec", "concurrency", "default", "description", "input", "Record", "key", "value", "Any", "pipe", "Type", "object", "typename", "version", "Annotation", "IconAnnotation", "set", "icon", "hue", "SystemTypeAnnotation", "Trigger", "make", "props", "Obj", "Schema", "DXN", "Obj", "Ref", "EmailEvent", "Struct", "from", "String", "to", "subject", "created", "body", "QueueEvent", "queue", "DXN", "Schema", "item", "Any", "cursor", "SubscriptionEvent", "type", "Ref", "Obj", "Unknown", "changedObjectId", "optional", "TimerEvent", "tick", "Number", "WebhookEvent", "url", "method", "Literal", "headers", "Record", "key", "value", "bodyText", "TriggerEvent", "Union", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "getUserFunctionIdInMetadata", "meta", "keys", "find", "key", "source", "id", "setUserFunctionIdInMetadata", "functionId", "Error", "push", "typeId", "Symbol", "for", "defineFunction", "key", "name", "description", "inputSchema", "outputSchema", "Any", "handler", "types", "services", "isSchema", "Error", "limit", "stackTraceLimit", "traceError", "cache", "captureStackTrace", "stack", "undefined", "split", "trim", "handlerWithSpan", "args", "result", "isEffect", "withSpan", "getServiceKeys", "map", "tag", "failedInvariant", "toOperation", "functionDef", "op", "Operation", "make", "schema", "input", "output", "meta", "operationHandler", "context", "data", "Promise", "tryPromise", "succeed", "FunctionDefinition", "isFunction", "value", "serialize", "assertArgument", "serializeFunction", "deserialize", "functionObj", "Obj", "instanceOf", "Function", "deserializeFunction", "fn", "version", "JsonSchema", "toJsonSchema", "deployedFunctionId", "change", "setUserFunctionIdInMetadata", "getMeta", "Unknown", "toEffectSchema", "getUserFunctionIdInMetadata", "defineFunction", "key", "name", "description", "inputSchema", "Struct", "iterations", "optional", "Number", "annotations", "default", "outputSchema", "result", "String", "handler", "fn", "data", "a", "b", "i", "toString", "Console", "Effect", "Schema", "defineFunction", "key", "name", "description", "inputSchema", "Any", "outputSchema", "handler", "fn", "data", "log", "Effect", "Schema", "defineFunction", "key", "name", "description", "inputSchema", "Struct", "duration", "optional", "Number", "annotations", "default", "outputSchema", "Void", "handler", "fn", "data", "sleep", "ExampleFunctions", "Fibonacci", "Reply", "Sleep", "HttpClient", "HttpClientRequest", "Context", "Effect", "Layer", "Redacted", "Query", "Database", "AccessToken", "CredentialsService", "Tag", "getCredential", "query", "gen", "credentials", "promise", "getApiKey", "credential", "apiKey", "Error", "service", "make", "configuredLayer", "succeed", "ConfiguredCredentialsService", "layerConfig", "effect", "serviceCredentials", "forEach", "value", "layerFromDatabase", "caching", "dbService", "Database", "Service", "cache", "Map", "queryCredentials", "cacheKey", "JSON", "stringify", "has", "get", "accessTokens", "db", "Query", "type", "AccessToken", "run", "filter", "accessToken", "source", "map", "token", "set", "length", "addCredentials", "push", "find", "withAuthorization", "kind", "mapRequest", "request", "authorization", "setHeader", "Context", "Effect", "Layer", "Schema", "Obj", "Type", "invariant", "LogLevel", "log", "Context", "Effect", "Layer", "AgentStatus", "Obj", "ObjectId", "Message", "TracingService", "Tag", "noop", "getTraceContext", "write", "traceInvocationStart", "sync", "invocationId", "ObjectId", "random", "invocationTraceQueue", "undefined", "traceInvocationEnd", "layerNoop", "succeed", "layerSubframe", "mapContext", "effect", "gen", "tracing", "context", "event", "die", "layerInvocation", "data", "currentInvocation", "emitStatus", "fnUntraced", "Obj", "make", "AgentStatus", "parentMessage", "toolCallId", "created", "Date", "toISOString", "emitConverationMessage", "Message", "properties", "MESSAGE_PROPERTY_TOOL_CALL_ID", "ComputeEventPayload", "Union", "Struct", "type", "Literal", "nodeId", "String", "inputs", "Array", "outputs", "property", "value", "Any", "event", "ComputeEvent", "payload", "pipe", "Type", "object", "typename", "version", "ComputeEventLogger", "Tag", "noop", "log", "undefined", "layerFromTracing", "effect", "gen", "tracing", "TracingService", "write", "Obj", "make", "getTraceContext", "logCustomEvent", "data", "logger", "Error", "createDefectLogger", "catchAll", "error", "createEventLogger", "level", "message", "logFunction", "LogLevel", "WARN", "warn", "VERBOSE", "verbose", "DEBUG", "debug", "INFO", "info", "ERROR", "invariant", "Context", "Effect", "Layer", "FunctionInvocationService", "Tag", "layerNotAvailable", "succeed", "invokeFunction", "die", "resolveFunction", "functionDef", "input", "serviceFunctionEffect", "service", "key", "Context", "Effect", "Layer", "QueueService", "Tag", "notAvailable", "succeed", "queues", "get", "_dxn", "Error", "create", "queue", "undefined", "make", "layer", "getQueue", "dxn", "pipe", "map", "createQueue", "options", "append", "objects", "promise", "ContextQueueService", "AnthropicClient", "Effect", "Layer", "Schema", "SchemaAST", "AiModelResolver", "AiService", "AnthropicResolver", "LifecycleState", "Resource", "Database", "Feed", "JsonSchema", "Ref", "refFromEncodedReference", "EchoClient", "createFeedServiceLayer", "runAndForwardErrors", "assertState", "failedInvariant", "invariant", "PublicKey", "Headers", "HttpClient", "HttpClientError", "HttpClientResponse", "Effect", "FiberRef", "Layer", "Stream", "log", "ErrorCodec", "requestInitTagKey", "FunctionsAiHttpClient", "make", "service", "request", "url", "signal", "fiber", "context", "getFiberRef", "currentContext", "options", "unsafeMap", "get", "headers", "merge", "fromInput", "send", "body", "tryPromise", "try", "fetch", "Request", "method", "catch", "cause", "error", "errorSerialized", "encode", "RequestError", "reason", "pipe", "map", "response", "fromWeb", "_tag", "formData", "toReadableStreamEffect", "stream", "flatMap", "undefined", "layer", "succeed", "wrapFunctionHandler", "func", "FunctionDefinition", "isFunction", "TypeError", "meta", "key", "name", "description", "inputSchema", "JsonSchema", "toJsonSchema", "outputSchema", "undefined", "services", "handler", "data", "context", "includes", "Database", "Service", "QueueService", "Feed", "dataService", "queryService", "FunctionError", "message", "isAnyKeyword", "ast", "Schema", "validateSync", "error", "cause", "funcContext", "FunctionContext", "open", "types", "length", "invariant", "db", "graph", "schemaRegistry", "register", "dataWithDecodedRefs", "decodeRefsFromSchema", "result", "isEffect", "runAndForwardErrors", "pipe", "orDie", "provide", "createLayer", "Resource", "client", "queues", "EchoClient", "connectToService", "queueService", "_open", "spaceId", "constructDatabase", "failedInvariant", "spaceKey", "PublicKey", "fromHex", "reactiveSchemaQuery", "preloadSchemaOnOpen", "setSpaceRoot", "spaceRootUrl", "constructQueueFactory", "_close", "close", "assertState", "_lifecycleState", "LifecycleState", "OPEN", "dbLayer", "layer", "notAvailable", "queuesLayer", "feedLayer", "createFeedServiceLayer", "credentials", "CredentialsService", "layerFromDatabase", "caching", "configuredLayer", "functionInvocationService", "MockedFunctionInvocationService", "tracing", "TracingService", "layerNoop", "aiLayer", "functionsAiService", "AiModelResolver", "buildAiService", "AnthropicResolver", "make", "apiUrl", "FunctionsAiHttpClient", "AiService", "mergeAll", "succeed", "FunctionInvocationService", "invokeFunction", "die", "resolveFunction", "value", "encoded", "encodedBoundAST", "Ref", "isRefType", "isRef", "resolver", "createRefResolver", "space", "refFromEncodedReference", "_tag", "Array", "isArray", "prop", "getPropertySignatures", "toString", "type", "elements", "rest", "elementType", "map", "item", "nonUndefined", "filter", "t", "isUndefinedKeyword", "f", "from"]
|
|
7
|
+
}
|