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