@dxos/functions 0.8.4-main.1da679c → 0.8.4-main.21d9917

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