@dxos/functions 0.8.4-main.67995b8 → 0.8.4-main.70d3990

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/dist/lib/browser/index.mjs +895 -366
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +895 -366
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +89 -28
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +7 -0
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/example/reply.d.ts +3 -0
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/example/sleep.d.ts +5 -0
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +5 -7
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/protocol/index.d.ts +2 -0
  22. package/dist/types/src/protocol/index.d.ts.map +1 -0
  23. package/dist/types/src/protocol/protocol.d.ts +7 -0
  24. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  25. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  26. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  27. package/dist/types/src/sdk.d.ts +100 -0
  28. package/dist/types/src/sdk.d.ts.map +1 -0
  29. package/dist/types/src/services/credentials.d.ts +19 -3
  30. package/dist/types/src/services/credentials.d.ts.map +1 -1
  31. package/dist/types/src/services/event-logger.d.ts +20 -5
  32. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  33. package/dist/types/src/services/function-invocation-service.d.ts +11 -0
  34. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  35. package/dist/types/src/services/index.d.ts +6 -6
  36. package/dist/types/src/services/index.d.ts.map +1 -1
  37. package/dist/types/src/services/queues.d.ts +21 -5
  38. package/dist/types/src/services/queues.d.ts.map +1 -1
  39. package/dist/types/src/services/tracing.d.ts +34 -6
  40. package/dist/types/src/services/tracing.d.ts.map +1 -1
  41. package/dist/types/src/types/Function.d.ts +63 -0
  42. package/dist/types/src/types/Function.d.ts.map +1 -0
  43. package/dist/types/src/types/Script.d.ts +28 -0
  44. package/dist/types/src/types/Script.d.ts.map +1 -0
  45. package/dist/types/src/types/Trigger.d.ts +141 -0
  46. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  47. package/dist/types/src/types/TriggerEvent.d.ts +43 -0
  48. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  49. package/dist/types/src/types/index.d.ts +6 -0
  50. package/dist/types/src/types/index.d.ts.map +1 -0
  51. package/dist/types/src/types/url.d.ts +12 -0
  52. package/dist/types/src/types/url.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +21 -74
  55. package/src/errors.ts +13 -5
  56. package/src/example/fib.ts +32 -0
  57. package/src/example/forex-effect.ts +40 -0
  58. package/src/example/index.ts +13 -0
  59. package/src/example/reply.ts +21 -0
  60. package/src/example/sleep.ts +24 -0
  61. package/src/index.ts +5 -9
  62. package/src/{executor → protocol}/index.ts +1 -1
  63. package/src/protocol/protocol.test.ts +59 -0
  64. package/src/protocol/protocol.ts +156 -0
  65. package/src/sdk.ts +240 -0
  66. package/src/services/credentials.ts +84 -5
  67. package/src/services/event-logger.ts +13 -4
  68. package/src/services/function-invocation-service.ts +23 -0
  69. package/src/services/index.ts +7 -6
  70. package/src/services/queues.ts +34 -10
  71. package/src/services/tracing.ts +81 -17
  72. package/src/types/Function.ts +80 -0
  73. package/src/types/Script.ts +33 -0
  74. package/src/types/Trigger.ts +140 -0
  75. package/src/types/TriggerEvent.ts +62 -0
  76. package/src/types/index.ts +9 -0
  77. package/src/types/url.ts +31 -0
  78. package/dist/lib/browser/bundler/index.mjs +0 -247
  79. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  80. package/dist/lib/browser/chunk-6PTFLPCO.mjs +0 -462
  81. package/dist/lib/browser/chunk-6PTFLPCO.mjs.map +0 -7
  82. package/dist/lib/browser/edge/index.mjs +0 -69
  83. package/dist/lib/browser/edge/index.mjs.map +0 -7
  84. package/dist/lib/browser/testing/index.mjs +0 -59
  85. package/dist/lib/browser/testing/index.mjs.map +0 -7
  86. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  87. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  88. package/dist/lib/node-esm/chunk-NYJ2TSXO.mjs +0 -464
  89. package/dist/lib/node-esm/chunk-NYJ2TSXO.mjs.map +0 -7
  90. package/dist/lib/node-esm/edge/index.mjs +0 -71
  91. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  92. package/dist/lib/node-esm/testing/index.mjs +0 -60
  93. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  94. package/dist/types/src/bundler/bundler.d.ts +0 -50
  95. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  96. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  97. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  98. package/dist/types/src/bundler/index.d.ts +0 -2
  99. package/dist/types/src/bundler/index.d.ts.map +0 -1
  100. package/dist/types/src/edge/functions.d.ts +0 -16
  101. package/dist/types/src/edge/functions.d.ts.map +0 -1
  102. package/dist/types/src/edge/index.d.ts +0 -2
  103. package/dist/types/src/edge/index.d.ts.map +0 -1
  104. package/dist/types/src/executor/executor.d.ts +0 -8
  105. package/dist/types/src/executor/executor.d.ts.map +0 -1
  106. package/dist/types/src/executor/index.d.ts +0 -2
  107. package/dist/types/src/executor/index.d.ts.map +0 -1
  108. package/dist/types/src/handler.d.ts +0 -62
  109. package/dist/types/src/handler.d.ts.map +0 -1
  110. package/dist/types/src/schema.d.ts +0 -38
  111. package/dist/types/src/schema.d.ts.map +0 -1
  112. package/dist/types/src/services/database.d.ts +0 -30
  113. package/dist/types/src/services/database.d.ts.map +0 -1
  114. package/dist/types/src/services/local-function-execution.d.ts +0 -11
  115. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  116. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -15
  117. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  118. package/dist/types/src/services/service-container.d.ts +0 -56
  119. package/dist/types/src/services/service-container.d.ts.map +0 -1
  120. package/dist/types/src/services/service-registry.d.ts +0 -29
  121. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  122. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  123. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  124. package/dist/types/src/testing/index.d.ts +0 -3
  125. package/dist/types/src/testing/index.d.ts.map +0 -1
  126. package/dist/types/src/testing/layer.d.ts +0 -10
  127. package/dist/types/src/testing/layer.d.ts.map +0 -1
  128. package/dist/types/src/testing/logger.d.ts +0 -5
  129. package/dist/types/src/testing/logger.d.ts.map +0 -1
  130. package/dist/types/src/testing/services.d.ts +0 -59
  131. package/dist/types/src/testing/services.d.ts.map +0 -1
  132. package/dist/types/src/trace.d.ts +0 -124
  133. package/dist/types/src/trace.d.ts.map +0 -1
  134. package/dist/types/src/translations.d.ts +0 -12
  135. package/dist/types/src/translations.d.ts.map +0 -1
  136. package/dist/types/src/types.d.ts +0 -411
  137. package/dist/types/src/types.d.ts.map +0 -1
  138. package/dist/types/src/url.d.ts +0 -17
  139. package/dist/types/src/url.d.ts.map +0 -1
  140. package/src/bundler/bundler.test.ts +0 -59
  141. package/src/bundler/bundler.ts +0 -292
  142. package/src/bundler/index.ts +0 -5
  143. package/src/edge/functions.ts +0 -64
  144. package/src/edge/index.ts +0 -9
  145. package/src/executor/executor.ts +0 -54
  146. package/src/handler.ts +0 -120
  147. package/src/schema.ts +0 -57
  148. package/src/services/database.ts +0 -74
  149. package/src/services/local-function-execution.ts +0 -70
  150. package/src/services/remote-function-execution-service.ts +0 -66
  151. package/src/services/service-container.ts +0 -113
  152. package/src/services/service-registry.test.ts +0 -42
  153. package/src/services/service-registry.ts +0 -59
  154. package/src/testing/index.ts +0 -6
  155. package/src/testing/layer.ts +0 -31
  156. package/src/testing/logger.ts +0 -16
  157. package/src/testing/services.ts +0 -114
  158. package/src/trace.ts +0 -180
  159. package/src/translations.ts +0 -20
  160. package/src/types.ts +0 -211
  161. package/src/url.ts +0 -52
@@ -1,102 +1,192 @@
1
- import {
2
- ComputeEvent,
3
- ComputeEventLogger,
4
- ComputeEventPayload,
5
- ConfiguredCredentialsService,
6
- ContextQueueService,
7
- CredentialsService,
8
- DatabaseService,
9
- FunctionError,
10
- LocalFunctionExecutionService,
11
- QueueService,
12
- RemoteFunctionExecutionService,
13
- SERVICE_TAGS,
14
- ServiceContainer,
15
- ServiceNotAvailableError,
16
- TracingService,
17
- createDefectLogger,
18
- createEventLogger,
19
- logCustomEvent
20
- } from "./chunk-6PTFLPCO.mjs";
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
21
6
 
22
- // src/handler.ts
23
- import { Schema } from "effect";
24
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
25
- if (!Schema.isSchema(inputSchema)) {
26
- throw new Error("Input schema must be a valid schema");
7
+ // src/errors.ts
8
+ import { BaseError } from "@dxos/errors";
9
+ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
10
+ constructor(service, options) {
11
+ super({
12
+ context: {
13
+ service
14
+ },
15
+ ...options
16
+ });
27
17
  }
28
- if (typeof handler !== "function") {
29
- throw new Error("Handler must be a function");
18
+ };
19
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
20
+ constructor(functionKey, options) {
21
+ super({
22
+ context: {
23
+ function: functionKey
24
+ },
25
+ ...options
26
+ });
30
27
  }
31
- return {
32
- name,
33
- description,
34
- inputSchema,
35
- outputSchema,
36
- handler
37
- };
28
+ };
29
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
30
+ };
31
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
38
32
  };
39
33
 
40
- // src/schema.ts
41
- import { Schema as Schema2 } from "effect";
42
- import { Type } from "@dxos/echo";
43
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
44
- import { DataType } from "@dxos/schema";
45
- var ScriptType = Schema2.Struct({
46
- name: Schema2.optional(Schema2.String),
47
- description: Schema2.optional(Schema2.String),
34
+ // src/example/fib.ts
35
+ import * as Effect2 from "effect/Effect";
36
+ import * as Schema6 from "effect/Schema";
37
+
38
+ // src/sdk.ts
39
+ import * as Effect from "effect/Effect";
40
+ import * as Schema5 from "effect/Schema";
41
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
42
+ import { assertArgument, failedInvariant } from "@dxos/invariant";
43
+
44
+ // src/types/Function.ts
45
+ var Function_exports = {};
46
+ __export(Function_exports, {
47
+ Function: () => Function,
48
+ make: () => make2,
49
+ setFrom: () => setFrom
50
+ });
51
+ import * as Schema2 from "effect/Schema";
52
+ import { Annotation as Annotation2, JsonSchema, Obj as Obj2, Type as Type2 } from "@dxos/echo";
53
+ import { SystemTypeAnnotation } from "@dxos/echo/internal";
54
+
55
+ // src/types/Script.ts
56
+ var Script_exports = {};
57
+ __export(Script_exports, {
58
+ Script: () => Script,
59
+ make: () => make
60
+ });
61
+ import * as Schema from "effect/Schema";
62
+ import { Annotation, Obj, Ref, Type } from "@dxos/echo";
63
+ import { FormInputAnnotation } from "@dxos/echo/internal";
64
+ import { Text } from "@dxos/schema";
65
+ var Script = Schema.Struct({
66
+ name: Schema.String.pipe(Schema.optional),
67
+ description: Schema.String.pipe(Schema.optional),
48
68
  // TODO(burdon): Change to hash of deployed content.
49
69
  // Whether source has changed since last deploy.
50
- changed: Schema2.optional(Schema2.Boolean),
51
- source: Ref(DataType.Text)
70
+ changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),
71
+ source: Type.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
52
72
  }).pipe(Type.Obj({
53
73
  typename: "dxos.org/type/Script",
54
74
  version: "0.1.0"
55
- }), LabelAnnotation.set([
75
+ }), Annotation.LabelAnnotation.set([
56
76
  "name"
57
77
  ]));
58
- var FunctionType = Schema2.Struct({
59
- // TODO(burdon): Rename to id/uri?
78
+ var make = ({ source = "", ...props } = {}) => Obj.make(Script, {
79
+ ...props,
80
+ source: Ref.make(Text.make(source))
81
+ });
82
+
83
+ // src/types/Function.ts
84
+ var Function = Schema2.Struct({
85
+ /**
86
+ * Global registry ID.
87
+ * NOTE: The `key` property refers to the original registry entry.
88
+ */
89
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
90
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
91
+ // TODO(dmaretskyi): Make required.
92
+ key: Schema2.optional(Schema2.String).annotations({
93
+ description: "Unique registration key for the blueprint"
94
+ }),
60
95
  name: Schema2.NonEmptyString,
61
96
  version: Schema2.String,
62
97
  description: Schema2.optional(Schema2.String),
98
+ /**
99
+ * ISO date string of the last deployment.
100
+ */
101
+ updated: Schema2.optional(Schema2.String),
63
102
  // Reference to a source script if it exists within ECHO.
64
103
  // TODO(burdon): Don't ref ScriptType directly (core).
65
- source: Schema2.optional(Ref(ScriptType)),
66
- inputSchema: Schema2.optional(JsonSchemaType),
67
- outputSchema: Schema2.optional(JsonSchemaType),
104
+ source: Schema2.optional(Type2.Ref(Script)),
105
+ inputSchema: Schema2.optional(JsonSchema.JsonSchema),
106
+ outputSchema: Schema2.optional(JsonSchema.JsonSchema),
107
+ /**
108
+ * List of required services.
109
+ * Match the Context.Tag keys of the FunctionServices variants.
110
+ */
111
+ services: Schema2.optional(Schema2.Array(Schema2.String)),
68
112
  // Local binding to a function name.
69
113
  binding: Schema2.optional(Schema2.String)
70
- }).pipe(Type.Obj({
114
+ }).pipe(Type2.Obj({
71
115
  typename: "dxos.org/type/Function",
72
116
  version: "0.1.0"
73
- }), LabelAnnotation.set([
117
+ }), Annotation2.LabelAnnotation.set([
74
118
  "name"
75
- ]));
76
-
77
- // src/trace.ts
78
- import { Schema as Schema4 } from "effect";
79
- import { Type as Type2 } from "@dxos/echo";
80
- import { Queue } from "@dxos/echo-db";
81
- import { ObjectId } from "@dxos/echo-schema";
82
- import { log } from "@dxos/log";
119
+ ]), SystemTypeAnnotation.set(true));
120
+ var make2 = (props) => Obj2.make(Function, props);
121
+ var setFrom = (target, source) => {
122
+ target.key = source.key ?? target.key;
123
+ target.name = source.name ?? target.name;
124
+ target.version = source.version;
125
+ target.description = source.description;
126
+ target.updated = source.updated;
127
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : void 0;
128
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : void 0;
129
+ Obj2.getMeta(target).keys = JSON.parse(JSON.stringify(Obj2.getMeta(source).keys));
130
+ };
83
131
 
84
- // src/types.ts
85
- import { Schema as Schema3, SchemaAST } from "effect";
86
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
132
+ // src/types/Trigger.ts
133
+ var Trigger_exports = {};
134
+ __export(Trigger_exports, {
135
+ EmailSpec: () => EmailSpec,
136
+ Kinds: () => Kinds,
137
+ QueueSpec: () => QueueSpec,
138
+ Spec: () => Spec,
139
+ SubscriptionSpec: () => SubscriptionSpec,
140
+ TimerSpec: () => TimerSpec,
141
+ Trigger: () => Trigger,
142
+ WebhookSpec: () => WebhookSpec,
143
+ make: () => make3
144
+ });
145
+ import * as Schema3 from "effect/Schema";
146
+ import * as SchemaAST from "effect/SchemaAST";
147
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
148
+ import { OptionsAnnotationId, SystemTypeAnnotation as SystemTypeAnnotation2 } from "@dxos/echo/internal";
87
149
  import { DXN } from "@dxos/keys";
88
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
89
- TriggerKind2["Timer"] = "timer";
90
- TriggerKind2["Webhook"] = "webhook";
91
- TriggerKind2["Subscription"] = "subscription";
92
- TriggerKind2["Email"] = "email";
93
- TriggerKind2["Queue"] = "queue";
94
- return TriggerKind2;
95
- }({});
150
+ var Kinds = [
151
+ "email",
152
+ "queue",
153
+ "subscription",
154
+ "timer",
155
+ "webhook"
156
+ ];
96
157
  var kindLiteralAnnotations = {
97
158
  title: "Kind"
98
159
  };
99
- var TimerTriggerSchema = Schema3.Struct({
160
+ var EmailSpec = Schema3.Struct({
161
+ kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
162
+ }).pipe(Schema3.mutable);
163
+ var QueueSpec = Schema3.Struct({
164
+ kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
165
+ // TODO(dmaretskyi): Change to a reference.
166
+ queue: DXN.Schema
167
+ }).pipe(Schema3.mutable);
168
+ var SubscriptionSpec = Schema3.Struct({
169
+ kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
170
+ query: Schema3.Struct({
171
+ raw: Schema3.optional(Schema3.String.annotations({
172
+ title: "Query"
173
+ })),
174
+ ast: QueryAST.Query
175
+ }).pipe(Schema3.mutable),
176
+ options: Schema3.optional(Schema3.Struct({
177
+ // Watch changes to object (not just creation).
178
+ deep: Schema3.optional(Schema3.Boolean.annotations({
179
+ title: "Nested"
180
+ })),
181
+ // Debounce changes (delay in ms).
182
+ delay: Schema3.optional(Schema3.Number.annotations({
183
+ title: "Delay"
184
+ }))
185
+ }).annotations({
186
+ title: "Options"
187
+ }))
188
+ }).pipe(Schema3.mutable);
189
+ var TimerSpec = Schema3.Struct({
100
190
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
101
191
  cron: Schema3.String.annotations({
102
192
  title: "Cron",
@@ -105,14 +195,7 @@ var TimerTriggerSchema = Schema3.Struct({
105
195
  ]
106
196
  })
107
197
  }).pipe(Schema3.mutable);
108
- var EmailTriggerSchema = Schema3.Struct({
109
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
110
- }).pipe(Schema3.mutable);
111
- var QueueTriggerSchema = Schema3.Struct({
112
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
113
- queue: DXN.Schema
114
- }).pipe(Schema3.mutable);
115
- var WebhookTriggerSchema = Schema3.Struct({
198
+ var WebhookSpec = Schema3.Struct({
116
199
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
117
200
  method: Schema3.optional(Schema3.String.annotations({
118
201
  title: "Method",
@@ -125,71 +208,15 @@ var WebhookTriggerSchema = Schema3.Struct({
125
208
  title: "Port"
126
209
  }))
127
210
  }).pipe(Schema3.mutable);
128
- var QuerySchema = Schema3.Struct({
129
- type: Schema3.optional(Schema3.String.annotations({
130
- title: "Type"
131
- })),
132
- props: Schema3.optional(Schema3.Record({
133
- key: Schema3.String,
134
- value: Schema3.Any
135
- }))
136
- }).annotations({
137
- title: "Query"
138
- });
139
- var SubscriptionTriggerSchema = Schema3.Struct({
140
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
141
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
142
- filter: QuerySchema,
143
- options: Schema3.optional(Schema3.Struct({
144
- // Watch changes to object (not just creation).
145
- deep: Schema3.optional(Schema3.Boolean.annotations({
146
- title: "Nested"
147
- })),
148
- // Debounce changes (delay in ms).
149
- delay: Schema3.optional(Schema3.Number.annotations({
150
- title: "Delay"
151
- }))
152
- }).annotations({
153
- title: "Options"
154
- }))
155
- }).pipe(Schema3.mutable);
156
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
211
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
157
212
  title: "Trigger"
158
213
  });
159
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
160
- from: Schema3.String,
161
- to: Schema3.String,
162
- subject: Schema3.String,
163
- created: Schema3.String,
164
- body: Schema3.String
165
- }));
166
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
167
- url: Schema3.String,
168
- method: Schema3.Literal("GET", "POST"),
169
- headers: Schema3.Record({
170
- key: Schema3.String,
171
- value: Schema3.String
172
- }),
173
- bodyText: Schema3.String
174
- }));
175
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
176
- queue: DXN.Schema,
177
- item: Schema3.Any,
178
- cursor: Schema3.String
179
- }));
180
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
181
- type: Schema3.String,
182
- changedObjectId: Schema3.String
183
- }));
184
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
185
- tick: Schema3.Number
186
- }));
187
- var FunctionTriggerSchema = Schema3.Struct({
214
+ var Trigger_ = Schema3.Struct({
188
215
  /**
189
216
  * Function or workflow to invoke.
190
217
  */
191
218
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
192
- function: Schema3.optional(Ref2(Expando).annotations({
219
+ function: Schema3.optional(Type3.Ref(Type3.Expando).annotations({
193
220
  title: "Function"
194
221
  })),
195
222
  /**
@@ -203,7 +230,7 @@ var FunctionTriggerSchema = Schema3.Struct({
203
230
  enabled: Schema3.optional(Schema3.Boolean.annotations({
204
231
  title: "Enabled"
205
232
  })),
206
- spec: Schema3.optional(TriggerSchema),
233
+ spec: Schema3.optional(Spec),
207
234
  /**
208
235
  * Passed as the input data to the function.
209
236
  * Must match the function's input schema.
@@ -219,237 +246,752 @@ var FunctionTriggerSchema = Schema3.Struct({
219
246
  key: Schema3.String,
220
247
  value: Schema3.Any
221
248
  })))
222
- });
223
- var FunctionTrigger = class extends TypedObject({
224
- typename: "dxos.org/type/FunctionTrigger",
225
- version: "0.2.0"
226
- })(FunctionTriggerSchema.fields) {
227
- };
228
- var FunctionManifestSchema = Schema3.Struct({
229
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
230
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
231
- });
232
- var FUNCTION_TYPES = [
233
- FunctionType,
234
- FunctionTrigger
235
- ];
249
+ }).pipe(Type3.Obj({
250
+ typename: "dxos.org/type/Trigger",
251
+ version: "0.1.0"
252
+ }), SystemTypeAnnotation2.set(true));
253
+ var Trigger = Trigger_;
254
+ var make3 = (props) => Obj3.make(Trigger, props);
236
255
 
237
- // src/trace.ts
238
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
239
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
240
- InvocationOutcome2["SUCCESS"] = "success";
241
- InvocationOutcome2["FAILURE"] = "failure";
242
- InvocationOutcome2["PENDING"] = "pending";
243
- return InvocationOutcome2;
244
- }({});
245
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
246
- InvocationTraceEventType2["START"] = "start";
247
- InvocationTraceEventType2["END"] = "end";
248
- return InvocationTraceEventType2;
249
- }({});
250
- var TraceEventException = Schema4.Struct({
251
- timestampMs: Schema4.Number,
252
- message: Schema4.String,
253
- name: Schema4.String,
254
- stack: Schema4.optional(Schema4.String)
256
+ // src/types/TriggerEvent.ts
257
+ var TriggerEvent_exports = {};
258
+ __export(TriggerEvent_exports, {
259
+ EmailEvent: () => EmailEvent,
260
+ QueueEvent: () => QueueEvent,
261
+ SubscriptionEvent: () => SubscriptionEvent,
262
+ TimerEvent: () => TimerEvent,
263
+ WebhookEvent: () => WebhookEvent
255
264
  });
256
- var InvocationTraceStartEvent = Schema4.Struct({
257
- /**
258
- * Queue message id.
259
- */
260
- id: ObjectId,
261
- type: Schema4.Literal("start"),
262
- /**
263
- * Invocation id, the same for invocation start and end events.
264
- */
265
- invocationId: ObjectId,
266
- /**
267
- * Event generation time.
268
- */
269
- timestampMs: Schema4.Number,
270
- /**
271
- * Data passed to function / workflow as an argument.
272
- */
273
- // TODO(burdon): Input schema?
274
- input: Schema4.Object,
275
- /**
276
- * Queue for function/workflow invocation events.
277
- */
278
- invocationTraceQueue: Type2.Ref(Queue),
279
- /**
280
- * DXN of the invoked function/workflow.
281
- */
282
- invocationTarget: Type2.Ref(Type2.Expando),
283
- /**
284
- * Present for automatic invocations.
285
- */
286
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
287
- }).pipe(Type2.Obj({
288
- typename: "dxos.org/type/InvocationTraceStart",
289
- version: "0.1.0"
265
+ import * as Schema4 from "effect/Schema";
266
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
267
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
268
+ from: Schema4.String,
269
+ to: Schema4.String,
270
+ subject: Schema4.String,
271
+ created: Schema4.String,
272
+ body: Schema4.String
273
+ }));
274
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
275
+ queue: DXN2.Schema,
276
+ item: Schema4.Any,
277
+ cursor: Schema4.String
290
278
  }));
291
- var InvocationTraceEndEvent = Schema4.Struct({
279
+ var SubscriptionEvent = Schema4.Struct({
292
280
  /**
293
- * Trace event id.
281
+ * Type of the mutation.
294
282
  */
295
- id: ObjectId,
296
- type: Schema4.Literal("end"),
283
+ // TODO(dmaretskyi): Specify enum.
284
+ type: Schema4.String,
297
285
  /**
298
- * Invocation id, will be the same for invocation start and end.
286
+ * Reference to the object that was changed or created.
299
287
  */
300
- invocationId: ObjectId,
288
+ subject: Type4.Ref(Obj4.Any),
301
289
  /**
302
- * Event generation time.
290
+ * @deprecated
303
291
  */
304
- // TODO(burdon): Remove ms suffix.
305
- timestampMs: Schema4.Number,
306
- outcome: Schema4.Enums(InvocationOutcome),
307
- exception: Schema4.optional(TraceEventException)
308
- }).pipe(Type2.Obj({
309
- typename: "dxos.org/type/InvocationTraceEnd",
310
- version: "0.1.0"
292
+ changedObjectId: Schema4.optional(Schema4.String)
293
+ }).pipe(Schema4.mutable);
294
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
295
+ tick: Schema4.Number
311
296
  }));
312
- var TraceEventLog = Schema4.Struct({
313
- timestampMs: Schema4.Number,
314
- level: Schema4.String,
315
- message: Schema4.String,
316
- context: Schema4.optional(Schema4.Object)
317
- });
318
- var TraceEvent = Schema4.Struct({
319
- id: ObjectId,
320
- // TODO(burdon): Need enum/numeric result (not string).
321
- outcome: Schema4.String,
322
- truncated: Schema4.Boolean,
323
- /**
324
- * Time when the event was persisted.
325
- */
326
- ingestionTimestampMs: Schema4.Number,
327
- logs: Schema4.Array(TraceEventLog),
328
- exceptions: Schema4.Array(TraceEventException)
329
- }).pipe(Type2.Obj({
330
- typename: "dxos.org/type/TraceEvent",
331
- version: "0.1.0"
297
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
298
+ url: Schema4.String,
299
+ method: Schema4.Literal("GET", "POST"),
300
+ headers: Schema4.Record({
301
+ key: Schema4.String,
302
+ value: Schema4.String
303
+ }),
304
+ bodyText: Schema4.String
332
305
  }));
333
- var createInvocationSpans = (items) => {
334
- if (!items) {
335
- return [];
336
- }
337
- const eventsByInvocationId = /* @__PURE__ */ new Map();
338
- for (const event of items) {
339
- if (!("invocationId" in event)) {
340
- continue;
341
- }
342
- const invocationId = event.invocationId;
343
- const entry = eventsByInvocationId.get(invocationId) || {
344
- start: void 0,
345
- end: void 0
346
- };
347
- if (event.type === "start") {
348
- entry.start = event;
349
- } else if (event.type === "end") {
350
- entry.end = event;
351
- }
352
- eventsByInvocationId.set(invocationId, entry);
353
- }
354
- const now = Date.now();
355
- const result = [];
356
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
357
- if (!start) {
358
- log.warn("found end event without matching start", {
359
- invocationId
360
- }, {
361
- F: __dxlog_file,
362
- L: 160,
363
- S: void 0,
364
- C: (f, a) => f(...a)
365
- });
366
- continue;
367
- }
368
- const isInProgress = end === void 0;
369
- result.push({
370
- id: invocationId,
371
- timestampMs: start.timestampMs,
372
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
373
- outcome: end?.outcome ?? "pending",
374
- exception: end?.exception,
375
- input: start.input,
376
- invocationTraceQueue: start.invocationTraceQueue,
377
- invocationTarget: start.invocationTarget,
378
- trigger: start.trigger
379
- });
380
- }
381
- return result;
382
- };
383
306
 
384
- // src/url.ts
307
+ // src/types/url.ts
385
308
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
386
309
  var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
387
- var isSecure = (protocol) => {
388
- return protocol === "https:" || protocol === "wss:";
389
- };
390
- var getUserFunctionUrlInMetadata = (meta) => {
310
+ var getUserFunctionIdInMetadata = (meta) => {
391
311
  return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
392
312
  };
393
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
313
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
394
314
  const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
395
315
  if (key) {
396
- if (key.id !== functionUrl) {
316
+ if (key.id !== functionId) {
397
317
  throw new Error("Metadata mismatch");
398
318
  }
399
319
  } else {
400
320
  meta.keys.push({
401
321
  source: FUNCTIONS_META_KEY,
402
- id: functionUrl
322
+ id: functionId
403
323
  });
404
324
  }
405
325
  };
406
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
407
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
408
- const baseUrl = new URL("functions/", edgeUrl);
409
- const relativeUrl = functionUrl.replace(/^\//, "");
410
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
411
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
412
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
413
- url.protocol = isSecure(url.protocol) ? "https" : "http";
414
- return url.toString();
326
+
327
+ // src/sdk.ts
328
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
329
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, types, services }) => {
330
+ if (!Schema5.isSchema(inputSchema)) {
331
+ throw new Error("Input schema must be a valid schema");
332
+ }
333
+ if (typeof handler !== "function") {
334
+ throw new Error("Handler must be a function");
335
+ }
336
+ const limit = Error.stackTraceLimit;
337
+ Error.stackTraceLimit = 2;
338
+ const traceError = new Error();
339
+ Error.stackTraceLimit = limit;
340
+ let cache = false;
341
+ const captureStackTrace = () => {
342
+ if (cache !== false) {
343
+ return cache;
344
+ }
345
+ if (traceError.stack !== void 0) {
346
+ const stack = traceError.stack.split("\n");
347
+ if (stack[2] !== void 0) {
348
+ cache = stack[2].trim();
349
+ return cache;
350
+ }
351
+ }
352
+ };
353
+ const handlerWithSpan = (...args) => {
354
+ const result = handler(...args);
355
+ if (Effect.isEffect(result)) {
356
+ return Effect.withSpan(result, `${key ?? name}`, {
357
+ captureStackTrace
358
+ });
359
+ }
360
+ return result;
361
+ };
362
+ return {
363
+ [typeId]: true,
364
+ key,
365
+ name,
366
+ description,
367
+ inputSchema,
368
+ outputSchema,
369
+ handler: handlerWithSpan,
370
+ types: types ?? [],
371
+ services: !services ? [] : getServiceKeys(services)
372
+ };
373
+ };
374
+ var getServiceKeys = (services) => {
375
+ return services.map((tag) => {
376
+ if (typeof tag.key === "string") {
377
+ return tag.key;
378
+ }
379
+ console.log(tag);
380
+ failedInvariant();
381
+ });
382
+ };
383
+ var FunctionDefinition = {
384
+ make: defineFunction,
385
+ isFunction: (value2) => {
386
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
387
+ },
388
+ serialize: (functionDef) => {
389
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
390
+ return serializeFunction(functionDef);
391
+ },
392
+ deserialize: (functionObj) => {
393
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
394
+ return deserializeFunction(functionObj);
395
+ }
396
+ };
397
+ var serializeFunction = (functionDef) => {
398
+ const fn4 = Function_exports.make({
399
+ key: functionDef.key,
400
+ name: functionDef.name,
401
+ version: "0.1.0",
402
+ description: functionDef.description,
403
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
404
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema),
405
+ services: functionDef.services
406
+ });
407
+ if (functionDef.meta?.deployedFunctionId) {
408
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
409
+ }
410
+ return fn4;
411
+ };
412
+ var deserializeFunction = (functionObj) => {
413
+ return {
414
+ [typeId]: true,
415
+ // TODO(dmaretskyi): Fix key.
416
+ key: functionObj.key ?? functionObj.name,
417
+ name: functionObj.name,
418
+ description: functionObj.description,
419
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
420
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
421
+ // TODO(dmaretskyi): This should throw error.
422
+ handler: () => {
423
+ },
424
+ services: functionObj.services ?? [],
425
+ types: [],
426
+ meta: {
427
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
428
+ }
429
+ };
430
+ };
431
+
432
+ // src/example/fib.ts
433
+ var fib_default = defineFunction({
434
+ key: "example.org/function/fib",
435
+ name: "Fibonacci",
436
+ description: "Function that calculates a Fibonacci number",
437
+ inputSchema: Schema6.Struct({
438
+ iterations: Schema6.optional(Schema6.Number).annotations({
439
+ description: "Number of iterations",
440
+ default: 1e5
441
+ })
442
+ }),
443
+ outputSchema: Schema6.Struct({
444
+ result: Schema6.String
445
+ }),
446
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
447
+ let a = 0n;
448
+ let b = 1n;
449
+ for (let i = 0; i < iterations; i++) {
450
+ a += b;
451
+ b = a - b;
452
+ }
453
+ return {
454
+ result: a.toString()
455
+ };
456
+ })
457
+ });
458
+
459
+ // src/example/reply.ts
460
+ import * as Console from "effect/Console";
461
+ import * as Effect3 from "effect/Effect";
462
+ import * as Schema7 from "effect/Schema";
463
+ var reply_default = defineFunction({
464
+ key: "example.org/function/reply",
465
+ name: "Reply",
466
+ description: "Function that echoes the input",
467
+ inputSchema: Schema7.Any,
468
+ outputSchema: Schema7.Any,
469
+ handler: Effect3.fn(function* ({ data }) {
470
+ yield* Console.log("reply", {
471
+ data
472
+ });
473
+ return data;
474
+ })
475
+ });
476
+
477
+ // src/example/sleep.ts
478
+ import * as Effect4 from "effect/Effect";
479
+ import * as Schema8 from "effect/Schema";
480
+ var sleep_default = defineFunction({
481
+ key: "example.org/function/sleep",
482
+ name: "Sleep",
483
+ description: "Function that sleeps for a given amount of time",
484
+ inputSchema: Schema8.Struct({
485
+ duration: Schema8.optional(Schema8.Number).annotations({
486
+ description: "Milliseconds to sleep",
487
+ default: 1e5
488
+ })
489
+ }),
490
+ outputSchema: Schema8.Void,
491
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
492
+ yield* Effect4.sleep(duration);
493
+ })
494
+ });
495
+
496
+ // src/example/index.ts
497
+ (function(Example2) {
498
+ Example2.fib = fib_default;
499
+ Example2.reply = reply_default;
500
+ Example2.sleep = sleep_default;
501
+ })(Example || (Example = {}));
502
+ var Example;
503
+
504
+ // src/services/index.ts
505
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
506
+
507
+ // src/services/credentials.ts
508
+ import * as HttpClient from "@effect/platform/HttpClient";
509
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
510
+ import * as Context from "effect/Context";
511
+ import * as Effect5 from "effect/Effect";
512
+ import * as Layer from "effect/Layer";
513
+ import * as Redacted from "effect/Redacted";
514
+ import { Query } from "@dxos/echo";
515
+ import { DatabaseService } from "@dxos/echo-db";
516
+ import { AccessToken } from "@dxos/types";
517
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
518
+ static getCredential = (query) => Effect5.gen(function* () {
519
+ const credentials = yield* _CredentialsService;
520
+ return yield* Effect5.promise(() => credentials.getCredential(query));
521
+ });
522
+ static getApiKey = (query) => Effect5.gen(function* () {
523
+ const credential = yield* _CredentialsService.getCredential(query);
524
+ if (!credential.apiKey) {
525
+ throw new Error(`API key not found for service: ${query.service}`);
526
+ }
527
+ return Redacted.make(credential.apiKey);
528
+ });
529
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
530
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
531
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
532
+ return {
533
+ service,
534
+ apiKey: Redacted.value(yield* apiKey)
535
+ };
536
+ }));
537
+ return new ConfiguredCredentialsService(serviceCredentials);
538
+ }));
539
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
540
+ const dbService = yield* DatabaseService;
541
+ const queryCredentials = async (query) => {
542
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
543
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
544
+ service: accessToken.source,
545
+ apiKey: accessToken.token
546
+ }));
547
+ };
548
+ return {
549
+ getCredential: async (query) => {
550
+ const credentials = await queryCredentials(query);
551
+ if (credentials.length === 0) {
552
+ throw new Error(`Credential not found for service: ${query.service}`);
553
+ }
554
+ return credentials[0];
555
+ },
556
+ queryCredentials: async (query) => {
557
+ return queryCredentials(query);
558
+ }
559
+ };
560
+ }));
561
+ };
562
+ var ConfiguredCredentialsService = class {
563
+ credentials;
564
+ constructor(credentials = []) {
565
+ this.credentials = credentials;
566
+ }
567
+ addCredentials(credentials) {
568
+ this.credentials.push(...credentials);
569
+ return this;
570
+ }
571
+ async queryCredentials(query) {
572
+ return this.credentials.filter((credential) => credential.service === query.service);
573
+ }
574
+ async getCredential(query) {
575
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
576
+ if (!credential) {
577
+ throw new Error(`Credential not found for service: ${query.service}`);
578
+ }
579
+ return credential;
580
+ }
581
+ };
582
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
583
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
584
+ const authorization = kind ? `${kind} ${key}` : key;
585
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
586
+ }));
587
+
588
+ // src/services/event-logger.ts
589
+ import * as Context3 from "effect/Context";
590
+ import * as Effect7 from "effect/Effect";
591
+ import * as Layer3 from "effect/Layer";
592
+ import * as Schema9 from "effect/Schema";
593
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
594
+ import { invariant } from "@dxos/invariant";
595
+ import { LogLevel, log as log2 } from "@dxos/log";
596
+
597
+ // src/services/tracing.ts
598
+ import * as Context2 from "effect/Context";
599
+ import * as Effect6 from "effect/Effect";
600
+ import * as Layer2 from "effect/Layer";
601
+ import { AgentStatus } from "@dxos/ai";
602
+ import { Obj as Obj6 } from "@dxos/echo";
603
+ import { Message } from "@dxos/types";
604
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
605
+ static noop = {
606
+ getTraceContext: () => ({}),
607
+ write: () => {
608
+ }
609
+ };
610
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
611
+ /**
612
+ * Creates a TracingService layer that emits events to the parent tracing service.
613
+ */
614
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
615
+ const tracing = yield* _TracingService;
616
+ const context = mapContext(tracing.getTraceContext());
617
+ return {
618
+ write: (event) => tracing.write(event),
619
+ getTraceContext: () => context
620
+ };
621
+ }));
622
+ /**
623
+ * Emit the current human-readable execution status.
624
+ */
625
+ static emitStatus = Effect6.fnUntraced(function* (data) {
626
+ const tracing = yield* _TracingService;
627
+ tracing.write(Obj6.make(AgentStatus, {
628
+ parentMessage: tracing.getTraceContext().parentMessage,
629
+ toolCallId: tracing.getTraceContext().toolCallId,
630
+ created: (/* @__PURE__ */ new Date()).toISOString(),
631
+ ...data
632
+ }));
633
+ });
634
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
635
+ const tracing = yield* _TracingService;
636
+ tracing.write(Obj6.make(Message.Message, {
637
+ parentMessage: tracing.getTraceContext().parentMessage,
638
+ ...data,
639
+ properties: {
640
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
641
+ ...data.properties
642
+ }
643
+ }));
644
+ });
415
645
  };
646
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
416
647
 
417
- // src/executor/executor.ts
418
- import { Effect, Schema as Schema5 } from "effect";
419
- import { runAndForwardErrors } from "@dxos/effect";
420
- var FunctionExecutor = class {
421
- constructor(_services) {
422
- this._services = _services;
648
+ // src/services/event-logger.ts
649
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
650
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
651
+ type: Schema9.Literal("begin-compute"),
652
+ nodeId: Schema9.String,
653
+ /**
654
+ * Names of the inputs begin computed.
655
+ */
656
+ inputs: Schema9.Array(Schema9.String)
657
+ }), Schema9.Struct({
658
+ type: Schema9.Literal("end-compute"),
659
+ nodeId: Schema9.String,
660
+ /**
661
+ * Names of the outputs computed.
662
+ */
663
+ outputs: Schema9.Array(Schema9.String)
664
+ }), Schema9.Struct({
665
+ type: Schema9.Literal("compute-input"),
666
+ nodeId: Schema9.String,
667
+ property: Schema9.String,
668
+ value: Schema9.Any
669
+ }), Schema9.Struct({
670
+ type: Schema9.Literal("compute-output"),
671
+ nodeId: Schema9.String,
672
+ property: Schema9.String,
673
+ value: Schema9.Any
674
+ }), Schema9.Struct({
675
+ type: Schema9.Literal("custom"),
676
+ nodeId: Schema9.String,
677
+ event: Schema9.Any
678
+ }));
679
+ var ComputeEvent = Schema9.Struct({
680
+ payload: ComputeEventPayload
681
+ }).pipe(Type6.Obj({
682
+ typename: "dxos.org/type/ComputeEvent",
683
+ version: "0.1.0"
684
+ }));
685
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
686
+ static noop = {
687
+ log: () => {
688
+ },
689
+ nodeId: void 0
690
+ };
691
+ /**
692
+ * Implements ComputeEventLogger using TracingService.
693
+ */
694
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
695
+ const tracing = yield* TracingService;
696
+ return {
697
+ log: (event) => {
698
+ tracing.write(Obj7.make(ComputeEvent, {
699
+ payload: event
700
+ }));
701
+ },
702
+ nodeId: void 0
703
+ };
704
+ }));
705
+ };
706
+ var logCustomEvent = (data) => Effect7.gen(function* () {
707
+ const logger = yield* ComputeEventLogger;
708
+ if (!logger.nodeId) {
709
+ throw new Error("logCustomEvent must be called within a node compute function");
423
710
  }
424
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
425
- async invoke(fnDef, input) {
426
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
427
- assertInput(input);
428
- const context = {
429
- getService: this._services.getService.bind(this._services),
430
- getSpace: async (_spaceId) => {
431
- throw new Error("Not available. Use the database service instead.");
711
+ logger.log({
712
+ type: "custom",
713
+ nodeId: logger.nodeId,
714
+ event: data
715
+ });
716
+ });
717
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
718
+ log2.error("unhandled effect error", {
719
+ error
720
+ }, {
721
+ F: __dxlog_file,
722
+ L: 102,
723
+ S: this,
724
+ C: (f, a) => f(...a)
725
+ });
726
+ throw error;
727
+ }));
728
+ var createEventLogger = (level, message = "event") => {
729
+ const logFunction = {
730
+ [LogLevel.WARN]: log2.warn,
731
+ [LogLevel.VERBOSE]: log2.verbose,
732
+ [LogLevel.DEBUG]: log2.debug,
733
+ [LogLevel.INFO]: log2.info,
734
+ [LogLevel.ERROR]: log2.error
735
+ }[level];
736
+ invariant(logFunction, void 0, {
737
+ F: __dxlog_file,
738
+ L: 120,
739
+ S: void 0,
740
+ A: [
741
+ "logFunction",
742
+ ""
743
+ ]
744
+ });
745
+ return {
746
+ log: (event) => {
747
+ logFunction(message, event);
748
+ },
749
+ nodeId: void 0
750
+ };
751
+ };
752
+
753
+ // src/services/function-invocation-service.ts
754
+ import * as Context4 from "effect/Context";
755
+ import * as Effect8 from "effect/Effect";
756
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
757
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
758
+ };
759
+
760
+ // src/services/queues.ts
761
+ import * as Context5 from "effect/Context";
762
+ import * as Effect9 from "effect/Effect";
763
+ import * as Layer4 from "effect/Layer";
764
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
765
+ static notAvailable = Layer4.succeed(_QueueService, {
766
+ queues: {
767
+ get(_dxn) {
768
+ throw new Error("Queues not available");
432
769
  },
433
- space: void 0,
434
- get ai() {
435
- throw new Error("Not available. Use the ai service instead.");
770
+ create() {
771
+ throw new Error("Queues not available");
436
772
  }
773
+ },
774
+ queue: void 0
775
+ });
776
+ static make = (queues, queue) => {
777
+ return {
778
+ queues,
779
+ queue
437
780
  };
438
- const result = fnDef.handler({
439
- context,
440
- data: input
781
+ };
782
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
783
+ /**
784
+ * Gets a queue by its DXN.
785
+ */
786
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
787
+ /**
788
+ * Creates a new queue.
789
+ */
790
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
791
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
792
+ };
793
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
794
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
795
+ queue
796
+ });
797
+ };
798
+
799
+ // src/protocol/protocol.ts
800
+ import * as Effect10 from "effect/Effect";
801
+ import * as Layer5 from "effect/Layer";
802
+ import * as Schema10 from "effect/Schema";
803
+ import * as SchemaAST2 from "effect/SchemaAST";
804
+ import { AiService } from "@dxos/ai";
805
+ import { LifecycleState, Resource } from "@dxos/context";
806
+ import { Type as Type7 } from "@dxos/echo";
807
+ import { EchoClient } from "@dxos/echo-db";
808
+ import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
809
+ import { PublicKey } from "@dxos/keys";
810
+ function _ts_add_disposable_resource(env, value2, async) {
811
+ if (value2 !== null && value2 !== void 0) {
812
+ if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
813
+ var dispose, inner;
814
+ if (async) {
815
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
816
+ dispose = value2[Symbol.asyncDispose];
817
+ }
818
+ if (dispose === void 0) {
819
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
820
+ dispose = value2[Symbol.dispose];
821
+ if (async) inner = dispose;
822
+ }
823
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
824
+ if (inner) dispose = function() {
825
+ try {
826
+ inner.call(this);
827
+ } catch (e) {
828
+ return Promise.reject(e);
829
+ }
830
+ };
831
+ env.stack.push({
832
+ value: value2,
833
+ dispose,
834
+ async
441
835
  });
442
- let data;
443
- if (Effect.isEffect(result)) {
444
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
445
- } else {
446
- data = await result;
836
+ } else if (async) {
837
+ env.stack.push({
838
+ async: true
839
+ });
840
+ }
841
+ return value2;
842
+ }
843
+ function _ts_dispose_resources(env) {
844
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
845
+ var e = new Error(message);
846
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
847
+ };
848
+ return (_ts_dispose_resources = function _ts_dispose_resources2(env2) {
849
+ function fail(e) {
850
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
851
+ env2.hasError = true;
852
+ }
853
+ var r, s = 0;
854
+ function next() {
855
+ while (r = env2.stack.pop()) {
856
+ try {
857
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
858
+ if (r.dispose) {
859
+ var result = r.dispose.call(r.value);
860
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
861
+ fail(e);
862
+ return next();
863
+ });
864
+ } else s |= 1;
865
+ } catch (e) {
866
+ fail(e);
867
+ }
868
+ }
869
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
870
+ if (env2.hasError) throw env2.error;
871
+ }
872
+ return next();
873
+ })(env);
874
+ }
875
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
876
+ var wrapFunctionHandler = (func) => {
877
+ if (!FunctionDefinition.isFunction(func)) {
878
+ throw new TypeError("Invalid function definition");
879
+ }
880
+ return {
881
+ meta: {
882
+ key: func.key,
883
+ name: func.name,
884
+ description: func.description,
885
+ inputSchema: Type7.toJsonSchema(func.inputSchema),
886
+ outputSchema: func.outputSchema === void 0 ? void 0 : Type7.toJsonSchema(func.outputSchema),
887
+ services: func.services
888
+ },
889
+ handler: async ({ data, context }) => {
890
+ if ((func.services.includes(DatabaseService2.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
891
+ throw new FunctionError({
892
+ message: "Services not provided: dataService, queryService"
893
+ });
894
+ }
895
+ try {
896
+ const env = {
897
+ stack: [],
898
+ error: void 0,
899
+ hasError: false
900
+ };
901
+ try {
902
+ if (!SchemaAST2.isAnyKeyword(func.inputSchema.ast)) {
903
+ try {
904
+ Schema10.validateSync(func.inputSchema)(data);
905
+ } catch (error) {
906
+ throw new FunctionError({
907
+ message: "Invalid input schema",
908
+ cause: error
909
+ });
910
+ }
911
+ }
912
+ const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
913
+ if (func.types.length > 0) {
914
+ invariant2(funcContext.db, "Database is required for functions with types", {
915
+ F: __dxlog_file2,
916
+ L: 63,
917
+ S: void 0,
918
+ A: [
919
+ "funcContext.db",
920
+ "'Database is required for functions with types'"
921
+ ]
922
+ });
923
+ funcContext.db.graph.schemaRegistry.addSchema(func.types);
924
+ }
925
+ let result = await func.handler({
926
+ // TODO(dmaretskyi): Fix the types.
927
+ context,
928
+ data
929
+ });
930
+ if (Effect10.isEffect(result)) {
931
+ result = await Effect10.runPromise(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
932
+ }
933
+ if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
934
+ Schema10.validateSync(func.outputSchema)(result);
935
+ }
936
+ return result;
937
+ } catch (e) {
938
+ env.error = e;
939
+ env.hasError = true;
940
+ } finally {
941
+ const result = _ts_dispose_resources(env);
942
+ if (result) await result;
943
+ }
944
+ } catch (error) {
945
+ throw error;
946
+ }
947
+ }
948
+ };
949
+ };
950
+ var FunctionContext = class extends Resource {
951
+ context;
952
+ client;
953
+ db;
954
+ queues;
955
+ constructor(context) {
956
+ super();
957
+ this.context = context;
958
+ if (context.services.dataService && context.services.queryService) {
959
+ this.client = new EchoClient().connectToService({
960
+ dataService: context.services.dataService,
961
+ queryService: context.services.queryService,
962
+ queueService: context.services.queueService
963
+ });
447
964
  }
448
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
449
- assertOutput(data);
450
- return data;
965
+ }
966
+ async _open() {
967
+ await this.client?.open();
968
+ this.db = this.client && this.context.spaceId ? this.client.constructDatabase({
969
+ spaceId: this.context.spaceId ?? failedInvariant2(),
970
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
971
+ reactiveSchemaQuery: false
972
+ }) : void 0;
973
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context"));
974
+ await this.db?.open();
975
+ this.queues = this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : void 0;
976
+ }
977
+ async _close() {
978
+ await this.db?.close();
979
+ await this.client?.close();
980
+ }
981
+ createLayer() {
982
+ assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
983
+ const dbLayer = this.db ? DatabaseService2.layer(this.db) : DatabaseService2.notAvailable;
984
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
985
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
986
+ const functionInvocationService = MockedFunctionInvocationService;
987
+ const aiService = AiService.notAvailable;
988
+ const tracing = TracingService.layerNoop;
989
+ return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
451
990
  }
452
991
  };
992
+ var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
993
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
994
+ });
453
995
  export {
454
996
  ComputeEvent,
455
997
  ComputeEventLogger,
@@ -457,45 +999,32 @@ export {
457
999
  ConfiguredCredentialsService,
458
1000
  ContextQueueService,
459
1001
  CredentialsService,
460
- DatabaseService,
461
- EmailTriggerOutput,
1002
+ DatabaseService2 as DatabaseService,
1003
+ Example,
1004
+ FUNCTIONS_META_KEY,
462
1005
  FUNCTIONS_PRESET_META_KEY,
463
- FUNCTION_TYPES,
1006
+ Function_exports as Function,
1007
+ FunctionDefinition,
464
1008
  FunctionError,
465
- FunctionExecutor,
466
- FunctionManifestSchema,
467
- FunctionTrigger,
468
- FunctionTriggerSchema,
469
- FunctionType,
470
- InvocationOutcome,
471
- InvocationTraceEndEvent,
472
- InvocationTraceEventType,
473
- InvocationTraceStartEvent,
474
- LocalFunctionExecutionService,
1009
+ FunctionInvocationService,
1010
+ FunctionNotFoundError,
1011
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
475
1012
  QueueService,
476
- QueueTriggerOutput,
477
- RemoteFunctionExecutionService,
478
- SERVICE_TAGS,
479
- ScriptType,
480
- ServiceContainer,
1013
+ Script_exports as Script,
481
1014
  ServiceNotAvailableError,
482
- SubscriptionTriggerOutput,
483
- TimerTriggerOutput,
484
- TraceEvent,
485
- TraceEventException,
486
- TraceEventLog,
487
1015
  TracingService,
488
- TriggerKind,
489
- TriggerSchema,
490
- WebhookTriggerOutput,
1016
+ Trigger_exports as Trigger,
1017
+ TriggerEvent_exports as TriggerEvent,
1018
+ TriggerStateNotFoundError,
491
1019
  createDefectLogger,
492
1020
  createEventLogger,
493
- createInvocationSpans,
494
1021
  defineFunction,
495
- getInvocationUrl,
496
- getUserFunctionUrlInMetadata,
1022
+ deserializeFunction,
1023
+ getUserFunctionIdInMetadata,
497
1024
  logCustomEvent,
498
- makeFunctionUrl,
499
- setUserFunctionUrlInMetadata
1025
+ serializeFunction,
1026
+ setUserFunctionIdInMetadata,
1027
+ withAuthorization,
1028
+ wrapFunctionHandler
500
1029
  };
501
1030
  //# sourceMappingURL=index.mjs.map