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