@dxos/functions 0.8.4-main.5ad4a44 → 0.8.4-main.66e292d

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 (191) hide show
  1. package/dist/lib/browser/index.mjs +830 -1195
  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 +830 -1195
  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 +28 -36
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/{examples → example}/fib.d.ts +1 -1
  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/{examples → example}/reply.d.ts +1 -1
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/{examples → example}/sleep.d.ts +1 -1
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +4 -8
  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 +1 -1
  30. package/dist/types/src/services/credentials.d.ts.map +1 -1
  31. package/dist/types/src/services/event-logger.d.ts +16 -4
  32. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  33. package/dist/types/src/services/function-invocation-service.d.ts +3 -20
  34. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  35. package/dist/types/src/services/index.d.ts +3 -4
  36. package/dist/types/src/services/index.d.ts.map +1 -1
  37. package/dist/types/src/services/queues.d.ts +4 -4
  38. package/dist/types/src/services/queues.d.ts.map +1 -1
  39. package/dist/types/src/services/tracing.d.ts +5 -10
  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/{url.d.ts → types/url.d.ts} +0 -9
  52. package/dist/types/src/types/url.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +15 -59
  55. package/src/{examples → example}/fib.ts +1 -1
  56. package/src/example/forex-effect.ts +40 -0
  57. package/src/example/index.ts +13 -0
  58. package/src/{examples → example}/reply.ts +1 -1
  59. package/src/{examples → example}/sleep.ts +1 -1
  60. package/src/index.ts +4 -8
  61. package/src/{executor → protocol}/index.ts +1 -1
  62. package/src/protocol/protocol.test.ts +59 -0
  63. package/src/protocol/protocol.ts +156 -0
  64. package/src/{handler.ts → sdk.ts} +96 -81
  65. package/src/services/credentials.ts +3 -4
  66. package/src/services/event-logger.ts +8 -2
  67. package/src/services/function-invocation-service.ts +10 -71
  68. package/src/services/index.ts +4 -4
  69. package/src/services/queues.ts +5 -7
  70. package/src/services/tracing.ts +8 -43
  71. package/src/types/Function.ts +80 -0
  72. package/src/types/Script.ts +33 -0
  73. package/src/types/Trigger.ts +140 -0
  74. package/src/types/TriggerEvent.ts +62 -0
  75. package/src/types/index.ts +9 -0
  76. package/src/{url.ts → types/url.ts} +0 -24
  77. package/dist/lib/browser/bundler/index.mjs +0 -269
  78. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  79. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  80. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  81. package/dist/lib/browser/chunk-LKYT2SAL.mjs +0 -665
  82. package/dist/lib/browser/chunk-LKYT2SAL.mjs.map +0 -7
  83. package/dist/lib/browser/edge/index.mjs +0 -83
  84. package/dist/lib/browser/edge/index.mjs.map +0 -7
  85. package/dist/lib/browser/testing/index.mjs +0 -131
  86. package/dist/lib/browser/testing/index.mjs.map +0 -7
  87. package/dist/lib/node-esm/bundler/index.mjs +0 -270
  88. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  89. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  90. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  91. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs +0 -667
  92. package/dist/lib/node-esm/chunk-NAQIKLZB.mjs.map +0 -7
  93. package/dist/lib/node-esm/edge/index.mjs +0 -84
  94. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  95. package/dist/lib/node-esm/testing/index.mjs +0 -132
  96. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  97. package/dist/types/src/bundler/bundler.d.ts +0 -49
  98. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  99. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  100. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  101. package/dist/types/src/bundler/index.d.ts +0 -2
  102. package/dist/types/src/bundler/index.d.ts.map +0 -1
  103. package/dist/types/src/edge/functions.d.ts +0 -17
  104. package/dist/types/src/edge/functions.d.ts.map +0 -1
  105. package/dist/types/src/edge/index.d.ts +0 -2
  106. package/dist/types/src/edge/index.d.ts.map +0 -1
  107. package/dist/types/src/examples/fib.d.ts.map +0 -1
  108. package/dist/types/src/examples/index.d.ts +0 -4
  109. package/dist/types/src/examples/index.d.ts.map +0 -1
  110. package/dist/types/src/examples/reply.d.ts.map +0 -1
  111. package/dist/types/src/examples/sleep.d.ts.map +0 -1
  112. package/dist/types/src/executor/executor.d.ts +0 -14
  113. package/dist/types/src/executor/executor.d.ts.map +0 -1
  114. package/dist/types/src/executor/index.d.ts +0 -2
  115. package/dist/types/src/executor/index.d.ts.map +0 -1
  116. package/dist/types/src/handler.d.ts +0 -109
  117. package/dist/types/src/handler.d.ts.map +0 -1
  118. package/dist/types/src/schema.d.ts +0 -43
  119. package/dist/types/src/schema.d.ts.map +0 -1
  120. package/dist/types/src/services/database.d.ts +0 -67
  121. package/dist/types/src/services/database.d.ts.map +0 -1
  122. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  123. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  124. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  125. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  126. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  127. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  128. package/dist/types/src/services/service-container.d.ts +0 -57
  129. package/dist/types/src/services/service-container.d.ts.map +0 -1
  130. package/dist/types/src/services/service-registry.d.ts +0 -31
  131. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  132. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  133. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  134. package/dist/types/src/testing/index.d.ts +0 -3
  135. package/dist/types/src/testing/index.d.ts.map +0 -1
  136. package/dist/types/src/testing/layer.d.ts +0 -18
  137. package/dist/types/src/testing/layer.d.ts.map +0 -1
  138. package/dist/types/src/testing/logger.d.ts +0 -5
  139. package/dist/types/src/testing/logger.d.ts.map +0 -1
  140. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  141. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  142. package/dist/types/src/testing/services.d.ts +0 -59
  143. package/dist/types/src/testing/services.d.ts.map +0 -1
  144. package/dist/types/src/trace.d.ts +0 -122
  145. package/dist/types/src/trace.d.ts.map +0 -1
  146. package/dist/types/src/translations.d.ts +0 -12
  147. package/dist/types/src/translations.d.ts.map +0 -1
  148. package/dist/types/src/triggers/index.d.ts +0 -4
  149. package/dist/types/src/triggers/index.d.ts.map +0 -1
  150. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  151. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  152. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  153. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  154. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  155. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  156. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  157. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  158. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  159. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  160. package/dist/types/src/types.d.ts +0 -230
  161. package/dist/types/src/types.d.ts.map +0 -1
  162. package/dist/types/src/url.d.ts.map +0 -1
  163. package/src/bundler/bundler.test.ts +0 -58
  164. package/src/bundler/bundler.ts +0 -295
  165. package/src/bundler/index.ts +0 -5
  166. package/src/edge/functions.ts +0 -67
  167. package/src/edge/index.ts +0 -9
  168. package/src/examples/index.ts +0 -7
  169. package/src/executor/executor.ts +0 -58
  170. package/src/schema.ts +0 -71
  171. package/src/services/database.ts +0 -175
  172. package/src/services/function-invocation-service.test.ts +0 -81
  173. package/src/services/local-function-execution.ts +0 -153
  174. package/src/services/remote-function-execution-service.ts +0 -63
  175. package/src/services/service-container.ts +0 -115
  176. package/src/services/service-registry.test.ts +0 -45
  177. package/src/services/service-registry.ts +0 -63
  178. package/src/testing/index.ts +0 -6
  179. package/src/testing/layer.ts +0 -114
  180. package/src/testing/logger.ts +0 -17
  181. package/src/testing/persist-database.test.ts +0 -87
  182. package/src/testing/services.ts +0 -115
  183. package/src/trace.ts +0 -178
  184. package/src/translations.ts +0 -20
  185. package/src/triggers/index.ts +0 -7
  186. package/src/triggers/input-builder.ts +0 -35
  187. package/src/triggers/invocation-tracer.ts +0 -101
  188. package/src/triggers/trigger-dispatcher.test.ts +0 -665
  189. package/src/triggers/trigger-dispatcher.ts +0 -533
  190. package/src/triggers/trigger-state-store.ts +0 -61
  191. package/src/types.ts +0 -218
@@ -1,61 +1,88 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- ComputeEvent,
4
- ComputeEventLogger,
5
- ComputeEventPayload,
6
- ConfiguredCredentialsService,
7
- ContextQueueService,
8
- CredentialsService,
9
- DatabaseService,
10
- FUNCTIONS_META_KEY,
11
- FUNCTIONS_PRESET_META_KEY,
12
- FunctionError,
13
- FunctionNotFoundError,
14
- MESSAGE_PROPERTY_TOOL_CALL_ID,
15
- QueueService,
16
- RemoteFunctionExecutionService,
17
- SERVICE_TAGS,
18
- ServiceContainer,
19
- ServiceNotAvailableError,
20
- TracingService,
21
- TriggerStateNotFoundError,
22
- createDefectLogger,
23
- createEventLogger,
24
- getInvocationUrl,
25
- getUserFunctionIdInMetadata,
26
- logCustomEvent,
27
- setUserFunctionIdInMetadata,
28
- withAuthorization
29
- } from "./chunk-NAQIKLZB.mjs";
30
- import {
31
- __export
32
- } from "./chunk-HSLMI22Q.mjs";
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
7
+
8
+ // src/errors.ts
9
+ import { BaseError } from "@dxos/errors";
10
+ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
11
+ constructor(service, options) {
12
+ super({
13
+ context: {
14
+ service
15
+ },
16
+ ...options
17
+ });
18
+ }
19
+ };
20
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
21
+ constructor(functionKey, options) {
22
+ super({
23
+ context: {
24
+ function: functionKey
25
+ },
26
+ ...options
27
+ });
28
+ }
29
+ };
30
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
31
+ };
32
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
33
+ };
34
+
35
+ // src/example/fib.ts
36
+ import * as Effect2 from "effect/Effect";
37
+ import * as Schema6 from "effect/Schema";
33
38
 
34
- // src/handler.ts
39
+ // src/sdk.ts
35
40
  import * as Effect from "effect/Effect";
41
+ import * as Schema5 from "effect/Schema";
42
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
43
+ import { assertArgument, failedInvariant } from "@dxos/invariant";
44
+
45
+ // src/types/Function.ts
46
+ var Function_exports = {};
47
+ __export(Function_exports, {
48
+ Function: () => Function,
49
+ make: () => make2,
50
+ setFrom: () => setFrom
51
+ });
36
52
  import * as Schema2 from "effect/Schema";
37
- import { Obj, Type as Type2 } from "@dxos/echo";
38
- import { assertArgument } from "@dxos/invariant";
53
+ import { Annotation as Annotation2, JsonSchema, Obj as Obj2, Type as Type2 } from "@dxos/echo";
54
+ import { SystemTypeAnnotation } from "@dxos/echo/internal";
39
55
 
40
- // src/schema.ts
56
+ // src/types/Script.ts
57
+ var Script_exports = {};
58
+ __export(Script_exports, {
59
+ Script: () => Script,
60
+ make: () => make
61
+ });
41
62
  import * as Schema from "effect/Schema";
42
- import { Type } from "@dxos/echo";
43
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo/internal";
44
- import { DataType } from "@dxos/schema";
45
- var ScriptType = Schema.Struct({
46
- name: Schema.optional(Schema.String),
47
- description: Schema.optional(Schema.String),
63
+ import { Annotation, Obj, Ref, Type } from "@dxos/echo";
64
+ import { FormInputAnnotation } from "@dxos/echo/internal";
65
+ import { Text } from "@dxos/schema";
66
+ var Script = Schema.Struct({
67
+ name: Schema.String.pipe(Schema.optional),
68
+ description: Schema.String.pipe(Schema.optional),
48
69
  // TODO(burdon): Change to hash of deployed content.
49
70
  // Whether source has changed since last deploy.
50
- changed: Schema.optional(Schema.Boolean),
51
- source: Ref(DataType.Text)
71
+ changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),
72
+ source: Type.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
52
73
  }).pipe(Type.Obj({
53
74
  typename: "dxos.org/type/Script",
54
75
  version: "0.1.0"
55
- }), LabelAnnotation.set([
76
+ }), Annotation.LabelAnnotation.set([
56
77
  "name"
57
78
  ]));
58
- var FunctionType = Schema.Struct({
79
+ var make = ({ source = "", ...props } = {}) => Obj.make(Script, {
80
+ ...props,
81
+ source: Ref.make(Text.make(source))
82
+ });
83
+
84
+ // src/types/Function.ts
85
+ var Function = Schema2.Struct({
59
86
  /**
60
87
  * Global registry ID.
61
88
  * NOTE: The `key` property refers to the original registry entry.
@@ -63,175 +90,86 @@ var FunctionType = Schema.Struct({
63
90
  // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
64
91
  // TODO(dmaretskyi): Consider making it part of ECHO meta.
65
92
  // TODO(dmaretskyi): Make required.
66
- key: Schema.optional(Schema.String).annotations({
93
+ key: Schema2.optional(Schema2.String).annotations({
67
94
  description: "Unique registration key for the blueprint"
68
95
  }),
69
- // TODO(burdon): Rename to id/uri?
70
- name: Schema.NonEmptyString,
71
- version: Schema.String,
72
- description: Schema.optional(Schema.String),
96
+ name: Schema2.NonEmptyString,
97
+ version: Schema2.String,
98
+ description: Schema2.optional(Schema2.String),
99
+ /**
100
+ * ISO date string of the last deployment.
101
+ */
102
+ updated: Schema2.optional(Schema2.String),
73
103
  // Reference to a source script if it exists within ECHO.
74
104
  // TODO(burdon): Don't ref ScriptType directly (core).
75
- source: Schema.optional(Ref(ScriptType)),
76
- inputSchema: Schema.optional(JsonSchemaType),
77
- outputSchema: Schema.optional(JsonSchemaType),
105
+ source: Schema2.optional(Type2.Ref(Script)),
106
+ inputSchema: Schema2.optional(JsonSchema.JsonSchema),
107
+ outputSchema: Schema2.optional(JsonSchema.JsonSchema),
108
+ /**
109
+ * List of required services.
110
+ * Match the Context.Tag keys of the FunctionServices variants.
111
+ */
112
+ services: Schema2.optional(Schema2.Array(Schema2.String)),
78
113
  // Local binding to a function name.
79
- binding: Schema.optional(Schema.String)
80
- }).pipe(Type.Obj({
114
+ binding: Schema2.optional(Schema2.String)
115
+ }).pipe(Type2.Obj({
81
116
  typename: "dxos.org/type/Function",
82
117
  version: "0.1.0"
83
- }), LabelAnnotation.set([
118
+ }), Annotation2.LabelAnnotation.set([
84
119
  "name"
85
- ]));
86
-
87
- // src/handler.ts
88
- var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
89
- var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema2.Any, handler }) => {
90
- if (!Schema2.isSchema(inputSchema)) {
91
- throw new Error("Input schema must be a valid schema");
92
- }
93
- if (typeof handler !== "function") {
94
- throw new Error("Handler must be a function");
95
- }
96
- const limit = Error.stackTraceLimit;
97
- Error.stackTraceLimit = 2;
98
- const traceError = new Error();
99
- Error.stackTraceLimit = limit;
100
- let cache = false;
101
- const captureStackTrace = () => {
102
- if (cache !== false) {
103
- return cache;
104
- }
105
- if (traceError.stack !== void 0) {
106
- const stack = traceError.stack.split("\n");
107
- if (stack[2] !== void 0) {
108
- cache = stack[2].trim();
109
- return cache;
110
- }
111
- }
112
- };
113
- const handlerWithSpan = (...args) => {
114
- const result = handler(...args);
115
- if (Effect.isEffect(result)) {
116
- return Effect.withSpan(result, `${key ?? name}`, {
117
- captureStackTrace
118
- });
119
- }
120
- return result;
121
- };
122
- return {
123
- [typeId]: true,
124
- key,
125
- name,
126
- description,
127
- inputSchema,
128
- outputSchema,
129
- handler: handlerWithSpan
130
- };
131
- };
132
- var FunctionDefinition = {
133
- make: defineFunction,
134
- isFunction: (value) => {
135
- return typeof value === "object" && value !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value;
136
- },
137
- serialize: (functionDef) => {
138
- assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
139
- return serializeFunction(functionDef);
140
- },
141
- deserialize: (functionObj) => {
142
- assertArgument(Obj.instanceOf(FunctionType, functionObj), "functionObj");
143
- return deserializeFunction(functionObj);
144
- }
145
- };
146
- var serializeFunction = (functionDef) => {
147
- const fn6 = Obj.make(FunctionType, {
148
- key: functionDef.key,
149
- name: functionDef.name,
150
- version: "0.1.0",
151
- description: functionDef.description,
152
- inputSchema: Type2.toJsonSchema(functionDef.inputSchema),
153
- outputSchema: !functionDef.outputSchema ? void 0 : Type2.toJsonSchema(functionDef.outputSchema)
154
- });
155
- if (functionDef.meta?.deployedFunctionId) {
156
- setUserFunctionIdInMetadata(Obj.getMeta(fn6), functionDef.meta.deployedFunctionId);
157
- }
158
- return fn6;
159
- };
160
- var deserializeFunction = (functionObj) => {
161
- return {
162
- [typeId]: true,
163
- // TODO(dmaretskyi): Fix key.
164
- key: functionObj.key ?? functionObj.name,
165
- name: functionObj.name,
166
- description: functionObj.description,
167
- inputSchema: !functionObj.inputSchema ? Schema2.Unknown : Type2.toEffectSchema(functionObj.inputSchema),
168
- outputSchema: !functionObj.outputSchema ? void 0 : Type2.toEffectSchema(functionObj.outputSchema),
169
- // TODO(dmaretskyi): This should throw error.
170
- handler: () => {
171
- },
172
- meta: {
173
- deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj))
174
- }
175
- };
120
+ ]), SystemTypeAnnotation.set(true));
121
+ var make2 = (props) => Obj2.make(Function, props);
122
+ var setFrom = (target, source) => {
123
+ target.key = source.key ?? target.key;
124
+ target.name = source.name ?? target.name;
125
+ target.version = source.version;
126
+ target.description = source.description;
127
+ target.updated = source.updated;
128
+ target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : void 0;
129
+ target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : void 0;
130
+ Obj2.getMeta(target).keys = JSON.parse(JSON.stringify(Obj2.getMeta(source).keys));
176
131
  };
177
132
 
178
- // src/trace.ts
179
- import * as Schema4 from "effect/Schema";
180
- import { Type as Type4 } from "@dxos/echo";
181
- import { ObjectId } from "@dxos/echo/internal";
182
- import { Queue } from "@dxos/echo-db";
183
- import { log } from "@dxos/log";
184
-
185
- // src/types.ts
133
+ // src/types/Trigger.ts
134
+ var Trigger_exports = {};
135
+ __export(Trigger_exports, {
136
+ EmailSpec: () => EmailSpec,
137
+ Kinds: () => Kinds,
138
+ QueueSpec: () => QueueSpec,
139
+ Spec: () => Spec,
140
+ SubscriptionSpec: () => SubscriptionSpec,
141
+ TimerSpec: () => TimerSpec,
142
+ Trigger: () => Trigger,
143
+ WebhookSpec: () => WebhookSpec,
144
+ make: () => make3
145
+ });
186
146
  import * as Schema3 from "effect/Schema";
187
147
  import * as SchemaAST from "effect/SchemaAST";
188
- import { Obj as Obj2, QueryAST, Type as Type3 } from "@dxos/echo";
189
- import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2 } from "@dxos/echo/internal";
148
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
149
+ import { OptionsAnnotationId, SystemTypeAnnotation as SystemTypeAnnotation2 } from "@dxos/echo/internal";
190
150
  import { DXN } from "@dxos/keys";
191
- var TriggerKinds = [
192
- "timer",
193
- "webhook",
194
- "subscription",
151
+ var Kinds = [
195
152
  "email",
196
- "queue"
153
+ "queue",
154
+ "subscription",
155
+ "timer",
156
+ "webhook"
197
157
  ];
198
158
  var kindLiteralAnnotations = {
199
159
  title: "Kind"
200
160
  };
201
- var TimerTriggerSchema = Schema3.Struct({
202
- kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
203
- cron: Schema3.String.annotations({
204
- title: "Cron",
205
- [SchemaAST.ExamplesAnnotationId]: [
206
- "0 0 * * *"
207
- ]
208
- })
209
- }).pipe(Schema3.mutable);
210
- var EmailTriggerSchema = Schema3.Struct({
161
+ var EmailSpec = Schema3.Struct({
211
162
  kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
212
163
  }).pipe(Schema3.mutable);
213
- var QueueTriggerSchema = Schema3.Struct({
164
+ var QueueSpec = Schema3.Struct({
214
165
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
215
166
  // TODO(dmaretskyi): Change to a reference.
216
167
  queue: DXN.Schema
217
168
  }).pipe(Schema3.mutable);
218
- var WebhookTriggerSchema = Schema3.Struct({
219
- kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
220
- method: Schema3.optional(Schema3.String.annotations({
221
- title: "Method",
222
- [OptionsAnnotationId]: [
223
- "GET",
224
- "POST"
225
- ]
226
- })),
227
- port: Schema3.optional(Schema3.Number.annotations({
228
- title: "Port"
229
- }))
230
- }).pipe(Schema3.mutable);
231
- var SubscriptionTriggerSchema = Schema3.Struct({
169
+ var SubscriptionSpec = Schema3.Struct({
232
170
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
233
171
  query: Schema3.Struct({
234
- string: Schema3.optional(Schema3.String.annotations({
172
+ raw: Schema3.optional(Schema3.String.annotations({
235
173
  title: "Query"
236
174
  })),
237
175
  ast: QueryAST.Query
@@ -249,54 +187,37 @@ var SubscriptionTriggerSchema = Schema3.Struct({
249
187
  title: "Options"
250
188
  }))
251
189
  }).pipe(Schema3.mutable);
252
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
190
+ var TimerSpec = Schema3.Struct({
191
+ kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
192
+ cron: Schema3.String.annotations({
193
+ title: "Cron",
194
+ [SchemaAST.ExamplesAnnotationId]: [
195
+ "0 0 * * *"
196
+ ]
197
+ })
198
+ }).pipe(Schema3.mutable);
199
+ var WebhookSpec = Schema3.Struct({
200
+ kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
201
+ method: Schema3.optional(Schema3.String.annotations({
202
+ title: "Method",
203
+ [OptionsAnnotationId]: [
204
+ "GET",
205
+ "POST"
206
+ ]
207
+ })),
208
+ port: Schema3.optional(Schema3.Number.annotations({
209
+ title: "Port"
210
+ }))
211
+ }).pipe(Schema3.mutable);
212
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
253
213
  title: "Trigger"
254
214
  });
255
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
256
- from: Schema3.String,
257
- to: Schema3.String,
258
- subject: Schema3.String,
259
- created: Schema3.String,
260
- body: Schema3.String
261
- }));
262
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
263
- url: Schema3.String,
264
- method: Schema3.Literal("GET", "POST"),
265
- headers: Schema3.Record({
266
- key: Schema3.String,
267
- value: Schema3.String
268
- }),
269
- bodyText: Schema3.String
270
- }));
271
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
272
- queue: DXN.Schema,
273
- item: Schema3.Any,
274
- cursor: Schema3.String
275
- }));
276
- var SubscriptionTriggerOutput = Schema3.Struct({
277
- /**
278
- * Type of the mutation.
279
- */
280
- // TODO(dmaretskyi): Specify enum.
281
- type: Schema3.String,
282
- /**
283
- * Reference to the object that was changed or created.
284
- */
285
- subject: Type3.Ref(Obj2.Any),
286
- /**
287
- * @deprecated
288
- */
289
- changedObjectId: Schema3.optional(Schema3.String)
290
- }).pipe(Schema3.mutable);
291
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
292
- tick: Schema3.Number
293
- }));
294
- var FunctionTrigger_ = Schema3.Struct({
215
+ var Trigger_ = Schema3.Struct({
295
216
  /**
296
217
  * Function or workflow to invoke.
297
218
  */
298
219
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
299
- function: Schema3.optional(Ref2(Expando).annotations({
220
+ function: Schema3.optional(Type3.Ref(Type3.Expando).annotations({
300
221
  title: "Function"
301
222
  })),
302
223
  /**
@@ -310,7 +231,7 @@ var FunctionTrigger_ = Schema3.Struct({
310
231
  enabled: Schema3.optional(Schema3.Boolean.annotations({
311
232
  title: "Enabled"
312
233
  })),
313
- spec: Schema3.optional(TriggerSchema),
234
+ spec: Schema3.optional(Spec),
314
235
  /**
315
236
  * Passed as the input data to the function.
316
237
  * Must match the function's input schema.
@@ -327,963 +248,203 @@ var FunctionTrigger_ = Schema3.Struct({
327
248
  value: Schema3.Any
328
249
  })))
329
250
  }).pipe(Type3.Obj({
330
- typename: "dxos.org/type/FunctionTrigger",
331
- version: "0.2.0"
332
- }));
333
- var FunctionTrigger = FunctionTrigger_;
334
- var FunctionManifestSchema = Schema3.Struct({
335
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
336
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
337
- });
338
- var FUNCTION_TYPES = [
339
- FunctionType,
340
- FunctionTrigger
341
- ];
251
+ typename: "dxos.org/type/Trigger",
252
+ version: "0.1.0"
253
+ }), SystemTypeAnnotation2.set(true));
254
+ var Trigger = Trigger_;
255
+ var make3 = (props) => Obj3.make(Trigger, props);
342
256
 
343
- // src/trace.ts
344
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
345
- var InvocationOutcome = /* @__PURE__ */ (function(InvocationOutcome2) {
346
- InvocationOutcome2["SUCCESS"] = "success";
347
- InvocationOutcome2["FAILURE"] = "failure";
348
- InvocationOutcome2["PENDING"] = "pending";
349
- return InvocationOutcome2;
350
- })({});
351
- var InvocationTraceEventType = /* @__PURE__ */ (function(InvocationTraceEventType2) {
352
- InvocationTraceEventType2["START"] = "start";
353
- InvocationTraceEventType2["END"] = "end";
354
- return InvocationTraceEventType2;
355
- })({});
356
- var TraceEventException = Schema4.Struct({
357
- timestamp: Schema4.Number,
358
- message: Schema4.String,
359
- name: Schema4.String,
360
- stack: Schema4.optional(Schema4.String)
257
+ // src/types/TriggerEvent.ts
258
+ var TriggerEvent_exports = {};
259
+ __export(TriggerEvent_exports, {
260
+ EmailEvent: () => EmailEvent,
261
+ QueueEvent: () => QueueEvent,
262
+ SubscriptionEvent: () => SubscriptionEvent,
263
+ TimerEvent: () => TimerEvent,
264
+ WebhookEvent: () => WebhookEvent
361
265
  });
362
- var InvocationTraceStartEvent = Schema4.Struct({
363
- /**
364
- * Queue message id.
365
- */
366
- id: ObjectId,
367
- type: Schema4.Literal("start"),
368
- /**
369
- * Invocation id, the same for invocation start and end events.
370
- */
371
- invocationId: ObjectId,
372
- /**
373
- * Event generation time.
374
- */
375
- timestamp: Schema4.Number,
376
- /**
377
- * Data passed to function / workflow as an argument.
378
- */
379
- // TODO(burdon): Input schema?
380
- input: Schema4.Object,
381
- /**
382
- * Queue for function/workflow invocation events.
383
- */
384
- invocationTraceQueue: Schema4.optional(Type4.Ref(Queue)),
385
- /**
386
- * DXN of the invoked function/workflow.
387
- */
388
- invocationTarget: Schema4.optional(Type4.Ref(Type4.Expando)),
389
- /**
390
- * Present for automatic invocations.
391
- */
392
- trigger: Schema4.optional(Type4.Ref(FunctionTrigger))
393
- }).pipe(Type4.Obj({
394
- typename: "dxos.org/type/InvocationTraceStart",
395
- version: "0.1.0"
266
+ import * as Schema4 from "effect/Schema";
267
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
268
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
269
+ from: Schema4.String,
270
+ to: Schema4.String,
271
+ subject: Schema4.String,
272
+ created: Schema4.String,
273
+ body: Schema4.String
396
274
  }));
397
- var InvocationTraceEndEvent = Schema4.Struct({
275
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
276
+ queue: DXN2.Schema,
277
+ item: Schema4.Any,
278
+ cursor: Schema4.String
279
+ }));
280
+ var SubscriptionEvent = Schema4.Struct({
398
281
  /**
399
- * Trace event id.
282
+ * Type of the mutation.
400
283
  */
401
- id: ObjectId,
402
- type: Schema4.Literal("end"),
284
+ // TODO(dmaretskyi): Specify enum.
285
+ type: Schema4.String,
403
286
  /**
404
- * Invocation id, will be the same for invocation start and end.
287
+ * Reference to the object that was changed or created.
405
288
  */
406
- invocationId: ObjectId,
289
+ subject: Type4.Ref(Obj4.Any),
407
290
  /**
408
- * Event generation time.
291
+ * @deprecated
409
292
  */
410
- // TODO(burdon): Remove ms suffix.
411
- timestamp: Schema4.Number,
412
- outcome: Schema4.Enums(InvocationOutcome),
413
- exception: Schema4.optional(TraceEventException)
414
- }).pipe(Type4.Obj({
415
- typename: "dxos.org/type/InvocationTraceEnd",
416
- version: "0.1.0"
293
+ changedObjectId: Schema4.optional(Schema4.String)
294
+ }).pipe(Schema4.mutable);
295
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
296
+ tick: Schema4.Number
417
297
  }));
418
- var TraceEventLog = Schema4.Struct({
419
- timestamp: Schema4.Number,
420
- level: Schema4.String,
421
- message: Schema4.String,
422
- context: Schema4.optional(Schema4.Object)
423
- });
424
- var TraceEvent = Schema4.Struct({
425
- id: ObjectId,
426
- // TODO(burdon): Need enum/numeric result (not string).
427
- outcome: Schema4.String,
428
- truncated: Schema4.Boolean,
429
- /** Time when the event was persisted. */
430
- ingestionTimestamp: Schema4.Number,
431
- logs: Schema4.Array(TraceEventLog),
432
- exceptions: Schema4.Array(TraceEventException)
433
- }).pipe(Type4.Obj({
434
- typename: "dxos.org/type/TraceEvent",
435
- version: "0.1.0"
298
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
299
+ url: Schema4.String,
300
+ method: Schema4.Literal("GET", "POST"),
301
+ headers: Schema4.Record({
302
+ key: Schema4.String,
303
+ value: Schema4.String
304
+ }),
305
+ bodyText: Schema4.String
436
306
  }));
437
- var createInvocationSpans = (items) => {
438
- if (!items) {
439
- return [];
440
- }
441
- const eventsByInvocationId = /* @__PURE__ */ new Map();
442
- for (const event of items) {
443
- if (!("invocationId" in event)) {
444
- continue;
445
- }
446
- const invocationId = event.invocationId;
447
- const entry = eventsByInvocationId.get(invocationId) || {
448
- start: void 0,
449
- end: void 0
450
- };
451
- if (event.type === "start") {
452
- entry.start = event;
453
- } else if (event.type === "end") {
454
- entry.end = event;
455
- }
456
- eventsByInvocationId.set(invocationId, entry);
457
- }
458
- const now = Date.now();
459
- const result = [];
460
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
461
- if (!start) {
462
- log.warn("found end event without matching start", {
463
- invocationId
464
- }, {
465
- F: __dxlog_file,
466
- L: 158,
467
- S: void 0,
468
- C: (f, a) => f(...a)
469
- });
470
- continue;
307
+
308
+ // src/types/url.ts
309
+ var FUNCTIONS_META_KEY = "dxos.org/service/function";
310
+ var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
311
+ var getUserFunctionIdInMetadata = (meta) => {
312
+ return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
313
+ };
314
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
315
+ const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
316
+ if (key) {
317
+ if (key.id !== functionId) {
318
+ throw new Error("Metadata mismatch");
471
319
  }
472
- const isInProgress = end === void 0;
473
- result.push({
474
- id: invocationId,
475
- timestamp: start.timestamp,
476
- duration: isInProgress ? now - start.timestamp : end.timestamp - start.timestamp,
477
- outcome: end?.outcome ?? "pending",
478
- exception: end?.exception,
479
- input: start.input,
480
- invocationTraceQueue: start.invocationTraceQueue,
481
- invocationTarget: start.invocationTarget,
482
- trigger: start.trigger
320
+ } else {
321
+ meta.keys.push({
322
+ source: FUNCTIONS_META_KEY,
323
+ id: functionId
483
324
  });
484
325
  }
485
- return result;
486
326
  };
487
327
 
488
- // src/triggers/invocation-tracer.ts
489
- import * as Context3 from "effect/Context";
490
- import * as Effect4 from "effect/Effect";
491
- import * as Layer3 from "effect/Layer";
492
- import { Obj as Obj3, Ref as Ref3 } from "@dxos/echo";
493
- import { DXN as DXN2, ObjectId as ObjectId2 } from "@dxos/keys";
494
-
495
- // src/services/function-invocation-service.ts
496
- import * as Context2 from "effect/Context";
497
- import * as Effect3 from "effect/Effect";
498
- import * as Layer2 from "effect/Layer";
499
- import { AiService as AiService2 } from "@dxos/ai";
500
-
501
- // src/services/local-function-execution.ts
502
- import * as Context from "effect/Context";
503
- import * as Effect2 from "effect/Effect";
504
- import * as Layer from "effect/Layer";
505
- import * as Schema5 from "effect/Schema";
506
- import { AiService } from "@dxos/ai";
507
- import { todo } from "@dxos/debug";
508
- import { log as log2 } from "@dxos/log";
509
- function _define_property(obj, key, value) {
510
- if (key in obj) {
511
- Object.defineProperty(obj, key, {
512
- value,
513
- enumerable: true,
514
- configurable: true,
515
- writable: true
516
- });
517
- } else {
518
- obj[key] = value;
328
+ // src/sdk.ts
329
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
330
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, types, services }) => {
331
+ if (!Schema5.isSchema(inputSchema)) {
332
+ throw new Error("Input schema must be a valid schema");
519
333
  }
520
- return obj;
521
- }
522
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/services/local-function-execution.ts";
523
- var _Context_Tag;
524
- var LocalFunctionExecutionService = class extends (_Context_Tag = Context.Tag("@dxos/functions/LocalFunctionExecutionService")()) {
525
- };
526
- _define_property(LocalFunctionExecutionService, "layerLive", Layer.effect(LocalFunctionExecutionService, Effect2.gen(function* () {
527
- const resolver = yield* FunctionImplementationResolver;
528
- const ai = yield* AiService.AiService;
529
- const credentials = yield* CredentialsService;
530
- const database = yield* DatabaseService;
531
- const queues = yield* QueueService;
532
- const functionCallService = yield* RemoteFunctionExecutionService;
533
- return {
534
- // TODO(dmaretskyi): Better error types.
535
- invokeFunction: (functionDef, input) => Effect2.gen(function* () {
536
- const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect2.orDie);
537
- const output = yield* invokeFunction(resolved, input);
538
- return output;
539
- }).pipe(Effect2.provideService(AiService.AiService, ai), Effect2.provideService(CredentialsService, credentials), Effect2.provideService(DatabaseService, database), Effect2.provideService(QueueService, queues), Effect2.provideService(RemoteFunctionExecutionService, functionCallService))
540
- };
541
- })));
542
- _define_property(LocalFunctionExecutionService, "invokeFunction", Effect2.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction));
543
- var invokeFunction = (functionDef, input) => Effect2.gen(function* () {
544
- try {
545
- const assertInput = functionDef.inputSchema.pipe(Schema5.asserts);
546
- assertInput(input);
547
- } catch (e) {
548
- throw new FunctionError({
549
- message: "Invalid function input",
550
- context: {
551
- name: functionDef.name
552
- },
553
- cause: e
554
- });
334
+ if (typeof handler !== "function") {
335
+ throw new Error("Handler must be a function");
555
336
  }
556
- const context = {
557
- space: void 0,
558
- getService: () => todo(),
559
- getSpace: async (_spaceId) => {
560
- throw new Error("Not available. Use the database service instead.");
561
- }
562
- };
563
- log2.info("invoking function", {
564
- name: functionDef.name,
565
- input
566
- }, {
567
- F: __dxlog_file2,
568
- L: 98,
569
- S: this,
570
- C: (f, a) => f(...a)
571
- });
572
- const data = yield* Effect2.gen(function* () {
573
- const result = functionDef.handler({
574
- context,
575
- data: input
576
- });
577
- if (Effect2.isEffect(result)) {
578
- return yield* result.pipe(Effect2.orDie);
579
- } else if (typeof result === "object" && result !== null && "then" in result && typeof result.then === "function") {
580
- return yield* Effect2.promise(() => result);
581
- } else {
582
- return result;
583
- }
584
- }).pipe(Effect2.orDie, Effect2.catchAllDefect((defect) => Effect2.die(new FunctionError({
585
- context: {
586
- name: functionDef.name
587
- },
588
- cause: defect
589
- }))));
590
- log2.info("completed", {
591
- function: functionDef.name,
592
- input,
593
- data
594
- }, {
595
- F: __dxlog_file2,
596
- L: 122,
597
- S: this,
598
- C: (f, a) => f(...a)
599
- });
600
- try {
601
- const assertOutput = functionDef.outputSchema?.pipe(Schema5.asserts);
602
- assertOutput(data);
603
- } catch (e) {
604
- throw new FunctionError({
605
- message: "Invalid function output",
606
- context: {
607
- name: functionDef.name
608
- },
609
- cause: e
610
- });
611
- }
612
- return data;
613
- }).pipe(Effect2.withSpan("invokeFunction", {
614
- attributes: {
615
- name: functionDef.name
616
- }
617
- }));
618
- var _Context_Tag1;
619
- var FunctionImplementationResolver = class extends (_Context_Tag1 = Context.Tag("@dxos/functions/FunctionImplementationResolver")()) {
620
- };
621
- _define_property(FunctionImplementationResolver, "layerTest", ({ functions }) => Layer.succeed(FunctionImplementationResolver, {
622
- resolveFunctionImplementation: (functionDef) => {
623
- const resolved = functions.find((f) => f.key === functionDef.key);
624
- if (!resolved) {
625
- return Effect2.fail(new FunctionNotFoundError(functionDef.name));
337
+ const limit = Error.stackTraceLimit;
338
+ Error.stackTraceLimit = 2;
339
+ const traceError = new Error();
340
+ Error.stackTraceLimit = limit;
341
+ let cache = false;
342
+ const captureStackTrace = () => {
343
+ if (cache !== false) {
344
+ return cache;
626
345
  }
627
- return Effect2.succeed(resolved);
628
- }
629
- }));
630
-
631
- // src/services/function-invocation-service.ts
632
- function _define_property2(obj, key, value) {
633
- if (key in obj) {
634
- Object.defineProperty(obj, key, {
635
- value,
636
- enumerable: true,
637
- configurable: true,
638
- writable: true
639
- });
640
- } else {
641
- obj[key] = value;
642
- }
643
- return obj;
644
- }
645
- var _Context_Tag2;
646
- var FunctionInvocationService = class extends (_Context_Tag2 = Context2.Tag("@dxos/functions/FunctionInvocationService")()) {
647
- };
648
- _define_property2(FunctionInvocationService, "invokeFunction", Effect3.serviceFunctionEffect(FunctionInvocationService, (_) => _.invokeFunction));
649
- _define_property2(FunctionInvocationService, "layer", Layer2.effect(FunctionInvocationService, Effect3.gen(function* () {
650
- const localExecutioner = yield* LocalFunctionExecutionService;
651
- const remoteExecutioner = yield* RemoteFunctionExecutionService;
652
- return {
653
- invokeFunction: (functionDef, input) => Effect3.gen(function* () {
654
- if (functionDef.meta?.deployedFunctionId) {
655
- return yield* remoteExecutioner.callFunction(functionDef.meta.deployedFunctionId, input);
346
+ if (traceError.stack !== void 0) {
347
+ const stack = traceError.stack.split("\n");
348
+ if (stack[2] !== void 0) {
349
+ cache = stack[2].trim();
350
+ return cache;
656
351
  }
657
- return yield* localExecutioner.invokeFunction(functionDef, input);
658
- })
352
+ }
659
353
  };
660
- })));
661
- _define_property2(FunctionInvocationService, "layerTest", ({ functions = [] } = {}) => FunctionInvocationService.layer.pipe(Layer2.provide(LocalFunctionExecutionService.layerLive), Layer2.provide(FunctionImplementationResolver.layerTest({
662
- functions
663
- })), Layer2.provide(RemoteFunctionExecutionService.layerMock)));
664
- _define_property2(FunctionInvocationService, "layerTestMocked", ({ functions }) => FunctionInvocationService.layerTest({
665
- functions
666
- }).pipe(Layer2.provide(AiService2.notAvailable), Layer2.provide(CredentialsService.configuredLayer([])), Layer2.provide(DatabaseService.notAvailable), Layer2.provide(QueueService.notAvailable)));
667
-
668
- // src/triggers/invocation-tracer.ts
669
- function _define_property3(obj, key, value) {
670
- if (key in obj) {
671
- Object.defineProperty(obj, key, {
672
- value,
673
- enumerable: true,
674
- configurable: true,
675
- writable: true
676
- });
677
- } else {
678
- obj[key] = value;
679
- }
680
- return obj;
681
- }
682
- var _Context_Tag3;
683
- var InvocationTracer = class extends (_Context_Tag3 = Context3.Tag("@dxos/functions/InvocationTracer")()) {
684
- };
685
- _define_property3(InvocationTracer, "layerLive", (opts) => Layer3.effect(InvocationTracer, Effect4.gen(function* () {
686
- return {
687
- traceInvocationStart: Effect4.fn("traceInvocationStart")(function* ({ payload, target }) {
688
- const invocationId = ObjectId2.random();
689
- const invocationTraceQueue = yield* QueueService.createQueue({
690
- subspaceTag: "trace"
691
- });
692
- const now = Date.now();
693
- const traceEvent = Obj3.make(InvocationTraceStartEvent, {
694
- type: InvocationTraceEventType.START,
695
- invocationId,
696
- timestamp: now,
697
- // TODO(dmaretskyi): Not json-stringifying this makes ECHO fail when one ECHO object becomes embedded in another ECHO object.
698
- input: JSON.parse(JSON.stringify(payload.data ?? {})),
699
- invocationTraceQueue: Ref3.fromDXN(invocationTraceQueue.dxn),
700
- invocationTarget: target ? Ref3.fromDXN(target) : void 0,
701
- trigger: payload.trigger ? Ref3.fromDXN(DXN2.fromLocalObjectId(payload.trigger.id)) : void 0
702
- });
703
- yield* QueueService.append(opts.invocationTraceQueue, [
704
- traceEvent
705
- ]);
706
- return {
707
- invocationId,
708
- invocationTraceQueue
709
- };
710
- }),
711
- traceInvocationEnd: Effect4.fn("traceInvocationEnd")(function* ({ trace, exception }) {
712
- const now = Date.now();
713
- const traceEvent = Obj3.make(InvocationTraceEndEvent, {
714
- type: InvocationTraceEventType.END,
715
- invocationId: trace.invocationId,
716
- timestamp: now,
717
- outcome: exception ? InvocationOutcome.FAILURE : InvocationOutcome.SUCCESS,
718
- exception: exception ? {
719
- name: exception.constructor.name,
720
- timestamp: now,
721
- message: exception?.message ?? "Unknown error",
722
- stack: exception?.stack
723
- } : void 0
354
+ const handlerWithSpan = (...args) => {
355
+ const result = handler(...args);
356
+ if (Effect.isEffect(result)) {
357
+ return Effect.withSpan(result, `${key ?? name}`, {
358
+ captureStackTrace
724
359
  });
725
- yield* QueueService.append(opts.invocationTraceQueue, [
726
- traceEvent
727
- ]);
728
- })
729
- };
730
- })));
731
- _define_property3(InvocationTracer, "layerTest", Layer3.unwrapEffect(Effect4.gen(function* () {
732
- const queue = yield* QueueService.createQueue({
733
- subspaceTag: "trace"
734
- });
735
- return InvocationTracer.layerLive({
736
- invocationTraceQueue: queue
737
- });
738
- })));
739
-
740
- // src/triggers/trigger-dispatcher.ts
741
- import * as Cause from "effect/Cause";
742
- import * as Context5 from "effect/Context";
743
- import * as Cron from "effect/Cron";
744
- import * as Duration from "effect/Duration";
745
- import * as Effect6 from "effect/Effect";
746
- import * as Either from "effect/Either";
747
- import * as Exit from "effect/Exit";
748
- import * as Fiber from "effect/Fiber";
749
- import * as Layer5 from "effect/Layer";
750
- import * as Option2 from "effect/Option";
751
- import * as Record3 from "effect/Record";
752
- import * as Schedule from "effect/Schedule";
753
- import { DXN as DXN3, Filter, Obj as Obj4, Query } from "@dxos/echo";
754
- import { causeToError } from "@dxos/effect";
755
- import { invariant } from "@dxos/invariant";
756
- import { log as log3 } from "@dxos/log";
757
- import { KEY_QUEUE_POSITION } from "@dxos/protocols";
758
-
759
- // src/triggers/input-builder.ts
760
- var createInvocationPayload = (trigger, event) => {
761
- if (!trigger.input) {
762
- return event;
763
- }
764
- const payload = {};
765
- for (const [key, value] of Object.entries(trigger.input)) {
766
- if (typeof value !== "string" || !(value.startsWith("{{") && value.endsWith("}}"))) {
767
- payload[key] = value;
768
- continue;
769
360
  }
770
- const propertyPath = value.slice(2, -2);
771
- let valueSubstitution = propertyPath.startsWith("trigger.") ? trigger : propertyPath.startsWith("event.") ? event : void 0;
772
- for (const pathSegment of propertyPath.split(".").slice(1)) {
773
- if (valueSubstitution && typeof valueSubstitution === "object") {
774
- valueSubstitution = valueSubstitution[pathSegment];
775
- }
776
- }
777
- payload[key] = valueSubstitution;
778
- }
779
- return payload;
361
+ return result;
362
+ };
363
+ return {
364
+ [typeId]: true,
365
+ key,
366
+ name,
367
+ description,
368
+ inputSchema,
369
+ outputSchema,
370
+ handler: handlerWithSpan,
371
+ types: types ?? [],
372
+ services: !services ? [] : getServiceKeys(services)
373
+ };
780
374
  };
781
-
782
- // src/triggers/trigger-state-store.ts
783
- import * as KeyValueStore from "@effect/platform/KeyValueStore";
784
- import * as Context4 from "effect/Context";
785
- import * as Effect5 from "effect/Effect";
786
- import * as Layer4 from "effect/Layer";
787
- import * as Option from "effect/Option";
788
- import * as Schema6 from "effect/Schema";
789
- import { ObjectId as ObjectId3 } from "@dxos/keys";
790
- function _define_property4(obj, key, value) {
791
- if (key in obj) {
792
- Object.defineProperty(obj, key, {
793
- value,
794
- enumerable: true,
795
- configurable: true,
796
- writable: true
797
- });
798
- } else {
799
- obj[key] = value;
800
- }
801
- return obj;
802
- }
803
- var TriggerState = Schema6.Struct({
804
- version: Schema6.Literal("1"),
805
- triggerId: Schema6.String,
806
- state: Schema6.optional(Schema6.Union(Schema6.TaggedStruct("subscription", {
807
- processedVersions: Schema6.Record({
808
- key: ObjectId3,
809
- value: Schema6.String
810
- })
811
- })))
812
- });
813
- var _Context_Tag4;
814
- var TriggerStateStore = class extends (_Context_Tag4 = Context4.Tag("@dxos/functions/TriggerStateStore")()) {
375
+ var getServiceKeys = (services) => {
376
+ return services.map((tag) => {
377
+ if (typeof tag.key === "string") {
378
+ return tag.key;
379
+ }
380
+ console.log(tag);
381
+ failedInvariant();
382
+ });
815
383
  };
816
- _define_property4(TriggerStateStore, "getState", Effect5.serviceFunctionEffect(TriggerStateStore, (_) => _.getState));
817
- _define_property4(TriggerStateStore, "saveState", Effect5.serviceFunctionEffect(TriggerStateStore, (_) => _.saveState));
818
- _define_property4(TriggerStateStore, "layerKv", Layer4.effect(TriggerStateStore, Effect5.gen(function* () {
819
- const kv = yield* KeyValueStore.KeyValueStore;
820
- const schemaStore = kv.forSchema(Schema6.parseJson(TriggerState));
821
- const store = {
822
- getState: Effect5.fn("TriggerStateStore.getState")(function* (triggerId) {
823
- const valueOption = yield* schemaStore.get(triggerId).pipe(Effect5.orDie);
824
- if (Option.isNone(valueOption)) {
825
- return yield* Effect5.fail(new TriggerStateNotFoundError());
826
- }
827
- return valueOption.value;
828
- }),
829
- saveState: Effect5.fn("TriggerStateStore.saveState")(function* (state) {
830
- yield* schemaStore.set(state.triggerId, state).pipe(Effect5.orDie);
831
- })
832
- };
833
- return store;
834
- })));
835
- _define_property4(TriggerStateStore, "layerMemory", TriggerStateStore.layerKv.pipe(Layer4.provide(KeyValueStore.layerMemory)));
836
-
837
- // src/triggers/trigger-dispatcher.ts
838
- function _define_property5(obj, key, value) {
839
- if (key in obj) {
840
- Object.defineProperty(obj, key, {
841
- value,
842
- enumerable: true,
843
- configurable: true,
844
- writable: true
845
- });
846
- } else {
847
- obj[key] = value;
384
+ var FunctionDefinition = {
385
+ make: defineFunction,
386
+ isFunction: (value2) => {
387
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
388
+ },
389
+ serialize: (functionDef) => {
390
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
391
+ return serializeFunction(functionDef);
392
+ },
393
+ deserialize: (functionObj) => {
394
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
395
+ return deserializeFunction(functionObj);
848
396
  }
849
- return obj;
850
- }
851
- var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/triggers/trigger-dispatcher.ts";
852
- var _Context_Tag5;
853
- var TriggerDispatcher = class extends (_Context_Tag5 = Context5.Tag("@dxos/functions/TriggerDispatcher")()) {
854
397
  };
855
- _define_property5(TriggerDispatcher, "layer", (options) => Layer5.effect(TriggerDispatcher, Effect6.gen(function* () {
856
- return new TriggerDispatcherImpl(options);
857
- })));
858
- var TriggerDispatcherImpl = class {
859
- get running() {
860
- return this._running;
861
- }
862
- constructor(options) {
863
- _define_property5(this, "livePollInterval", void 0);
864
- _define_property5(this, "timeControl", void 0);
865
- _define_property5(this, "_running", false);
866
- _define_property5(this, "_internalTime", void 0);
867
- _define_property5(this, "_timerFiber", void 0);
868
- _define_property5(this, "_scheduledTriggers", /* @__PURE__ */ new Map());
869
- _define_property5(this, "start", () => Effect6.gen(this, function* () {
870
- if (this._running) {
871
- return;
872
- }
873
- this._running = true;
874
- if (this.timeControl === "natural") {
875
- this._timerFiber = yield* this._startNaturalTimeProcessing().pipe(Effect6.tapErrorCause((cause) => {
876
- const error = causeToError(cause);
877
- log3.error("trigger dispatcher error", {
878
- error
879
- }, {
880
- F: __dxlog_file3,
881
- L: 187,
882
- S: this,
883
- C: (f, a) => f(...a)
884
- });
885
- this._running = false;
886
- return Effect6.void;
887
- }), Effect6.forkDaemon);
888
- } else {
889
- return yield* Effect6.dieMessage("TriggerDispatcher started in manual time control mode");
890
- }
891
- log3.info("TriggerDispatcher started", {
892
- timeControl: this.timeControl
893
- }, {
894
- F: __dxlog_file3,
895
- L: 197,
896
- S: this,
897
- C: (f, a) => f(...a)
898
- });
899
- }));
900
- _define_property5(this, "stop", () => Effect6.gen(this, function* () {
901
- if (!this._running) {
902
- return;
903
- }
904
- this._running = false;
905
- if (this._timerFiber) {
906
- yield* Fiber.interrupt(this._timerFiber);
907
- this._timerFiber = void 0;
908
- }
909
- this._scheduledTriggers.clear();
910
- log3.info("TriggerDispatcher stopped", void 0, {
911
- F: __dxlog_file3,
912
- L: 217,
913
- S: this,
914
- C: (f, a) => f(...a)
915
- });
916
- }));
917
- _define_property5(this, "invokeTrigger", (options2) => Effect6.gen(this, function* () {
918
- const { trigger, event } = options2;
919
- log3.info("running trigger", {
920
- triggerId: trigger.id,
921
- spec: trigger.spec,
922
- event
923
- }, {
924
- F: __dxlog_file3,
925
- L: 225,
926
- S: this,
927
- C: (f, a) => f(...a)
928
- });
929
- const tracer = yield* InvocationTracer;
930
- const trace = yield* tracer.traceInvocationStart({
931
- target: trigger.function?.dxn,
932
- payload: {
933
- trigger: {
934
- id: trigger.id,
935
- // TODO(dmaretskyi): Is `spec` always there>
936
- kind: trigger.spec.kind
937
- },
938
- data: event
939
- }
940
- });
941
- const result = yield* Effect6.gen(this, function* () {
942
- if (!trigger.enabled) {
943
- return yield* Effect6.dieMessage("Attempting to invoke disabled trigger");
944
- }
945
- if (!trigger.function) {
946
- return yield* Effect6.dieMessage("Trigger has no function reference");
947
- }
948
- const serialiedFunction = yield* DatabaseService.load(trigger.function).pipe(Effect6.orDie);
949
- invariant(Obj4.instanceOf(FunctionType, serialiedFunction), void 0, {
950
- F: __dxlog_file3,
951
- L: 252,
952
- S: this,
953
- A: [
954
- "Obj.instanceOf(FunctionType, serialiedFunction)",
955
- ""
956
- ]
957
- });
958
- const functionDef = deserializeFunction(serialiedFunction);
959
- const inputData = this._prepareInputData(trigger, event);
960
- return yield* FunctionInvocationService.invokeFunction(functionDef, inputData).pipe(Effect6.provide(ComputeEventLogger.layerFromTracing.pipe(Layer5.provideMerge(TracingService.layerQueue(trace.invocationTraceQueue)))));
961
- }).pipe(Effect6.exit);
962
- const triggerExecutionResult = {
963
- triggerId: trigger.id,
964
- result
965
- };
966
- if (Exit.isSuccess(result)) {
967
- log3.info("trigger execution success", {
968
- triggerId: trigger.id
969
- }, {
970
- F: __dxlog_file3,
971
- L: 273,
972
- S: this,
973
- C: (f, a) => f(...a)
974
- });
975
- } else {
976
- log3.error("trigger execution failure", {
977
- error: causeToError(result.cause)
978
- }, {
979
- F: __dxlog_file3,
980
- L: 277,
981
- S: this,
982
- C: (f, a) => f(...a)
983
- });
984
- }
985
- yield* tracer.traceInvocationEnd({
986
- trace,
987
- // TODO(dmaretskyi): Might miss errors.
988
- exception: Exit.isFailure(result) ? Cause.prettyErrors(result.cause)[0] : void 0
989
- });
990
- return triggerExecutionResult;
991
- }));
992
- _define_property5(this, "invokeScheduledTriggers", ({ kinds = [
993
- "timer",
994
- "queue",
995
- "subscription"
996
- ] } = {}) => Effect6.gen(this, function* () {
997
- const invocations = [];
998
- for (const kind of kinds) {
999
- switch (kind) {
1000
- case "timer":
1001
- {
1002
- yield* this.refreshTriggers();
1003
- const now = this.getCurrentTime();
1004
- const triggersToInvoke = [];
1005
- for (const [triggerId, scheduledTrigger] of this._scheduledTriggers.entries()) {
1006
- if (scheduledTrigger.nextExecution <= now) {
1007
- triggersToInvoke.push(scheduledTrigger.trigger);
1008
- scheduledTrigger.nextExecution = Cron.next(scheduledTrigger.cron, now);
1009
- }
1010
- }
1011
- invocations.push(...yield* Effect6.forEach(triggersToInvoke, (trigger) => this.invokeTrigger({
1012
- trigger,
1013
- event: {
1014
- tick: now.getTime()
1015
- }
1016
- }), {
1017
- concurrency: 1
1018
- }));
1019
- }
1020
- break;
1021
- case "queue": {
1022
- const triggers = yield* this._fetchTriggers();
1023
- for (const trigger of triggers) {
1024
- const spec = trigger.spec;
1025
- if (spec?.kind !== "queue") {
1026
- continue;
1027
- }
1028
- const cursor = Obj4.getKeys(trigger, KEY_QUEUE_CURSOR).at(0)?.id;
1029
- const queue = yield* QueueService.getQueue(DXN3.parse(spec.queue));
1030
- const objects = yield* Effect6.promise(() => queue.queryObjects());
1031
- for (const object of objects) {
1032
- const objectPos = Obj4.getKeys(object, KEY_QUEUE_POSITION).at(0)?.id;
1033
- if (!objectPos || cursor && parseInt(cursor) >= parseInt(objectPos)) {
1034
- continue;
1035
- }
1036
- invocations.push(yield* this.invokeTrigger({
1037
- trigger,
1038
- event: {
1039
- queue: spec.queue,
1040
- item: object,
1041
- cursor: objectPos
1042
- }
1043
- }));
1044
- Obj4.deleteKeys(trigger, KEY_QUEUE_CURSOR);
1045
- Obj4.getMeta(trigger).keys.push({
1046
- source: KEY_QUEUE_CURSOR,
1047
- id: objectPos
1048
- });
1049
- yield* DatabaseService.flush();
1050
- break;
1051
- }
1052
- }
1053
- break;
1054
- }
1055
- case "subscription": {
1056
- const triggers = yield* this._fetchTriggers();
1057
- for (const trigger of triggers) {
1058
- const spec = Obj4.getSnapshot(trigger).spec;
1059
- if (spec?.kind !== "subscription") {
1060
- continue;
1061
- }
1062
- const { objects } = yield* DatabaseService.runQuery(Query.fromAst(spec.query.ast));
1063
- const state = yield* TriggerStateStore.getState(trigger.id).pipe(Effect6.catchTag("TRIGGER_STATE_NOT_FOUND", () => Effect6.succeed({
1064
- version: "1",
1065
- triggerId: trigger.id,
1066
- state: {
1067
- _tag: "subscription",
1068
- processedVersions: {}
1069
- }
1070
- })));
1071
- invariant(state.state?._tag === "subscription", void 0, {
1072
- F: __dxlog_file3,
1073
- L: 390,
1074
- S: this,
1075
- A: [
1076
- "state.state?._tag === 'subscription'",
1077
- ""
1078
- ]
1079
- });
1080
- let updated = false;
1081
- for (const object of objects) {
1082
- const existingVersion = Record3.get(state.state.processedVersions, object.id).pipe(Option2.map(Obj4.decodeVersion));
1083
- const currentVersion = Obj4.version(object);
1084
- const run = Option2.isNone(existingVersion) || Obj4.compareVersions(currentVersion, existingVersion.value) === "different";
1085
- if (!run) {
1086
- continue;
1087
- }
1088
- const { db } = yield* DatabaseService;
1089
- invocations.push(yield* this.invokeTrigger({
1090
- trigger,
1091
- event: {
1092
- // TODO(dmaretskyi): Change type not supported.
1093
- type: "unknown",
1094
- subject: db.ref(Obj4.getDXN(object)),
1095
- changedObjectId: object.id
1096
- }
1097
- }));
1098
- state.state.processedVersions[object.id] = Obj4.encodeVersion(currentVersion);
1099
- updated = true;
1100
- }
1101
- if (updated) {
1102
- yield* TriggerStateStore.saveState(state);
1103
- }
1104
- }
1105
- break;
1106
- }
1107
- default: {
1108
- return yield* Effect6.dieMessage(`Unknown trigger kind: ${kind}`);
1109
- }
1110
- }
1111
- }
1112
- return invocations;
1113
- }));
1114
- _define_property5(this, "advanceTime", (duration) => Effect6.gen(this, function* () {
1115
- if (this.timeControl !== "manual") {
1116
- return yield* Effect6.dieMessage("advanceTime can only be used in manual time control mode");
1117
- }
1118
- const millis = Duration.toMillis(duration);
1119
- this._internalTime = new Date(this._internalTime.getTime() + millis);
1120
- log3("Advanced internal time", {
1121
- newTime: this._internalTime,
1122
- advancedBy: Duration.format(duration)
1123
- }, {
1124
- F: __dxlog_file3,
1125
- L: 447,
1126
- S: this,
1127
- C: (f, a) => f(...a)
1128
- });
1129
- }).pipe(Effect6.orDie));
1130
- _define_property5(this, "getCurrentTime", () => {
1131
- if (this.timeControl === "natural") {
1132
- return /* @__PURE__ */ new Date();
1133
- } else {
1134
- return new Date(this._internalTime);
1135
- }
1136
- });
1137
- _define_property5(this, "refreshTriggers", () => Effect6.gen(this, function* () {
1138
- const triggers = yield* this._fetchTriggers();
1139
- const currentTriggerIds = new Set(triggers.map((t) => t.id));
1140
- for (const triggerId of this._scheduledTriggers.keys()) {
1141
- if (!currentTriggerIds.has(triggerId)) {
1142
- this._scheduledTriggers.delete(triggerId);
1143
- }
1144
- }
1145
- for (const trigger of triggers) {
1146
- if (trigger.spec?.kind === "timer" && trigger.enabled) {
1147
- const timerSpec = trigger.spec;
1148
- const cronEither = Cron.parse(timerSpec.cron);
1149
- if (Either.isRight(cronEither)) {
1150
- const cron = cronEither.right;
1151
- const existing = this._scheduledTriggers.get(trigger.id);
1152
- const now = this.getCurrentTime();
1153
- const nextExecution = existing?.nextExecution ?? Cron.next(cron, now);
1154
- log3("Updated scheduled trigger", {
1155
- triggerId: trigger.id,
1156
- cron: timerSpec.cron,
1157
- nextExecution,
1158
- now
1159
- }, {
1160
- F: __dxlog_file3,
1161
- L: 487,
1162
- S: this,
1163
- C: (f, a) => f(...a)
1164
- });
1165
- this._scheduledTriggers.set(trigger.id, {
1166
- trigger,
1167
- cron,
1168
- nextExecution
1169
- });
1170
- } else {
1171
- log3.error("Invalid cron expression", {
1172
- triggerId: trigger.id,
1173
- cron: timerSpec.cron,
1174
- error: cronEither.left.message
1175
- }, {
1176
- F: __dxlog_file3,
1177
- L: 499,
1178
- S: this,
1179
- C: (f, a) => f(...a)
1180
- });
1181
- }
1182
- }
1183
- }
1184
- log3("Updated scheduled triggers", {
1185
- count: this._scheduledTriggers.size
1186
- }, {
1187
- F: __dxlog_file3,
1188
- L: 508,
1189
- S: this,
1190
- C: (f, a) => f(...a)
1191
- });
1192
- }).pipe(Effect6.withSpan("TriggerDispatcher.refreshTriggers")));
1193
- _define_property5(this, "_fetchTriggers", () => Effect6.gen(this, function* () {
1194
- const { objects } = yield* DatabaseService.runQuery(Filter.type(FunctionTrigger));
1195
- return objects;
1196
- }).pipe(Effect6.withSpan("TriggerDispatcher.fetchTriggers")));
1197
- _define_property5(this, "_startNaturalTimeProcessing", () => Effect6.gen(this, function* () {
1198
- yield* this.invokeScheduledTriggers();
1199
- }).pipe(Effect6.repeat(Schedule.fixed(this.livePollInterval)), Effect6.asVoid));
1200
- _define_property5(this, "_prepareInputData", (trigger, event) => {
1201
- return createInvocationPayload(trigger, event);
1202
- });
1203
- this.timeControl = options.timeControl;
1204
- this.livePollInterval = options.livePollInterval ?? Duration.seconds(1);
1205
- this._internalTime = options.startingTime ?? /* @__PURE__ */ new Date();
398
+ var serializeFunction = (functionDef) => {
399
+ const fn4 = Function_exports.make({
400
+ key: functionDef.key,
401
+ name: functionDef.name,
402
+ version: "0.1.0",
403
+ description: functionDef.description,
404
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
405
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema),
406
+ services: functionDef.services
407
+ });
408
+ if (functionDef.meta?.deployedFunctionId) {
409
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
1206
410
  }
411
+ return fn4;
1207
412
  };
1208
- var KEY_QUEUE_CURSOR = "dxos.org/key/local-trigger-dispatcher/queue-cursor";
1209
-
1210
- // src/executor/executor.ts
1211
- import * as Effect7 from "effect/Effect";
1212
- import * as Schema7 from "effect/Schema";
1213
- import { runAndForwardErrors } from "@dxos/effect";
1214
- function _define_property6(obj, key, value) {
1215
- if (key in obj) {
1216
- Object.defineProperty(obj, key, {
1217
- value,
1218
- enumerable: true,
1219
- configurable: true,
1220
- writable: true
1221
- });
1222
- } else {
1223
- obj[key] = value;
1224
- }
1225
- return obj;
1226
- }
1227
- var FunctionExecutor = class {
1228
- /**
1229
- * Invoke function.
1230
- */
1231
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
1232
- async invoke(functionDef, input) {
1233
- const assertInput = functionDef.inputSchema.pipe(Schema7.asserts);
1234
- assertInput(input);
1235
- const context = {
1236
- space: void 0,
1237
- getService: this._services.getService.bind(this._services),
1238
- getSpace: async (_spaceId) => {
1239
- throw new Error("Not available. Use the database service instead.");
1240
- }
1241
- };
1242
- const result = functionDef.handler({
1243
- context,
1244
- data: input
1245
- });
1246
- let data;
1247
- if (Effect7.isEffect(result)) {
1248
- data = await result.pipe(Effect7.provide(this._services.createLayer()), runAndForwardErrors);
1249
- } else {
1250
- data = await result;
413
+ var deserializeFunction = (functionObj) => {
414
+ return {
415
+ [typeId]: true,
416
+ // TODO(dmaretskyi): Fix key.
417
+ key: functionObj.key ?? functionObj.name,
418
+ name: functionObj.name,
419
+ description: functionObj.description,
420
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
421
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
422
+ // TODO(dmaretskyi): This should throw error.
423
+ handler: () => {
424
+ },
425
+ services: functionObj.services ?? [],
426
+ types: [],
427
+ meta: {
428
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
1251
429
  }
1252
- const assertOutput = functionDef.outputSchema?.pipe(Schema7.asserts);
1253
- assertOutput(data);
1254
- return data;
1255
- }
1256
- constructor(_services) {
1257
- _define_property6(this, "_services", void 0);
1258
- this._services = _services;
1259
- }
430
+ };
1260
431
  };
1261
432
 
1262
- // src/examples/index.ts
1263
- var examples_exports = {};
1264
- __export(examples_exports, {
1265
- fib: () => fib_default,
1266
- reply: () => reply_default,
1267
- sleep: () => sleep_default
1268
- });
1269
-
1270
- // src/examples/fib.ts
1271
- import * as Effect8 from "effect/Effect";
1272
- import * as Schema8 from "effect/Schema";
433
+ // src/example/fib.ts
1273
434
  var fib_default = defineFunction({
1274
435
  key: "example.org/function/fib",
1275
436
  name: "Fibonacci",
1276
437
  description: "Function that calculates a Fibonacci number",
1277
- inputSchema: Schema8.Struct({
1278
- iterations: Schema8.optional(Schema8.Number).annotations({
438
+ inputSchema: Schema6.Struct({
439
+ iterations: Schema6.optional(Schema6.Number).annotations({
1279
440
  description: "Number of iterations",
1280
441
  default: 1e5
1281
442
  })
1282
443
  }),
1283
- outputSchema: Schema8.Struct({
1284
- result: Schema8.String
444
+ outputSchema: Schema6.Struct({
445
+ result: Schema6.String
1285
446
  }),
1286
- handler: Effect8.fn(function* ({ data: { iterations = 1e5 } }) {
447
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
1287
448
  let a = 0n;
1288
449
  let b = 1n;
1289
450
  for (let i = 0; i < iterations; i++) {
@@ -1296,17 +457,17 @@ var fib_default = defineFunction({
1296
457
  })
1297
458
  });
1298
459
 
1299
- // src/examples/reply.ts
460
+ // src/example/reply.ts
1300
461
  import * as Console from "effect/Console";
1301
- import * as Effect9 from "effect/Effect";
1302
- import * as Schema9 from "effect/Schema";
462
+ import * as Effect3 from "effect/Effect";
463
+ import * as Schema7 from "effect/Schema";
1303
464
  var reply_default = defineFunction({
1304
465
  key: "example.org/function/reply",
1305
466
  name: "Reply",
1306
467
  description: "Function that echoes the input",
1307
- inputSchema: Schema9.Any,
1308
- outputSchema: Schema9.Any,
1309
- handler: Effect9.fn(function* ({ data }) {
468
+ inputSchema: Schema7.Any,
469
+ outputSchema: Schema7.Any,
470
+ handler: Effect3.fn(function* ({ data }) {
1310
471
  yield* Console.log("reply", {
1311
472
  data
1312
473
  });
@@ -1314,24 +475,524 @@ var reply_default = defineFunction({
1314
475
  })
1315
476
  });
1316
477
 
1317
- // src/examples/sleep.ts
1318
- import * as Effect10 from "effect/Effect";
1319
- import * as Schema10 from "effect/Schema";
478
+ // src/example/sleep.ts
479
+ import * as Effect4 from "effect/Effect";
480
+ import * as Schema8 from "effect/Schema";
1320
481
  var sleep_default = defineFunction({
1321
482
  key: "example.org/function/sleep",
1322
483
  name: "Sleep",
1323
484
  description: "Function that sleeps for a given amount of time",
1324
- inputSchema: Schema10.Struct({
1325
- duration: Schema10.optional(Schema10.Number).annotations({
485
+ inputSchema: Schema8.Struct({
486
+ duration: Schema8.optional(Schema8.Number).annotations({
1326
487
  description: "Milliseconds to sleep",
1327
488
  default: 1e5
1328
489
  })
1329
490
  }),
1330
- outputSchema: Schema10.Void,
1331
- handler: Effect10.fn(function* ({ data: { duration = 1e5 } }) {
1332
- yield* Effect10.sleep(duration);
491
+ outputSchema: Schema8.Void,
492
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
493
+ yield* Effect4.sleep(duration);
1333
494
  })
1334
495
  });
496
+
497
+ // src/example/index.ts
498
+ (function(Example2) {
499
+ Example2.fib = fib_default;
500
+ Example2.reply = reply_default;
501
+ Example2.sleep = sleep_default;
502
+ })(Example || (Example = {}));
503
+ var Example;
504
+
505
+ // src/services/index.ts
506
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
507
+
508
+ // src/services/credentials.ts
509
+ import * as HttpClient from "@effect/platform/HttpClient";
510
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
511
+ import * as Context from "effect/Context";
512
+ import * as Effect5 from "effect/Effect";
513
+ import * as Layer from "effect/Layer";
514
+ import * as Redacted from "effect/Redacted";
515
+ import { Query } from "@dxos/echo";
516
+ import { DatabaseService } from "@dxos/echo-db";
517
+ import { AccessToken } from "@dxos/types";
518
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
519
+ static getCredential = (query) => Effect5.gen(function* () {
520
+ const credentials = yield* _CredentialsService;
521
+ return yield* Effect5.promise(() => credentials.getCredential(query));
522
+ });
523
+ static getApiKey = (query) => Effect5.gen(function* () {
524
+ const credential = yield* _CredentialsService.getCredential(query);
525
+ if (!credential.apiKey) {
526
+ throw new Error(`API key not found for service: ${query.service}`);
527
+ }
528
+ return Redacted.make(credential.apiKey);
529
+ });
530
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
531
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
532
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
533
+ return {
534
+ service,
535
+ apiKey: Redacted.value(yield* apiKey)
536
+ };
537
+ }));
538
+ return new ConfiguredCredentialsService(serviceCredentials);
539
+ }));
540
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
541
+ const dbService = yield* DatabaseService;
542
+ const queryCredentials = async (query) => {
543
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
544
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
545
+ service: accessToken.source,
546
+ apiKey: accessToken.token
547
+ }));
548
+ };
549
+ return {
550
+ getCredential: async (query) => {
551
+ const credentials = await queryCredentials(query);
552
+ if (credentials.length === 0) {
553
+ throw new Error(`Credential not found for service: ${query.service}`);
554
+ }
555
+ return credentials[0];
556
+ },
557
+ queryCredentials: async (query) => {
558
+ return queryCredentials(query);
559
+ }
560
+ };
561
+ }));
562
+ };
563
+ var ConfiguredCredentialsService = class {
564
+ credentials;
565
+ constructor(credentials = []) {
566
+ this.credentials = credentials;
567
+ }
568
+ addCredentials(credentials) {
569
+ this.credentials.push(...credentials);
570
+ return this;
571
+ }
572
+ async queryCredentials(query) {
573
+ return this.credentials.filter((credential) => credential.service === query.service);
574
+ }
575
+ async getCredential(query) {
576
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
577
+ if (!credential) {
578
+ throw new Error(`Credential not found for service: ${query.service}`);
579
+ }
580
+ return credential;
581
+ }
582
+ };
583
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
584
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
585
+ const authorization = kind ? `${kind} ${key}` : key;
586
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
587
+ }));
588
+
589
+ // src/services/event-logger.ts
590
+ import * as Context3 from "effect/Context";
591
+ import * as Effect7 from "effect/Effect";
592
+ import * as Layer3 from "effect/Layer";
593
+ import * as Schema9 from "effect/Schema";
594
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
595
+ import { invariant } from "@dxos/invariant";
596
+ import { LogLevel, log as log2 } from "@dxos/log";
597
+
598
+ // src/services/tracing.ts
599
+ import * as Context2 from "effect/Context";
600
+ import * as Effect6 from "effect/Effect";
601
+ import * as Layer2 from "effect/Layer";
602
+ import { AgentStatus } from "@dxos/ai";
603
+ import { Obj as Obj6 } from "@dxos/echo";
604
+ import { Message } from "@dxos/types";
605
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
606
+ static noop = {
607
+ getTraceContext: () => ({}),
608
+ write: () => {
609
+ }
610
+ };
611
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
612
+ /**
613
+ * Creates a TracingService layer that emits events to the parent tracing service.
614
+ */
615
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
616
+ const tracing = yield* _TracingService;
617
+ const context = mapContext(tracing.getTraceContext());
618
+ return {
619
+ write: (event) => tracing.write(event),
620
+ getTraceContext: () => context
621
+ };
622
+ }));
623
+ /**
624
+ * Emit the current human-readable execution status.
625
+ */
626
+ static emitStatus = Effect6.fnUntraced(function* (data) {
627
+ const tracing = yield* _TracingService;
628
+ tracing.write(Obj6.make(AgentStatus, {
629
+ parentMessage: tracing.getTraceContext().parentMessage,
630
+ toolCallId: tracing.getTraceContext().toolCallId,
631
+ created: (/* @__PURE__ */ new Date()).toISOString(),
632
+ ...data
633
+ }));
634
+ });
635
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
636
+ const tracing = yield* _TracingService;
637
+ tracing.write(Obj6.make(Message.Message, {
638
+ parentMessage: tracing.getTraceContext().parentMessage,
639
+ ...data,
640
+ properties: {
641
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
642
+ ...data.properties
643
+ }
644
+ }));
645
+ });
646
+ };
647
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
648
+
649
+ // src/services/event-logger.ts
650
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
651
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
652
+ type: Schema9.Literal("begin-compute"),
653
+ nodeId: Schema9.String,
654
+ /**
655
+ * Names of the inputs begin computed.
656
+ */
657
+ inputs: Schema9.Array(Schema9.String)
658
+ }), Schema9.Struct({
659
+ type: Schema9.Literal("end-compute"),
660
+ nodeId: Schema9.String,
661
+ /**
662
+ * Names of the outputs computed.
663
+ */
664
+ outputs: Schema9.Array(Schema9.String)
665
+ }), Schema9.Struct({
666
+ type: Schema9.Literal("compute-input"),
667
+ nodeId: Schema9.String,
668
+ property: Schema9.String,
669
+ value: Schema9.Any
670
+ }), Schema9.Struct({
671
+ type: Schema9.Literal("compute-output"),
672
+ nodeId: Schema9.String,
673
+ property: Schema9.String,
674
+ value: Schema9.Any
675
+ }), Schema9.Struct({
676
+ type: Schema9.Literal("custom"),
677
+ nodeId: Schema9.String,
678
+ event: Schema9.Any
679
+ }));
680
+ var ComputeEvent = Schema9.Struct({
681
+ payload: ComputeEventPayload
682
+ }).pipe(Type6.Obj({
683
+ typename: "dxos.org/type/ComputeEvent",
684
+ version: "0.1.0"
685
+ }));
686
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
687
+ static noop = {
688
+ log: () => {
689
+ },
690
+ nodeId: void 0
691
+ };
692
+ /**
693
+ * Implements ComputeEventLogger using TracingService.
694
+ */
695
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
696
+ const tracing = yield* TracingService;
697
+ return {
698
+ log: (event) => {
699
+ tracing.write(Obj7.make(ComputeEvent, {
700
+ payload: event
701
+ }));
702
+ },
703
+ nodeId: void 0
704
+ };
705
+ }));
706
+ };
707
+ var logCustomEvent = (data) => Effect7.gen(function* () {
708
+ const logger = yield* ComputeEventLogger;
709
+ if (!logger.nodeId) {
710
+ throw new Error("logCustomEvent must be called within a node compute function");
711
+ }
712
+ logger.log({
713
+ type: "custom",
714
+ nodeId: logger.nodeId,
715
+ event: data
716
+ });
717
+ });
718
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
719
+ log2.error("unhandled effect error", {
720
+ error
721
+ }, {
722
+ F: __dxlog_file,
723
+ L: 102,
724
+ S: this,
725
+ C: (f, a) => f(...a)
726
+ });
727
+ throw error;
728
+ }));
729
+ var createEventLogger = (level, message = "event") => {
730
+ const logFunction = {
731
+ [LogLevel.WARN]: log2.warn,
732
+ [LogLevel.VERBOSE]: log2.verbose,
733
+ [LogLevel.DEBUG]: log2.debug,
734
+ [LogLevel.INFO]: log2.info,
735
+ [LogLevel.ERROR]: log2.error
736
+ }[level];
737
+ invariant(logFunction, void 0, {
738
+ F: __dxlog_file,
739
+ L: 120,
740
+ S: void 0,
741
+ A: [
742
+ "logFunction",
743
+ ""
744
+ ]
745
+ });
746
+ return {
747
+ log: (event) => {
748
+ logFunction(message, event);
749
+ },
750
+ nodeId: void 0
751
+ };
752
+ };
753
+
754
+ // src/services/function-invocation-service.ts
755
+ import * as Context4 from "effect/Context";
756
+ import * as Effect8 from "effect/Effect";
757
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
758
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
759
+ };
760
+
761
+ // src/services/queues.ts
762
+ import * as Context5 from "effect/Context";
763
+ import * as Effect9 from "effect/Effect";
764
+ import * as Layer4 from "effect/Layer";
765
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
766
+ static notAvailable = Layer4.succeed(_QueueService, {
767
+ queues: {
768
+ get(_dxn) {
769
+ throw new Error("Queues not available");
770
+ },
771
+ create() {
772
+ throw new Error("Queues not available");
773
+ }
774
+ },
775
+ queue: void 0
776
+ });
777
+ static make = (queues, queue) => {
778
+ return {
779
+ queues,
780
+ queue
781
+ };
782
+ };
783
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
784
+ /**
785
+ * Gets a queue by its DXN.
786
+ */
787
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
788
+ /**
789
+ * Creates a new queue.
790
+ */
791
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
792
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
793
+ };
794
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
795
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
796
+ queue
797
+ });
798
+ };
799
+
800
+ // src/protocol/protocol.ts
801
+ import * as Effect10 from "effect/Effect";
802
+ import * as Layer5 from "effect/Layer";
803
+ import * as Schema10 from "effect/Schema";
804
+ import * as SchemaAST2 from "effect/SchemaAST";
805
+ import { AiService } from "@dxos/ai";
806
+ import { LifecycleState, Resource } from "@dxos/context";
807
+ import { Type as Type7 } from "@dxos/echo";
808
+ import { EchoClient } from "@dxos/echo-db";
809
+ import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
810
+ import { PublicKey } from "@dxos/keys";
811
+ function _ts_add_disposable_resource(env, value2, async) {
812
+ if (value2 !== null && value2 !== void 0) {
813
+ if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
814
+ var dispose, inner;
815
+ if (async) {
816
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
817
+ dispose = value2[Symbol.asyncDispose];
818
+ }
819
+ if (dispose === void 0) {
820
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
821
+ dispose = value2[Symbol.dispose];
822
+ if (async) inner = dispose;
823
+ }
824
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
825
+ if (inner) dispose = function() {
826
+ try {
827
+ inner.call(this);
828
+ } catch (e) {
829
+ return Promise.reject(e);
830
+ }
831
+ };
832
+ env.stack.push({
833
+ value: value2,
834
+ dispose,
835
+ async
836
+ });
837
+ } else if (async) {
838
+ env.stack.push({
839
+ async: true
840
+ });
841
+ }
842
+ return value2;
843
+ }
844
+ function _ts_dispose_resources(env) {
845
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
846
+ var e = new Error(message);
847
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
848
+ };
849
+ return (_ts_dispose_resources = function _ts_dispose_resources2(env2) {
850
+ function fail(e) {
851
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
852
+ env2.hasError = true;
853
+ }
854
+ var r, s = 0;
855
+ function next() {
856
+ while (r = env2.stack.pop()) {
857
+ try {
858
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
859
+ if (r.dispose) {
860
+ var result = r.dispose.call(r.value);
861
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
862
+ fail(e);
863
+ return next();
864
+ });
865
+ } else s |= 1;
866
+ } catch (e) {
867
+ fail(e);
868
+ }
869
+ }
870
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
871
+ if (env2.hasError) throw env2.error;
872
+ }
873
+ return next();
874
+ })(env);
875
+ }
876
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
877
+ var wrapFunctionHandler = (func) => {
878
+ if (!FunctionDefinition.isFunction(func)) {
879
+ throw new TypeError("Invalid function definition");
880
+ }
881
+ return {
882
+ meta: {
883
+ key: func.key,
884
+ name: func.name,
885
+ description: func.description,
886
+ inputSchema: Type7.toJsonSchema(func.inputSchema),
887
+ outputSchema: func.outputSchema === void 0 ? void 0 : Type7.toJsonSchema(func.outputSchema),
888
+ services: func.services
889
+ },
890
+ handler: async ({ data, context }) => {
891
+ if ((func.services.includes(DatabaseService2.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
892
+ throw new FunctionError({
893
+ message: "Services not provided: dataService, queryService"
894
+ });
895
+ }
896
+ try {
897
+ const env = {
898
+ stack: [],
899
+ error: void 0,
900
+ hasError: false
901
+ };
902
+ try {
903
+ if (!SchemaAST2.isAnyKeyword(func.inputSchema.ast)) {
904
+ try {
905
+ Schema10.validateSync(func.inputSchema)(data);
906
+ } catch (error) {
907
+ throw new FunctionError({
908
+ message: "Invalid input schema",
909
+ cause: error
910
+ });
911
+ }
912
+ }
913
+ const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
914
+ if (func.types.length > 0) {
915
+ invariant2(funcContext.db, "Database is required for functions with types", {
916
+ F: __dxlog_file2,
917
+ L: 63,
918
+ S: void 0,
919
+ A: [
920
+ "funcContext.db",
921
+ "'Database is required for functions with types'"
922
+ ]
923
+ });
924
+ funcContext.db.graph.schemaRegistry.addSchema(func.types);
925
+ }
926
+ let result = await func.handler({
927
+ // TODO(dmaretskyi): Fix the types.
928
+ context,
929
+ data
930
+ });
931
+ if (Effect10.isEffect(result)) {
932
+ result = await Effect10.runPromise(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
933
+ }
934
+ if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
935
+ Schema10.validateSync(func.outputSchema)(result);
936
+ }
937
+ return result;
938
+ } catch (e) {
939
+ env.error = e;
940
+ env.hasError = true;
941
+ } finally {
942
+ const result = _ts_dispose_resources(env);
943
+ if (result) await result;
944
+ }
945
+ } catch (error) {
946
+ throw error;
947
+ }
948
+ }
949
+ };
950
+ };
951
+ var FunctionContext = class extends Resource {
952
+ context;
953
+ client;
954
+ db;
955
+ queues;
956
+ constructor(context) {
957
+ super();
958
+ this.context = context;
959
+ if (context.services.dataService && context.services.queryService) {
960
+ this.client = new EchoClient().connectToService({
961
+ dataService: context.services.dataService,
962
+ queryService: context.services.queryService,
963
+ queueService: context.services.queueService
964
+ });
965
+ }
966
+ }
967
+ async _open() {
968
+ await this.client?.open();
969
+ this.db = this.client && this.context.spaceId ? this.client.constructDatabase({
970
+ spaceId: this.context.spaceId ?? failedInvariant2(),
971
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
972
+ reactiveSchemaQuery: false
973
+ }) : void 0;
974
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context"));
975
+ await this.db?.open();
976
+ this.queues = this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : void 0;
977
+ }
978
+ async _close() {
979
+ await this.db?.close();
980
+ await this.client?.close();
981
+ }
982
+ createLayer() {
983
+ assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
984
+ const dbLayer = this.db ? DatabaseService2.layer(this.db) : DatabaseService2.notAvailable;
985
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
986
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
987
+ const functionInvocationService = MockedFunctionInvocationService;
988
+ const aiService = AiService.notAvailable;
989
+ const tracing = TracingService.layerNoop;
990
+ return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
991
+ }
992
+ };
993
+ var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
994
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
995
+ });
1335
996
  export {
1336
997
  ComputeEvent,
1337
998
  ComputeEventLogger,
@@ -1339,58 +1000,32 @@ export {
1339
1000
  ConfiguredCredentialsService,
1340
1001
  ContextQueueService,
1341
1002
  CredentialsService,
1342
- DatabaseService,
1343
- EmailTriggerOutput,
1003
+ DatabaseService2 as DatabaseService,
1004
+ Example,
1344
1005
  FUNCTIONS_META_KEY,
1345
1006
  FUNCTIONS_PRESET_META_KEY,
1346
- FUNCTION_TYPES,
1007
+ Function_exports as Function,
1347
1008
  FunctionDefinition,
1348
1009
  FunctionError,
1349
- FunctionExecutor,
1350
- FunctionImplementationResolver,
1351
1010
  FunctionInvocationService,
1352
- FunctionManifestSchema,
1353
1011
  FunctionNotFoundError,
1354
- FunctionTrigger,
1355
- FunctionType,
1356
- InvocationOutcome,
1357
- InvocationTraceEndEvent,
1358
- InvocationTraceEventType,
1359
- InvocationTraceStartEvent,
1360
- InvocationTracer,
1361
- LocalFunctionExecutionService,
1362
1012
  MESSAGE_PROPERTY_TOOL_CALL_ID,
1363
1013
  QueueService,
1364
- QueueTriggerOutput,
1365
- RemoteFunctionExecutionService,
1366
- SERVICE_TAGS,
1367
- ScriptType,
1368
- ServiceContainer,
1014
+ Script_exports as Script,
1369
1015
  ServiceNotAvailableError,
1370
- SubscriptionTriggerOutput,
1371
- TimerTriggerOutput,
1372
- TraceEvent,
1373
- TraceEventException,
1374
- TraceEventLog,
1375
1016
  TracingService,
1376
- TriggerDispatcher,
1377
- TriggerKinds,
1378
- TriggerSchema,
1379
- TriggerState,
1017
+ Trigger_exports as Trigger,
1018
+ TriggerEvent_exports as TriggerEvent,
1380
1019
  TriggerStateNotFoundError,
1381
- TriggerStateStore,
1382
- WebhookTriggerOutput,
1383
1020
  createDefectLogger,
1384
1021
  createEventLogger,
1385
- createInvocationSpans,
1386
1022
  defineFunction,
1387
1023
  deserializeFunction,
1388
- examples_exports as exampleFunctions,
1389
- getInvocationUrl,
1390
1024
  getUserFunctionIdInMetadata,
1391
1025
  logCustomEvent,
1392
1026
  serializeFunction,
1393
1027
  setUserFunctionIdInMetadata,
1394
- withAuthorization
1028
+ withAuthorization,
1029
+ wrapFunctionHandler
1395
1030
  };
1396
1031
  //# sourceMappingURL=index.mjs.map