@dxos/functions 0.8.4-main.84f28bd → 0.8.4-main.937b3ca

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 (161) hide show
  1. package/dist/lib/browser/index.mjs +1100 -363
  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 +1100 -363
  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 +121 -0
  8. package/dist/types/src/errors.d.ts.map +1 -0
  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 -6
  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 +23 -3
  34. package/dist/types/src/services/credentials.d.ts.map +1 -1
  35. package/dist/types/src/services/event-logger.d.ts +74 -30
  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 -7
  40. package/dist/types/src/services/index.d.ts.map +1 -1
  41. package/dist/types/src/services/queues.d.ts +33 -4
  42. package/dist/types/src/services/queues.d.ts.map +1 -1
  43. package/dist/types/src/services/tracing.d.ts +78 -5
  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 +26 -66
  59. package/src/errors.ts +21 -0
  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 -8
  66. package/src/operation-compatibility.test.ts +185 -0
  67. package/src/protocol/functions-ai-http-client.ts +67 -0
  68. package/src/{executor → protocol}/index.ts +1 -1
  69. package/src/protocol/protocol.test.ts +59 -0
  70. package/src/protocol/protocol.ts +262 -0
  71. package/src/sdk.ts +289 -0
  72. package/src/services/credentials.ts +108 -4
  73. package/src/services/event-logger.ts +77 -37
  74. package/src/services/function-invocation-service.ts +37 -0
  75. package/src/services/index.ts +5 -7
  76. package/src/services/queues.ts +48 -8
  77. package/src/services/tracing.ts +151 -11
  78. package/src/types/Function.ts +82 -0
  79. package/src/types/Script.ts +34 -0
  80. package/src/types/Trigger.ts +143 -0
  81. package/src/types/TriggerEvent.ts +68 -0
  82. package/src/types/index.ts +9 -0
  83. package/src/types/url.ts +32 -0
  84. package/dist/lib/browser/bundler/index.mjs +0 -247
  85. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  86. package/dist/lib/browser/chunk-54U464M4.mjs +0 -360
  87. package/dist/lib/browser/chunk-54U464M4.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 -79
  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-XDSX35BS.mjs +0 -362
  95. package/dist/lib/node-esm/chunk-XDSX35BS.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 -80
  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 -61
  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/ai.d.ts +0 -12
  119. package/dist/types/src/services/ai.d.ts.map +0 -1
  120. package/dist/types/src/services/database.d.ts +0 -15
  121. package/dist/types/src/services/database.d.ts.map +0 -1
  122. package/dist/types/src/services/function-call-service.d.ts +0 -16
  123. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  124. package/dist/types/src/services/service-container.d.ts +0 -46
  125. package/dist/types/src/services/service-container.d.ts.map +0 -1
  126. package/dist/types/src/services/tool-resolver.d.ts +0 -14
  127. package/dist/types/src/services/tool-resolver.d.ts.map +0 -1
  128. package/dist/types/src/testing/index.d.ts +0 -2
  129. package/dist/types/src/testing/index.d.ts.map +0 -1
  130. package/dist/types/src/testing/logger.d.ts +0 -5
  131. package/dist/types/src/testing/logger.d.ts.map +0 -1
  132. package/dist/types/src/testing/services.d.ts +0 -71
  133. package/dist/types/src/testing/services.d.ts.map +0 -1
  134. package/dist/types/src/trace.d.ts +0 -124
  135. package/dist/types/src/trace.d.ts.map +0 -1
  136. package/dist/types/src/translations.d.ts +0 -12
  137. package/dist/types/src/translations.d.ts.map +0 -1
  138. package/dist/types/src/types.d.ts +0 -411
  139. package/dist/types/src/types.d.ts.map +0 -1
  140. package/dist/types/src/url.d.ts +0 -17
  141. package/dist/types/src/url.d.ts.map +0 -1
  142. package/src/bundler/bundler.test.ts +0 -59
  143. package/src/bundler/bundler.ts +0 -292
  144. package/src/bundler/index.ts +0 -5
  145. package/src/edge/functions.ts +0 -64
  146. package/src/edge/index.ts +0 -9
  147. package/src/executor/executor.ts +0 -54
  148. package/src/handler.ts +0 -113
  149. package/src/schema.ts +0 -57
  150. package/src/services/ai.ts +0 -32
  151. package/src/services/database.ts +0 -50
  152. package/src/services/function-call-service.ts +0 -64
  153. package/src/services/service-container.ts +0 -127
  154. package/src/services/tool-resolver.ts +0 -31
  155. package/src/testing/index.ts +0 -5
  156. package/src/testing/logger.ts +0 -16
  157. package/src/testing/services.ts +0 -174
  158. package/src/trace.ts +0 -180
  159. package/src/translations.ts +0 -20
  160. package/src/types.ts +0 -211
  161. package/src/url.ts +0 -52
@@ -1,98 +1,197 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- AiService,
4
- ConfiguredCredentialsService,
5
- CredentialsService,
6
- DatabaseService,
7
- EventLogger,
8
- FunctionCallService,
9
- QueueService,
10
- SERVICE_TAGS,
11
- ServiceContainer,
12
- ToolResolverService,
13
- TracingService,
14
- createDefectLogger,
15
- createEventLogger,
16
- logCustomEvent
17
- } from "./chunk-XDSX35BS.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
+ };
18
7
 
19
- // src/handler.ts
20
- import { Schema } from "effect";
21
- var defineFunction = (params) => {
22
- if (!Schema.isSchema(params.inputSchema)) {
23
- 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
+ });
24
18
  }
25
- if (typeof params.handler !== "function") {
26
- 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
+ });
27
28
  }
28
- return {
29
- description: params.description,
30
- inputSchema: params.inputSchema,
31
- outputSchema: params.outputSchema ?? Schema.Any,
32
- handler: params.handler
33
- };
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") {
34
33
  };
35
34
 
36
- // src/schema.ts
37
- import { Schema as Schema2 } from "effect";
38
- import { Type } from "@dxos/echo";
39
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
40
- import { DataType } from "@dxos/schema";
41
- var ScriptType = Schema2.Struct({
42
- name: Schema2.optional(Schema2.String),
43
- 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),
44
70
  // TODO(burdon): Change to hash of deployed content.
45
71
  // Whether source has changed since last deploy.
46
- changed: Schema2.optional(Schema2.Boolean),
47
- source: Ref(DataType.Text)
48
- }).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({
49
75
  typename: "dxos.org/type/Script",
50
76
  version: "0.1.0"
51
- }), LabelAnnotation.set([
77
+ }), Annotation.LabelAnnotation.set([
52
78
  "name"
53
79
  ]));
54
- var FunctionType = Schema2.Struct({
55
- // 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
+ }),
56
97
  name: Schema2.NonEmptyString,
57
98
  version: Schema2.String,
58
99
  description: Schema2.optional(Schema2.String),
100
+ /**
101
+ * ISO date string of the last deployment.
102
+ */
103
+ updated: Schema2.optional(Schema2.String),
59
104
  // Reference to a source script if it exists within ECHO.
60
105
  // TODO(burdon): Don't ref ScriptType directly (core).
61
- source: Schema2.optional(Ref(ScriptType)),
62
- inputSchema: Schema2.optional(JsonSchemaType),
63
- 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)),
64
114
  // Local binding to a function name.
65
115
  binding: Schema2.optional(Schema2.String)
66
- }).pipe(Type.Obj({
116
+ }).pipe(Type2.object({
67
117
  typename: "dxos.org/type/Function",
68
118
  version: "0.1.0"
69
- }), LabelAnnotation.set([
119
+ }), Annotation2.LabelAnnotation.set([
70
120
  "name"
71
- ]));
72
-
73
- // src/trace.ts
74
- import { Schema as Schema4 } from "effect";
75
- import { Type as Type2 } from "@dxos/echo";
76
- import { Queue } from "@dxos/echo-db";
77
- import { ObjectId } from "@dxos/echo-schema";
78
- 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
+ };
79
135
 
80
- // src/types.ts
81
- import { Schema as Schema3, SchemaAST } from "effect";
82
- 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";
83
153
  import { DXN } from "@dxos/keys";
84
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
85
- TriggerKind2["Timer"] = "timer";
86
- TriggerKind2["Webhook"] = "webhook";
87
- TriggerKind2["Subscription"] = "subscription";
88
- TriggerKind2["Email"] = "email";
89
- TriggerKind2["Queue"] = "queue";
90
- return TriggerKind2;
91
- }({});
154
+ import { Expando } from "@dxos/schema";
155
+ var Kinds = [
156
+ "email",
157
+ "queue",
158
+ "subscription",
159
+ "timer",
160
+ "webhook"
161
+ ];
92
162
  var kindLiteralAnnotations = {
93
163
  title: "Kind"
94
164
  };
95
- var TimerTriggerSchema = Schema3.Struct({
165
+ var EmailSpec = Schema3.Struct({
166
+ kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
167
+ }).pipe(Schema3.mutable);
168
+ var QueueSpec = Schema3.Struct({
169
+ kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
170
+ // TODO(dmaretskyi): Change to a reference.
171
+ queue: DXN.Schema
172
+ }).pipe(Schema3.mutable);
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
+ }).pipe(Schema3.mutable),
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
+ }).pipe(Schema3.mutable);
194
+ var TimerSpec = Schema3.Struct({
96
195
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
97
196
  cron: Schema3.String.annotations({
98
197
  title: "Cron",
@@ -101,14 +200,7 @@ var TimerTriggerSchema = Schema3.Struct({
101
200
  ]
102
201
  })
103
202
  }).pipe(Schema3.mutable);
104
- var EmailTriggerSchema = Schema3.Struct({
105
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
106
- }).pipe(Schema3.mutable);
107
- var QueueTriggerSchema = Schema3.Struct({
108
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
109
- queue: DXN.Schema
110
- }).pipe(Schema3.mutable);
111
- var WebhookTriggerSchema = Schema3.Struct({
203
+ var WebhookSpec = Schema3.Struct({
112
204
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
113
205
  method: Schema3.optional(Schema3.String.annotations({
114
206
  title: "Method",
@@ -121,71 +213,15 @@ var WebhookTriggerSchema = Schema3.Struct({
121
213
  title: "Port"
122
214
  }))
123
215
  }).pipe(Schema3.mutable);
124
- var QuerySchema = Schema3.Struct({
125
- type: Schema3.optional(Schema3.String.annotations({
126
- title: "Type"
127
- })),
128
- props: Schema3.optional(Schema3.Record({
129
- key: Schema3.String,
130
- value: Schema3.Any
131
- }))
132
- }).annotations({
133
- title: "Query"
134
- });
135
- var SubscriptionTriggerSchema = Schema3.Struct({
136
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
137
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
138
- filter: QuerySchema,
139
- options: Schema3.optional(Schema3.Struct({
140
- // Watch changes to object (not just creation).
141
- deep: Schema3.optional(Schema3.Boolean.annotations({
142
- title: "Nested"
143
- })),
144
- // Debounce changes (delay in ms).
145
- delay: Schema3.optional(Schema3.Number.annotations({
146
- title: "Delay"
147
- }))
148
- }).annotations({
149
- title: "Options"
150
- }))
151
- }).pipe(Schema3.mutable);
152
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
216
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
153
217
  title: "Trigger"
154
218
  });
155
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
156
- from: Schema3.String,
157
- to: Schema3.String,
158
- subject: Schema3.String,
159
- created: Schema3.String,
160
- body: Schema3.String
161
- }));
162
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
163
- url: Schema3.String,
164
- method: Schema3.Literal("GET", "POST"),
165
- headers: Schema3.Record({
166
- key: Schema3.String,
167
- value: Schema3.String
168
- }),
169
- bodyText: Schema3.String
170
- }));
171
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
172
- queue: DXN.Schema,
173
- item: Schema3.Any,
174
- cursor: Schema3.String
175
- }));
176
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
177
- type: Schema3.String,
178
- changedObjectId: Schema3.String
179
- }));
180
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
181
- tick: Schema3.Number
182
- }));
183
- var FunctionTriggerSchema = Schema3.Struct({
219
+ var TriggerSchema = Schema3.Struct({
184
220
  /**
185
221
  * Function or workflow to invoke.
186
222
  */
187
223
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
188
- function: Schema3.optional(Ref2(Expando).annotations({
224
+ function: Schema3.optional(Type3.Ref(Expando.Expando).annotations({
189
225
  title: "Function"
190
226
  })),
191
227
  /**
@@ -196,10 +232,12 @@ var FunctionTriggerSchema = Schema3.Struct({
196
232
  inputNodeId: Schema3.optional(Schema3.String.annotations({
197
233
  title: "Input Node ID"
198
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.
199
237
  enabled: Schema3.optional(Schema3.Boolean.annotations({
200
238
  title: "Enabled"
201
239
  })),
202
- spec: Schema3.optional(TriggerSchema),
240
+ spec: Schema3.optional(Spec),
203
241
  /**
204
242
  * Passed as the input data to the function.
205
243
  * Must match the function's input schema.
@@ -215,279 +253,978 @@ var FunctionTriggerSchema = Schema3.Struct({
215
253
  key: Schema3.String,
216
254
  value: Schema3.Any
217
255
  })))
218
- });
219
- var FunctionTrigger = class extends TypedObject({
220
- typename: "dxos.org/type/FunctionTrigger",
221
- version: "0.2.0"
222
- })(FunctionTriggerSchema.fields) {
223
- };
224
- var FunctionManifestSchema = Schema3.Struct({
225
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
226
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
227
- });
228
- var FUNCTION_TYPES = [
229
- FunctionType,
230
- FunctionTrigger
231
- ];
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);
232
262
 
233
- // src/trace.ts
234
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
235
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
236
- InvocationOutcome2["SUCCESS"] = "success";
237
- InvocationOutcome2["FAILURE"] = "failure";
238
- InvocationOutcome2["PENDING"] = "pending";
239
- return InvocationOutcome2;
240
- }({});
241
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
242
- InvocationTraceEventType2["START"] = "start";
243
- InvocationTraceEventType2["END"] = "end";
244
- return InvocationTraceEventType2;
245
- }({});
246
- var TraceEventException = Schema4.Struct({
247
- timestampMs: Schema4.Number,
248
- message: Schema4.String,
249
- name: Schema4.String,
250
- stack: Schema4.optional(Schema4.String)
263
+ // src/types/TriggerEvent.ts
264
+ var TriggerEvent_exports = {};
265
+ __export(TriggerEvent_exports, {
266
+ EmailEvent: () => EmailEvent,
267
+ QueueEvent: () => QueueEvent,
268
+ SubscriptionEvent: () => SubscriptionEvent,
269
+ TimerEvent: () => TimerEvent,
270
+ TriggerEvent: () => TriggerEvent,
271
+ WebhookEvent: () => WebhookEvent
251
272
  });
252
- var InvocationTraceStartEvent = Schema4.Struct({
273
+ import * as Schema4 from "effect/Schema";
274
+ import { DXN as DXN2, Type as Type4 } from "@dxos/echo";
275
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
276
+ from: Schema4.String,
277
+ to: Schema4.String,
278
+ subject: Schema4.String,
279
+ created: Schema4.String,
280
+ body: Schema4.String
281
+ }));
282
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
283
+ queue: DXN2.Schema,
284
+ item: Schema4.Any,
285
+ cursor: Schema4.String
286
+ }));
287
+ var SubscriptionEvent = Schema4.Struct({
253
288
  /**
254
- * Queue message id.
289
+ * Type of the mutation.
255
290
  */
256
- id: ObjectId,
257
- type: Schema4.Literal("start"),
291
+ // TODO(dmaretskyi): Specify enum.
292
+ type: Schema4.String,
258
293
  /**
259
- * Invocation id, the same for invocation start and end events.
294
+ * Reference to the object that was changed or created.
260
295
  */
261
- invocationId: ObjectId,
296
+ subject: Type4.Ref(Type4.Obj),
262
297
  /**
263
- * Event generation time.
298
+ * @deprecated
264
299
  */
265
- timestampMs: Schema4.Number,
300
+ changedObjectId: Schema4.optional(Schema4.String)
301
+ }).pipe(Schema4.mutable);
302
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
303
+ tick: Schema4.Number
304
+ }));
305
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
306
+ url: Schema4.String,
307
+ method: Schema4.Literal("GET", "POST"),
308
+ headers: Schema4.Record({
309
+ key: Schema4.String,
310
+ value: Schema4.String
311
+ }),
312
+ bodyText: Schema4.String
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);
266
662
  /**
267
- * Data passed to function / workflow as an argument.
663
+ * Creates a TracingService layer that emits events to the parent tracing service.
268
664
  */
269
- // TODO(burdon): Input schema?
270
- 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
+ }));
271
675
  /**
272
- * Queue for function/workflow invocation events.
676
+ * Create sublayer to trace an invocation.
677
+ * @param data
678
+ * @returns
273
679
  */
274
- invocationTraceQueue: Type2.Ref(Queue),
680
+ static layerInvocation = (data) => _TracingService.layerSubframe((context) => ({
681
+ ...context,
682
+ currentInvocation: data
683
+ }));
275
684
  /**
276
- * DXN of the invoked function/workflow.
685
+ * Emit the current human-readable execution status.
277
686
  */
278
- 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,
279
715
  /**
280
- * Present for automatic invocations.
281
- */
282
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
283
- }).pipe(Type2.Obj({
284
- 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",
285
745
  version: "0.1.0"
286
746
  }));
287
- var InvocationTraceEndEvent = Schema4.Struct({
747
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
748
+ static noop = {
749
+ log: () => {
750
+ },
751
+ nodeId: void 0
752
+ };
288
753
  /**
289
- * Trace event id.
754
+ * Implements ComputeEventLogger using TracingService.
290
755
  */
291
- id: ObjectId,
292
- type: Schema4.Literal("end"),
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));
293
851
  /**
294
- * Invocation id, will be the same for invocation start and end.
852
+ * Gets a queue by its DXN.
295
853
  */
296
- invocationId: ObjectId,
854
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
297
855
  /**
298
- * Event generation time.
856
+ * Creates a new queue.
299
857
  */
300
- // TODO(burdon): Remove ms suffix.
301
- timestampMs: Schema4.Number,
302
- outcome: Schema4.Enums(InvocationOutcome),
303
- exception: Schema4.optional(TraceEventException)
304
- }).pipe(Type2.Obj({
305
- typename: "dxos.org/type/InvocationTraceEnd",
306
- version: "0.1.0"
307
- }));
308
- var TraceEventLog = Schema4.Struct({
309
- timestampMs: Schema4.Number,
310
- level: Schema4.String,
311
- message: Schema4.String,
312
- context: Schema4.optional(Schema4.Object)
313
- });
314
- var TraceEvent = Schema4.Struct({
315
- id: ObjectId,
316
- // TODO(burdon): Need enum/numeric result (not string).
317
- outcome: Schema4.String,
318
- truncated: Schema4.Boolean,
319
- /**
320
- * Time when the event was persisted.
321
- */
322
- ingestionTimestampMs: Schema4.Number,
323
- logs: Schema4.Array(TraceEventLog),
324
- exceptions: Schema4.Array(TraceEventException)
325
- }).pipe(Type2.Obj({
326
- typename: "dxos.org/type/TraceEvent",
327
- version: "0.1.0"
328
- }));
329
- var createInvocationSpans = (items) => {
330
- if (!items) {
331
- return [];
332
- }
333
- const eventsByInvocationId = /* @__PURE__ */ new Map();
334
- for (const event of items) {
335
- if (!("invocationId" in event)) {
336
- 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));
337
932
  }
338
- const invocationId = event.invocationId;
339
- const entry = eventsByInvocationId.get(invocationId) || {
340
- start: void 0,
341
- end: void 0
342
- };
343
- if (event.type === "start") {
344
- entry.start = event;
345
- } else if (event.type === "end") {
346
- 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];
347
946
  }
348
- eventsByInvocationId.set(invocationId, entry);
349
- }
350
- const now = Date.now();
351
- const result = [];
352
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
353
- if (!start) {
354
- log.warn("found end event without matching start", {
355
- invocationId
356
- }, {
357
- F: __dxlog_file,
358
- L: 160,
359
- S: void 0,
360
- C: (f, a) => f(...a)
361
- });
362
- 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;
363
951
  }
364
- const isInProgress = end === void 0;
365
- result.push({
366
- id: invocationId,
367
- timestampMs: start.timestampMs,
368
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
369
- outcome: end?.outcome ?? "pending",
370
- exception: end?.exception,
371
- input: start.input,
372
- invocationTraceQueue: start.invocationTraceQueue,
373
- invocationTarget: start.invocationTarget,
374
- 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
375
968
  });
376
969
  }
377
- return result;
378
- };
379
-
380
- // src/url.ts
381
- var FUNCTIONS_META_KEY = "dxos.org/service/function";
382
- var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
383
- var isSecure = (protocol) => {
384
- return protocol === "https:" || protocol === "wss:";
385
- };
386
- var getUserFunctionUrlInMetadata = (meta) => {
387
- return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
388
- };
389
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
390
- const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
391
- if (key) {
392
- if (key.id !== functionUrl) {
393
- 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;
394
981
  }
395
- } else {
396
- meta.keys.push({
397
- source: FUNCTIONS_META_KEY,
398
- id: functionUrl
399
- });
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");
400
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
+ };
401
1079
  };
402
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
403
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
404
- const baseUrl = new URL("functions/", edgeUrl);
405
- const relativeUrl = functionUrl.replace(/^\//, "");
406
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
407
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
408
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
409
- url.protocol = isSecure(url.protocol) ? "https" : "http";
410
- 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
+ }
411
1127
  };
412
-
413
- // src/executor/executor.ts
414
- import { Effect, Schema as Schema5 } from "effect";
415
- import { runAndForwardErrors } from "@dxos/effect";
416
- var FunctionExecutor = class {
417
- constructor(_services) {
418
- 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;
419
1135
  }
420
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
421
- async invoke(fnDef, input) {
422
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
423
- assertInput(input);
424
- const context = {
425
- getService: this._services.getService.bind(this._services),
426
- getSpace: async (_spaceId) => {
427
- throw new Error("Not available. Use the database service instead.");
428
- },
429
- space: void 0,
430
- get ai() {
431
- 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;
432
1155
  }
433
- };
434
- const result = fnDef.handler({
435
- context,
436
- data: input
437
- });
438
- let data;
439
- if (Effect.isEffect(result)) {
440
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
441
- } else {
442
- 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;
443
1192
  }
444
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
445
- assertOutput(data);
446
- return data;
447
1193
  }
448
1194
  };
449
1195
  export {
450
- AiService,
1196
+ ComputeEvent,
1197
+ ComputeEventLogger,
1198
+ ComputeEventPayload,
451
1199
  ConfiguredCredentialsService,
1200
+ ContextQueueService,
452
1201
  CredentialsService,
453
- DatabaseService,
454
- EmailTriggerOutput,
455
- EventLogger,
1202
+ Example,
1203
+ FUNCTIONS_META_KEY,
456
1204
  FUNCTIONS_PRESET_META_KEY,
457
- FUNCTION_TYPES,
458
- FunctionCallService,
459
- FunctionExecutor,
460
- FunctionManifestSchema,
461
- FunctionTrigger,
462
- FunctionTriggerSchema,
463
- FunctionType,
464
- InvocationOutcome,
465
- InvocationTraceEndEvent,
466
- InvocationTraceEventType,
467
- InvocationTraceStartEvent,
1205
+ Function_exports as Function,
1206
+ FunctionDefinition,
1207
+ FunctionError,
1208
+ FunctionInvocationService,
1209
+ FunctionNotFoundError,
1210
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
468
1211
  QueueService,
469
- QueueTriggerOutput,
470
- SERVICE_TAGS,
471
- ScriptType,
472
- ServiceContainer,
473
- SubscriptionTriggerOutput,
474
- TimerTriggerOutput,
475
- ToolResolverService,
476
- TraceEvent,
477
- TraceEventException,
478
- TraceEventLog,
1212
+ Script_exports as Script,
1213
+ ServiceNotAvailableError,
479
1214
  TracingService,
480
- TriggerKind,
481
- TriggerSchema,
482
- WebhookTriggerOutput,
1215
+ Trigger_exports as Trigger,
1216
+ TriggerEvent_exports as TriggerEvent,
1217
+ TriggerStateNotFoundError,
483
1218
  createDefectLogger,
484
1219
  createEventLogger,
485
- createInvocationSpans,
486
1220
  defineFunction,
487
- getInvocationUrl,
488
- getUserFunctionUrlInMetadata,
1221
+ deserializeFunction,
1222
+ getUserFunctionIdInMetadata,
489
1223
  logCustomEvent,
490
- makeFunctionUrl,
491
- setUserFunctionUrlInMetadata
1224
+ serializeFunction,
1225
+ setUserFunctionIdInMetadata,
1226
+ toOperation,
1227
+ withAuthorization,
1228
+ wrapFunctionHandler
492
1229
  };
493
1230
  //# sourceMappingURL=index.mjs.map