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