@dxos/functions 0.8.4-main.ae835ea → 0.8.4-main.bc674ce

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