@dxos/functions 0.8.4-main.67995b8 → 0.8.4-main.69d29f4

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