@dxos/functions 0.8.4-main.fd6878d → 0.8.4-main.fffef41

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 +788 -361
  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 +788 -361
  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 +87 -28
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +7 -0
  10. package/dist/types/src/example/fib.d.ts.map +1 -0
  11. package/dist/types/src/example/forex-effect.d.ts +3 -0
  12. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  13. package/dist/types/src/example/index.d.ts +12 -0
  14. package/dist/types/src/example/index.d.ts.map +1 -0
  15. package/dist/types/src/example/reply.d.ts +3 -0
  16. package/dist/types/src/example/reply.d.ts.map +1 -0
  17. package/dist/types/src/example/sleep.d.ts +5 -0
  18. package/dist/types/src/example/sleep.d.ts.map +1 -0
  19. package/dist/types/src/index.d.ts +5 -7
  20. package/dist/types/src/index.d.ts.map +1 -1
  21. package/dist/types/src/protocol/index.d.ts +2 -0
  22. package/dist/types/src/protocol/index.d.ts.map +1 -0
  23. package/dist/types/src/protocol/protocol.d.ts +7 -0
  24. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  25. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  26. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  27. package/dist/types/src/sdk.d.ts +89 -0
  28. package/dist/types/src/sdk.d.ts.map +1 -0
  29. package/dist/types/src/services/credentials.d.ts +17 -3
  30. package/dist/types/src/services/credentials.d.ts.map +1 -1
  31. package/dist/types/src/services/event-logger.d.ts +20 -5
  32. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  33. package/dist/types/src/services/function-invocation-service.d.ts +11 -0
  34. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  35. package/dist/types/src/services/index.d.ts +6 -6
  36. package/dist/types/src/services/index.d.ts.map +1 -1
  37. package/dist/types/src/services/queues.d.ts +4 -1
  38. package/dist/types/src/services/queues.d.ts.map +1 -1
  39. package/dist/types/src/services/tracing.d.ts +34 -6
  40. package/dist/types/src/services/tracing.d.ts.map +1 -1
  41. package/dist/types/src/types/Function.d.ts +58 -0
  42. package/dist/types/src/types/Function.d.ts.map +1 -0
  43. package/dist/types/src/types/Script.d.ts +28 -0
  44. package/dist/types/src/types/Script.d.ts.map +1 -0
  45. package/dist/types/src/types/Trigger.d.ts +139 -0
  46. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  47. package/dist/types/src/types/TriggerEvent.d.ts +44 -0
  48. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  49. package/dist/types/src/types/index.d.ts +6 -0
  50. package/dist/types/src/types/index.d.ts.map +1 -0
  51. package/dist/types/src/types/url.d.ts +12 -0
  52. package/dist/types/src/types/url.d.ts.map +1 -0
  53. package/dist/types/tsconfig.tsbuildinfo +1 -1
  54. package/package.json +18 -72
  55. package/src/errors.ts +13 -5
  56. package/src/example/fib.ts +32 -0
  57. package/src/example/forex-effect.ts +40 -0
  58. package/src/example/index.ts +13 -0
  59. package/src/example/reply.ts +21 -0
  60. package/src/example/sleep.ts +24 -0
  61. package/src/index.ts +5 -9
  62. package/src/{executor → protocol}/index.ts +1 -1
  63. package/src/protocol/protocol.test.ts +59 -0
  64. package/src/protocol/protocol.ts +145 -0
  65. package/src/sdk.ts +226 -0
  66. package/src/services/credentials.ts +51 -6
  67. package/src/services/event-logger.ts +12 -3
  68. package/src/services/function-invocation-service.ts +23 -0
  69. package/src/services/index.ts +7 -6
  70. package/src/services/queues.ts +8 -1
  71. package/src/services/tracing.ts +81 -17
  72. package/src/types/Function.ts +62 -0
  73. package/src/types/Script.ts +33 -0
  74. package/src/types/Trigger.ts +139 -0
  75. package/src/types/TriggerEvent.ts +62 -0
  76. package/src/types/index.ts +9 -0
  77. package/src/types/url.ts +31 -0
  78. package/dist/lib/browser/bundler/index.mjs +0 -248
  79. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  80. package/dist/lib/browser/chunk-M2OIFLGE.mjs +0 -486
  81. package/dist/lib/browser/chunk-M2OIFLGE.mjs.map +0 -7
  82. package/dist/lib/browser/edge/index.mjs +0 -69
  83. package/dist/lib/browser/edge/index.mjs.map +0 -7
  84. package/dist/lib/browser/testing/index.mjs +0 -59
  85. package/dist/lib/browser/testing/index.mjs.map +0 -7
  86. package/dist/lib/node-esm/bundler/index.mjs +0 -250
  87. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  88. package/dist/lib/node-esm/chunk-K7REX6H4.mjs +0 -488
  89. package/dist/lib/node-esm/chunk-K7REX6H4.mjs.map +0 -7
  90. package/dist/lib/node-esm/edge/index.mjs +0 -71
  91. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  92. package/dist/lib/node-esm/testing/index.mjs +0 -60
  93. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  94. package/dist/types/src/bundler/bundler.d.ts +0 -50
  95. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  96. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  97. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  98. package/dist/types/src/bundler/index.d.ts +0 -2
  99. package/dist/types/src/bundler/index.d.ts.map +0 -1
  100. package/dist/types/src/edge/functions.d.ts +0 -16
  101. package/dist/types/src/edge/functions.d.ts.map +0 -1
  102. package/dist/types/src/edge/index.d.ts +0 -2
  103. package/dist/types/src/edge/index.d.ts.map +0 -1
  104. package/dist/types/src/executor/executor.d.ts +0 -11
  105. package/dist/types/src/executor/executor.d.ts.map +0 -1
  106. package/dist/types/src/executor/index.d.ts +0 -2
  107. package/dist/types/src/executor/index.d.ts.map +0 -1
  108. package/dist/types/src/handler.d.ts +0 -65
  109. package/dist/types/src/handler.d.ts.map +0 -1
  110. package/dist/types/src/schema.d.ts +0 -38
  111. package/dist/types/src/schema.d.ts.map +0 -1
  112. package/dist/types/src/services/database.d.ts +0 -79
  113. package/dist/types/src/services/database.d.ts.map +0 -1
  114. package/dist/types/src/services/local-function-execution.d.ts +0 -12
  115. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  116. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -15
  117. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  118. package/dist/types/src/services/service-container.d.ts +0 -56
  119. package/dist/types/src/services/service-container.d.ts.map +0 -1
  120. package/dist/types/src/services/service-registry.d.ts +0 -29
  121. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  122. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  123. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  124. package/dist/types/src/testing/index.d.ts +0 -3
  125. package/dist/types/src/testing/index.d.ts.map +0 -1
  126. package/dist/types/src/testing/layer.d.ts +0 -10
  127. package/dist/types/src/testing/layer.d.ts.map +0 -1
  128. package/dist/types/src/testing/logger.d.ts +0 -5
  129. package/dist/types/src/testing/logger.d.ts.map +0 -1
  130. package/dist/types/src/testing/services.d.ts +0 -59
  131. package/dist/types/src/testing/services.d.ts.map +0 -1
  132. package/dist/types/src/trace.d.ts +0 -122
  133. package/dist/types/src/trace.d.ts.map +0 -1
  134. package/dist/types/src/translations.d.ts +0 -12
  135. package/dist/types/src/translations.d.ts.map +0 -1
  136. package/dist/types/src/types.d.ts +0 -411
  137. package/dist/types/src/types.d.ts.map +0 -1
  138. package/dist/types/src/url.d.ts +0 -17
  139. package/dist/types/src/url.d.ts.map +0 -1
  140. package/src/bundler/bundler.test.ts +0 -59
  141. package/src/bundler/bundler.ts +0 -292
  142. package/src/bundler/index.ts +0 -5
  143. package/src/edge/functions.ts +0 -64
  144. package/src/edge/index.ts +0 -9
  145. package/src/executor/executor.ts +0 -54
  146. package/src/handler.ts +0 -122
  147. package/src/schema.ts +0 -57
  148. package/src/services/database.ts +0 -116
  149. package/src/services/local-function-execution.ts +0 -74
  150. package/src/services/remote-function-execution-service.ts +0 -66
  151. package/src/services/service-container.ts +0 -114
  152. package/src/services/service-registry.test.ts +0 -42
  153. package/src/services/service-registry.ts +0 -59
  154. package/src/testing/index.ts +0 -6
  155. package/src/testing/layer.ts +0 -31
  156. package/src/testing/logger.ts +0 -16
  157. package/src/testing/services.ts +0 -115
  158. package/src/trace.ts +0 -178
  159. package/src/translations.ts +0 -20
  160. package/src/types.ts +0 -211
  161. package/src/url.ts +0 -52
@@ -1,103 +1,183 @@
1
1
  import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
- import {
3
- ComputeEvent,
4
- ComputeEventLogger,
5
- ComputeEventPayload,
6
- ConfiguredCredentialsService,
7
- ContextQueueService,
8
- CredentialsService,
9
- DatabaseService,
10
- FunctionError,
11
- LocalFunctionExecutionService,
12
- QueueService,
13
- RemoteFunctionExecutionService,
14
- SERVICE_TAGS,
15
- ServiceContainer,
16
- ServiceNotAvailableError,
17
- TracingService,
18
- createDefectLogger,
19
- createEventLogger,
20
- logCustomEvent
21
- } from "./chunk-K7REX6H4.mjs";
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, { get: all[name], enumerable: true });
6
+ };
22
7
 
23
- // src/handler.ts
24
- import { Schema } from "effect";
25
- var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
26
- if (!Schema.isSchema(inputSchema)) {
27
- throw new Error("Input schema must be a valid schema");
8
+ // src/errors.ts
9
+ import { BaseError } from "@dxos/errors";
10
+ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
11
+ constructor(service, options) {
12
+ super({
13
+ context: {
14
+ service
15
+ },
16
+ ...options
17
+ });
28
18
  }
29
- if (typeof handler !== "function") {
30
- throw new Error("Handler must be a function");
19
+ };
20
+ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
21
+ constructor(functionKey, options) {
22
+ super({
23
+ context: {
24
+ function: functionKey
25
+ },
26
+ ...options
27
+ });
31
28
  }
32
- return {
33
- name,
34
- description,
35
- inputSchema,
36
- outputSchema,
37
- handler
38
- };
29
+ };
30
+ var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
31
+ };
32
+ var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
39
33
  };
40
34
 
41
- // src/schema.ts
42
- import { Schema as Schema2 } from "effect";
43
- import { Type } from "@dxos/echo";
44
- import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
45
- import { DataType } from "@dxos/schema";
46
- var ScriptType = Schema2.Struct({
47
- name: Schema2.optional(Schema2.String),
48
- description: Schema2.optional(Schema2.String),
35
+ // src/example/fib.ts
36
+ import * as Effect2 from "effect/Effect";
37
+ import * as Schema6 from "effect/Schema";
38
+
39
+ // src/sdk.ts
40
+ import * as Effect from "effect/Effect";
41
+ import * as Schema5 from "effect/Schema";
42
+ import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
43
+ import { assertArgument, failedInvariant } from "@dxos/invariant";
44
+
45
+ // src/types/Function.ts
46
+ var Function_exports = {};
47
+ __export(Function_exports, {
48
+ Function: () => Function,
49
+ make: () => make2
50
+ });
51
+ import * as Schema2 from "effect/Schema";
52
+ import { Obj as Obj2, Type as Type2 } from "@dxos/echo";
53
+ import { JsonSchemaType, LabelAnnotation as LabelAnnotation2, Ref as Ref2 } from "@dxos/echo/internal";
54
+
55
+ // src/types/Script.ts
56
+ var Script_exports = {};
57
+ __export(Script_exports, {
58
+ Script: () => Script,
59
+ make: () => make
60
+ });
61
+ import * as Schema from "effect/Schema";
62
+ import { Obj, Ref, Type } from "@dxos/echo";
63
+ import { FormAnnotation, LabelAnnotation } from "@dxos/echo/internal";
64
+ import { Text } from "@dxos/schema";
65
+ var Script = Schema.Struct({
66
+ name: Schema.String.pipe(Schema.optional),
67
+ description: Schema.String.pipe(Schema.optional),
49
68
  // TODO(burdon): Change to hash of deployed content.
50
69
  // Whether source has changed since last deploy.
51
- changed: Schema2.optional(Schema2.Boolean),
52
- source: Ref(DataType.Text)
70
+ changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),
71
+ source: Type.Ref(Text.Text).pipe(FormAnnotation.set(false))
53
72
  }).pipe(Type.Obj({
54
73
  typename: "dxos.org/type/Script",
55
74
  version: "0.1.0"
56
75
  }), LabelAnnotation.set([
57
76
  "name"
58
77
  ]));
59
- var FunctionType = Schema2.Struct({
78
+ var make = ({ source = "", ...props } = {}) => Obj.make(Script, {
79
+ ...props,
80
+ source: Ref.make(Text.make(source))
81
+ });
82
+
83
+ // src/types/Function.ts
84
+ var Function = Schema2.Struct({
85
+ /**
86
+ * Global registry ID.
87
+ * NOTE: The `key` property refers to the original registry entry.
88
+ */
89
+ // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.
90
+ // TODO(dmaretskyi): Consider making it part of ECHO meta.
91
+ // TODO(dmaretskyi): Make required.
92
+ key: Schema2.optional(Schema2.String).annotations({
93
+ description: "Unique registration key for the blueprint"
94
+ }),
60
95
  // TODO(burdon): Rename to id/uri?
61
96
  name: Schema2.NonEmptyString,
62
97
  version: Schema2.String,
63
98
  description: Schema2.optional(Schema2.String),
99
+ /**
100
+ * ISO date string of the last deployment.
101
+ */
102
+ updated: Schema2.optional(Schema2.String),
64
103
  // Reference to a source script if it exists within ECHO.
65
104
  // TODO(burdon): Don't ref ScriptType directly (core).
66
- source: Schema2.optional(Ref(ScriptType)),
105
+ source: Schema2.optional(Ref2(Script)),
67
106
  inputSchema: Schema2.optional(JsonSchemaType),
68
107
  outputSchema: Schema2.optional(JsonSchemaType),
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)),
69
113
  // Local binding to a function name.
70
114
  binding: Schema2.optional(Schema2.String)
71
- }).pipe(Type.Obj({
115
+ }).pipe(Type2.Obj({
72
116
  typename: "dxos.org/type/Function",
73
117
  version: "0.1.0"
74
- }), LabelAnnotation.set([
118
+ }), LabelAnnotation2.set([
75
119
  "name"
76
120
  ]));
121
+ var make2 = (props) => Obj2.make(Function, props);
77
122
 
78
- // src/trace.ts
79
- import { Schema as Schema4 } from "effect";
80
- import { Type as Type2 } from "@dxos/echo";
81
- import { Queue } from "@dxos/echo-db";
82
- import { ObjectId } from "@dxos/echo-schema";
83
- import { log } from "@dxos/log";
84
-
85
- // src/types.ts
86
- import { Schema as Schema3, SchemaAST } from "effect";
87
- import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2, TypedObject } from "@dxos/echo-schema";
123
+ // src/types/Trigger.ts
124
+ var Trigger_exports = {};
125
+ __export(Trigger_exports, {
126
+ EmailSpec: () => EmailSpec,
127
+ Kinds: () => Kinds,
128
+ QueueSpec: () => QueueSpec,
129
+ Spec: () => Spec,
130
+ SubscriptionSpec: () => SubscriptionSpec,
131
+ TimerSpec: () => TimerSpec,
132
+ Trigger: () => Trigger,
133
+ WebhookSpec: () => WebhookSpec,
134
+ make: () => make3
135
+ });
136
+ import * as Schema3 from "effect/Schema";
137
+ import * as SchemaAST from "effect/SchemaAST";
138
+ import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
139
+ import { Expando, OptionsAnnotationId, Ref as Ref3 } from "@dxos/echo/internal";
88
140
  import { DXN } from "@dxos/keys";
89
- var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
90
- TriggerKind2["Timer"] = "timer";
91
- TriggerKind2["Webhook"] = "webhook";
92
- TriggerKind2["Subscription"] = "subscription";
93
- TriggerKind2["Email"] = "email";
94
- TriggerKind2["Queue"] = "queue";
95
- return TriggerKind2;
96
- }({});
141
+ var Kinds = [
142
+ "email",
143
+ "queue",
144
+ "subscription",
145
+ "timer",
146
+ "webhook"
147
+ ];
97
148
  var kindLiteralAnnotations = {
98
149
  title: "Kind"
99
150
  };
100
- var TimerTriggerSchema = Schema3.Struct({
151
+ var EmailSpec = Schema3.Struct({
152
+ kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
153
+ }).pipe(Schema3.mutable);
154
+ var QueueSpec = Schema3.Struct({
155
+ kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
156
+ // TODO(dmaretskyi): Change to a reference.
157
+ queue: DXN.Schema
158
+ }).pipe(Schema3.mutable);
159
+ var SubscriptionSpec = Schema3.Struct({
160
+ kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
161
+ query: Schema3.Struct({
162
+ raw: Schema3.optional(Schema3.String.annotations({
163
+ title: "Query"
164
+ })),
165
+ ast: QueryAST.Query
166
+ }).pipe(Schema3.mutable),
167
+ options: Schema3.optional(Schema3.Struct({
168
+ // Watch changes to object (not just creation).
169
+ deep: Schema3.optional(Schema3.Boolean.annotations({
170
+ title: "Nested"
171
+ })),
172
+ // Debounce changes (delay in ms).
173
+ delay: Schema3.optional(Schema3.Number.annotations({
174
+ title: "Delay"
175
+ }))
176
+ }).annotations({
177
+ title: "Options"
178
+ }))
179
+ }).pipe(Schema3.mutable);
180
+ var TimerSpec = Schema3.Struct({
101
181
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
102
182
  cron: Schema3.String.annotations({
103
183
  title: "Cron",
@@ -106,14 +186,7 @@ var TimerTriggerSchema = Schema3.Struct({
106
186
  ]
107
187
  })
108
188
  }).pipe(Schema3.mutable);
109
- var EmailTriggerSchema = Schema3.Struct({
110
- kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
111
- }).pipe(Schema3.mutable);
112
- var QueueTriggerSchema = Schema3.Struct({
113
- kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
114
- queue: DXN.Schema
115
- }).pipe(Schema3.mutable);
116
- var WebhookTriggerSchema = Schema3.Struct({
189
+ var WebhookSpec = Schema3.Struct({
117
190
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
118
191
  method: Schema3.optional(Schema3.String.annotations({
119
192
  title: "Method",
@@ -126,71 +199,15 @@ var WebhookTriggerSchema = Schema3.Struct({
126
199
  title: "Port"
127
200
  }))
128
201
  }).pipe(Schema3.mutable);
129
- var QuerySchema = Schema3.Struct({
130
- type: Schema3.optional(Schema3.String.annotations({
131
- title: "Type"
132
- })),
133
- props: Schema3.optional(Schema3.Record({
134
- key: Schema3.String,
135
- value: Schema3.Any
136
- }))
137
- }).annotations({
138
- title: "Query"
139
- });
140
- var SubscriptionTriggerSchema = Schema3.Struct({
141
- kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
142
- // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.
143
- filter: QuerySchema,
144
- options: Schema3.optional(Schema3.Struct({
145
- // Watch changes to object (not just creation).
146
- deep: Schema3.optional(Schema3.Boolean.annotations({
147
- title: "Nested"
148
- })),
149
- // Debounce changes (delay in ms).
150
- delay: Schema3.optional(Schema3.Number.annotations({
151
- title: "Delay"
152
- }))
153
- }).annotations({
154
- title: "Options"
155
- }))
156
- }).pipe(Schema3.mutable);
157
- var TriggerSchema = Schema3.Union(TimerTriggerSchema, WebhookTriggerSchema, SubscriptionTriggerSchema, EmailTriggerSchema, QueueTriggerSchema).annotations({
202
+ var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
158
203
  title: "Trigger"
159
204
  });
160
- var EmailTriggerOutput = Schema3.mutable(Schema3.Struct({
161
- from: Schema3.String,
162
- to: Schema3.String,
163
- subject: Schema3.String,
164
- created: Schema3.String,
165
- body: Schema3.String
166
- }));
167
- var WebhookTriggerOutput = Schema3.mutable(Schema3.Struct({
168
- url: Schema3.String,
169
- method: Schema3.Literal("GET", "POST"),
170
- headers: Schema3.Record({
171
- key: Schema3.String,
172
- value: Schema3.String
173
- }),
174
- bodyText: Schema3.String
175
- }));
176
- var QueueTriggerOutput = Schema3.mutable(Schema3.Struct({
177
- queue: DXN.Schema,
178
- item: Schema3.Any,
179
- cursor: Schema3.String
180
- }));
181
- var SubscriptionTriggerOutput = Schema3.mutable(Schema3.Struct({
182
- type: Schema3.String,
183
- changedObjectId: Schema3.String
184
- }));
185
- var TimerTriggerOutput = Schema3.mutable(Schema3.Struct({
186
- tick: Schema3.Number
187
- }));
188
- var FunctionTriggerSchema = Schema3.Struct({
205
+ var Trigger_ = Schema3.Struct({
189
206
  /**
190
207
  * Function or workflow to invoke.
191
208
  */
192
209
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
193
- function: Schema3.optional(Ref2(Expando).annotations({
210
+ function: Schema3.optional(Ref3(Expando).annotations({
194
211
  title: "Function"
195
212
  })),
196
213
  /**
@@ -204,7 +221,7 @@ var FunctionTriggerSchema = Schema3.Struct({
204
221
  enabled: Schema3.optional(Schema3.Boolean.annotations({
205
222
  title: "Enabled"
206
223
  })),
207
- spec: Schema3.optional(TriggerSchema),
224
+ spec: Schema3.optional(Spec),
208
225
  /**
209
226
  * Passed as the input data to the function.
210
227
  * Must match the function's input schema.
@@ -220,236 +237,659 @@ var FunctionTriggerSchema = Schema3.Struct({
220
237
  key: Schema3.String,
221
238
  value: Schema3.Any
222
239
  })))
223
- });
224
- var FunctionTrigger = class extends TypedObject({
225
- typename: "dxos.org/type/FunctionTrigger",
226
- version: "0.2.0"
227
- })(FunctionTriggerSchema.fields) {
228
- };
229
- var FunctionManifestSchema = Schema3.Struct({
230
- functions: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionType)))),
231
- triggers: Schema3.optional(Schema3.mutable(Schema3.Array(RawObject(FunctionTrigger))))
232
- });
233
- var FUNCTION_TYPES = [
234
- FunctionType,
235
- FunctionTrigger
236
- ];
240
+ }).pipe(Type3.Obj({
241
+ typename: "dxos.org/type/Trigger",
242
+ version: "0.1.0"
243
+ }));
244
+ var Trigger = Trigger_;
245
+ var make3 = (props) => Obj3.make(Trigger, props);
237
246
 
238
- // src/trace.ts
239
- var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
240
- var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
241
- InvocationOutcome2["SUCCESS"] = "success";
242
- InvocationOutcome2["FAILURE"] = "failure";
243
- InvocationOutcome2["PENDING"] = "pending";
244
- return InvocationOutcome2;
245
- }({});
246
- var InvocationTraceEventType = /* @__PURE__ */ function(InvocationTraceEventType2) {
247
- InvocationTraceEventType2["START"] = "start";
248
- InvocationTraceEventType2["END"] = "end";
249
- return InvocationTraceEventType2;
250
- }({});
251
- var TraceEventException = Schema4.Struct({
252
- timestampMs: Schema4.Number,
253
- message: Schema4.String,
254
- name: Schema4.String,
255
- stack: Schema4.optional(Schema4.String)
247
+ // src/types/TriggerEvent.ts
248
+ var TriggerEvent_exports = {};
249
+ __export(TriggerEvent_exports, {
250
+ EmailEvent: () => EmailEvent,
251
+ QueueEvent: () => QueueEvent,
252
+ SubscriptionEvent: () => SubscriptionEvent,
253
+ TimerEvent: () => TimerEvent,
254
+ WebhookEvent: () => WebhookEvent
256
255
  });
257
- var InvocationTraceStartEvent = Schema4.Struct({
258
- /**
259
- * Queue message id.
260
- */
261
- id: ObjectId,
262
- type: Schema4.Literal("start"),
263
- /**
264
- * Invocation id, the same for invocation start and end events.
265
- */
266
- invocationId: ObjectId,
267
- /**
268
- * Event generation time.
269
- */
270
- timestampMs: Schema4.Number,
271
- /**
272
- * Data passed to function / workflow as an argument.
273
- */
274
- // TODO(burdon): Input schema?
275
- input: Schema4.Object,
276
- /**
277
- * Queue for function/workflow invocation events.
278
- */
279
- invocationTraceQueue: Type2.Ref(Queue),
280
- /**
281
- * DXN of the invoked function/workflow.
282
- */
283
- invocationTarget: Type2.Ref(Type2.Expando),
284
- /**
285
- * Present for automatic invocations.
286
- */
287
- trigger: Schema4.optional(Type2.Ref(FunctionTrigger))
288
- }).pipe(Type2.Obj({
289
- typename: "dxos.org/type/InvocationTraceStart",
290
- version: "0.1.0"
256
+ import * as Schema4 from "effect/Schema";
257
+ import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
258
+ var EmailEvent = Schema4.mutable(Schema4.Struct({
259
+ from: Schema4.String,
260
+ to: Schema4.String,
261
+ subject: Schema4.String,
262
+ created: Schema4.String,
263
+ body: Schema4.String
291
264
  }));
292
- var InvocationTraceEndEvent = Schema4.Struct({
265
+ var QueueEvent = Schema4.mutable(Schema4.Struct({
266
+ queue: DXN2.Schema,
267
+ item: Schema4.Any,
268
+ cursor: Schema4.String
269
+ }));
270
+ var SubscriptionEvent = Schema4.Struct({
293
271
  /**
294
- * Trace event id.
272
+ * Type of the mutation.
295
273
  */
296
- id: ObjectId,
297
- type: Schema4.Literal("end"),
274
+ // TODO(dmaretskyi): Specify enum.
275
+ type: Schema4.String,
298
276
  /**
299
- * Invocation id, will be the same for invocation start and end.
277
+ * Reference to the object that was changed or created.
300
278
  */
301
- invocationId: ObjectId,
279
+ subject: Type4.Ref(Obj4.Any),
302
280
  /**
303
- * Event generation time.
281
+ * @deprecated
304
282
  */
305
- // TODO(burdon): Remove ms suffix.
306
- timestampMs: Schema4.Number,
307
- outcome: Schema4.Enums(InvocationOutcome),
308
- exception: Schema4.optional(TraceEventException)
309
- }).pipe(Type2.Obj({
310
- typename: "dxos.org/type/InvocationTraceEnd",
311
- version: "0.1.0"
283
+ changedObjectId: Schema4.optional(Schema4.String)
284
+ }).pipe(Schema4.mutable);
285
+ var TimerEvent = Schema4.mutable(Schema4.Struct({
286
+ tick: Schema4.Number
312
287
  }));
313
- var TraceEventLog = Schema4.Struct({
314
- timestampMs: Schema4.Number,
315
- level: Schema4.String,
316
- message: Schema4.String,
317
- context: Schema4.optional(Schema4.Object)
318
- });
319
- var TraceEvent = Schema4.Struct({
320
- id: ObjectId,
321
- // TODO(burdon): Need enum/numeric result (not string).
322
- outcome: Schema4.String,
323
- truncated: Schema4.Boolean,
324
- /** Time when the event was persisted. */
325
- ingestionTimestamp: Schema4.Number,
326
- logs: Schema4.Array(TraceEventLog),
327
- exceptions: Schema4.Array(TraceEventException)
328
- }).pipe(Type2.Obj({
329
- typename: "dxos.org/type/TraceEvent",
330
- version: "0.1.0"
288
+ var WebhookEvent = Schema4.mutable(Schema4.Struct({
289
+ url: Schema4.String,
290
+ method: Schema4.Literal("GET", "POST"),
291
+ headers: Schema4.Record({
292
+ key: Schema4.String,
293
+ value: Schema4.String
294
+ }),
295
+ bodyText: Schema4.String
331
296
  }));
332
- var createInvocationSpans = (items) => {
333
- if (!items) {
334
- return [];
335
- }
336
- const eventsByInvocationId = /* @__PURE__ */ new Map();
337
- for (const event of items) {
338
- if (!("invocationId" in event)) {
339
- continue;
340
- }
341
- const invocationId = event.invocationId;
342
- const entry = eventsByInvocationId.get(invocationId) || {
343
- start: void 0,
344
- end: void 0
345
- };
346
- if (event.type === "start") {
347
- entry.start = event;
348
- } else if (event.type === "end") {
349
- entry.end = event;
350
- }
351
- eventsByInvocationId.set(invocationId, entry);
352
- }
353
- const now = Date.now();
354
- const result = [];
355
- for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {
356
- if (!start) {
357
- log.warn("found end event without matching start", {
358
- invocationId
359
- }, {
360
- F: __dxlog_file,
361
- L: 158,
362
- S: void 0,
363
- C: (f, a) => f(...a)
364
- });
365
- continue;
366
- }
367
- const isInProgress = end === void 0;
368
- result.push({
369
- id: invocationId,
370
- timestampMs: start.timestampMs,
371
- durationMs: isInProgress ? now - start.timestampMs : end.timestampMs - start.timestampMs,
372
- outcome: end?.outcome ?? "pending",
373
- exception: end?.exception,
374
- input: start.input,
375
- invocationTraceQueue: start.invocationTraceQueue,
376
- invocationTarget: start.invocationTarget,
377
- trigger: start.trigger
378
- });
379
- }
380
- return result;
381
- };
382
297
 
383
- // src/url.ts
298
+ // src/types/url.ts
384
299
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
385
300
  var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
386
- var isSecure = (protocol) => {
387
- return protocol === "https:" || protocol === "wss:";
388
- };
389
- var getUserFunctionUrlInMetadata = (meta) => {
301
+ var getUserFunctionIdInMetadata = (meta) => {
390
302
  return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
391
303
  };
392
- var setUserFunctionUrlInMetadata = (meta, functionUrl) => {
304
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
393
305
  const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
394
306
  if (key) {
395
- if (key.id !== functionUrl) {
307
+ if (key.id !== functionId) {
396
308
  throw new Error("Metadata mismatch");
397
309
  }
398
310
  } else {
399
311
  meta.keys.push({
400
312
  source: FUNCTIONS_META_KEY,
401
- id: functionUrl
313
+ id: functionId
402
314
  });
403
315
  }
404
316
  };
405
- var makeFunctionUrl = (fn) => `/${fn.functionId}`;
406
- var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
407
- const baseUrl = new URL("functions/", edgeUrl);
408
- const relativeUrl = functionUrl.replace(/^\//, "");
409
- const url = new URL(`./${relativeUrl}`, baseUrl.toString());
410
- options.spaceId && url.searchParams.set("spaceId", options.spaceId);
411
- options.subjectId && url.searchParams.set("subjectId", options.subjectId);
412
- url.protocol = isSecure(url.protocol) ? "https" : "http";
413
- return url.toString();
317
+
318
+ // src/sdk.ts
319
+ var typeId = Symbol.for("@dxos/functions/FunctionDefinition");
320
+ var defineFunction = ({ key, name, description, inputSchema, outputSchema = Schema5.Any, handler, services }) => {
321
+ if (!Schema5.isSchema(inputSchema)) {
322
+ throw new Error("Input schema must be a valid schema");
323
+ }
324
+ if (typeof handler !== "function") {
325
+ throw new Error("Handler must be a function");
326
+ }
327
+ const limit = Error.stackTraceLimit;
328
+ Error.stackTraceLimit = 2;
329
+ const traceError = new Error();
330
+ Error.stackTraceLimit = limit;
331
+ let cache = false;
332
+ const captureStackTrace = () => {
333
+ if (cache !== false) {
334
+ return cache;
335
+ }
336
+ if (traceError.stack !== void 0) {
337
+ const stack = traceError.stack.split("\n");
338
+ if (stack[2] !== void 0) {
339
+ cache = stack[2].trim();
340
+ return cache;
341
+ }
342
+ }
343
+ };
344
+ const handlerWithSpan = (...args) => {
345
+ const result = handler(...args);
346
+ if (Effect.isEffect(result)) {
347
+ return Effect.withSpan(result, `${key ?? name}`, {
348
+ captureStackTrace
349
+ });
350
+ }
351
+ return result;
352
+ };
353
+ return {
354
+ [typeId]: true,
355
+ key,
356
+ name,
357
+ description,
358
+ inputSchema,
359
+ outputSchema,
360
+ handler: handlerWithSpan,
361
+ services: !services ? [] : getServiceKeys(services)
362
+ };
363
+ };
364
+ var getServiceKeys = (services) => {
365
+ return services.map((tag) => {
366
+ if (typeof tag.key === "string") {
367
+ return tag.key;
368
+ }
369
+ console.log(tag);
370
+ failedInvariant();
371
+ });
372
+ };
373
+ var FunctionDefinition = {
374
+ make: defineFunction,
375
+ isFunction: (value2) => {
376
+ return typeof value2 === "object" && value2 !== null && Symbol.for("@dxos/functions/FunctionDefinition") in value2;
377
+ },
378
+ serialize: (functionDef) => {
379
+ assertArgument(FunctionDefinition.isFunction(functionDef), "functionDef");
380
+ return serializeFunction(functionDef);
381
+ },
382
+ deserialize: (functionObj) => {
383
+ assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
384
+ return deserializeFunction(functionObj);
385
+ }
386
+ };
387
+ var serializeFunction = (functionDef) => {
388
+ const fn4 = Function_exports.make({
389
+ key: functionDef.key,
390
+ name: functionDef.name,
391
+ version: "0.1.0",
392
+ description: functionDef.description,
393
+ inputSchema: Type5.toJsonSchema(functionDef.inputSchema),
394
+ outputSchema: !functionDef.outputSchema ? void 0 : Type5.toJsonSchema(functionDef.outputSchema),
395
+ services: functionDef.services
396
+ });
397
+ if (functionDef.meta?.deployedFunctionId) {
398
+ setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
399
+ }
400
+ return fn4;
401
+ };
402
+ var deserializeFunction = (functionObj) => {
403
+ return {
404
+ [typeId]: true,
405
+ // TODO(dmaretskyi): Fix key.
406
+ key: functionObj.key ?? functionObj.name,
407
+ name: functionObj.name,
408
+ description: functionObj.description,
409
+ inputSchema: !functionObj.inputSchema ? Schema5.Unknown : Type5.toEffectSchema(functionObj.inputSchema),
410
+ outputSchema: !functionObj.outputSchema ? void 0 : Type5.toEffectSchema(functionObj.outputSchema),
411
+ // TODO(dmaretskyi): This should throw error.
412
+ handler: () => {
413
+ },
414
+ services: functionObj.services ?? [],
415
+ meta: {
416
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
417
+ }
418
+ };
414
419
  };
415
420
 
416
- // src/executor/executor.ts
417
- import { Effect, Schema as Schema5 } from "effect";
418
- import { runAndForwardErrors } from "@dxos/effect";
419
- var FunctionExecutor = class {
420
- _services;
421
- constructor(_services) {
422
- this._services = _services;
421
+ // src/example/fib.ts
422
+ var fib_default = defineFunction({
423
+ key: "example.org/function/fib",
424
+ name: "Fibonacci",
425
+ description: "Function that calculates a Fibonacci number",
426
+ inputSchema: Schema6.Struct({
427
+ iterations: Schema6.optional(Schema6.Number).annotations({
428
+ description: "Number of iterations",
429
+ default: 1e5
430
+ })
431
+ }),
432
+ outputSchema: Schema6.Struct({
433
+ result: Schema6.String
434
+ }),
435
+ handler: Effect2.fn(function* ({ data: { iterations = 1e5 } }) {
436
+ let a = 0n;
437
+ let b = 1n;
438
+ for (let i = 0; i < iterations; i++) {
439
+ a += b;
440
+ b = a - b;
441
+ }
442
+ return {
443
+ result: a.toString()
444
+ };
445
+ })
446
+ });
447
+
448
+ // src/example/reply.ts
449
+ import * as Console from "effect/Console";
450
+ import * as Effect3 from "effect/Effect";
451
+ import * as Schema7 from "effect/Schema";
452
+ var reply_default = defineFunction({
453
+ key: "example.org/function/reply",
454
+ name: "Reply",
455
+ description: "Function that echoes the input",
456
+ inputSchema: Schema7.Any,
457
+ outputSchema: Schema7.Any,
458
+ handler: Effect3.fn(function* ({ data }) {
459
+ yield* Console.log("reply", {
460
+ data
461
+ });
462
+ return data;
463
+ })
464
+ });
465
+
466
+ // src/example/sleep.ts
467
+ import * as Effect4 from "effect/Effect";
468
+ import * as Schema8 from "effect/Schema";
469
+ var sleep_default = defineFunction({
470
+ key: "example.org/function/sleep",
471
+ name: "Sleep",
472
+ description: "Function that sleeps for a given amount of time",
473
+ inputSchema: Schema8.Struct({
474
+ duration: Schema8.optional(Schema8.Number).annotations({
475
+ description: "Milliseconds to sleep",
476
+ default: 1e5
477
+ })
478
+ }),
479
+ outputSchema: Schema8.Void,
480
+ handler: Effect4.fn(function* ({ data: { duration = 1e5 } }) {
481
+ yield* Effect4.sleep(duration);
482
+ })
483
+ });
484
+
485
+ // src/example/index.ts
486
+ (function(Example2) {
487
+ Example2.fib = fib_default;
488
+ Example2.reply = reply_default;
489
+ Example2.sleep = sleep_default;
490
+ })(Example || (Example = {}));
491
+ var Example;
492
+
493
+ // src/services/index.ts
494
+ import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
495
+
496
+ // src/services/credentials.ts
497
+ import * as HttpClient from "@effect/platform/HttpClient";
498
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
499
+ import * as Context from "effect/Context";
500
+ import * as Effect5 from "effect/Effect";
501
+ import * as Layer from "effect/Layer";
502
+ import * as Redacted from "effect/Redacted";
503
+ import { Query } from "@dxos/echo";
504
+ import { DatabaseService } from "@dxos/echo-db";
505
+ import { AccessToken } from "@dxos/types";
506
+ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
507
+ static getCredential = (query) => Effect5.gen(function* () {
508
+ const credentials = yield* _CredentialsService;
509
+ return yield* Effect5.promise(() => credentials.getCredential(query));
510
+ });
511
+ static getApiKey = (query) => Effect5.gen(function* () {
512
+ const credential = yield* _CredentialsService.getCredential(query);
513
+ if (!credential.apiKey) {
514
+ throw new Error(`API key not found for service: ${query.service}`);
515
+ }
516
+ return Redacted.make(credential.apiKey);
517
+ });
518
+ static configuredLayer = (credentials) => Layer.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
519
+ static layerConfig = (credentials) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
520
+ const serviceCredentials = yield* Effect5.forEach(credentials, ({ service, apiKey }) => Effect5.gen(function* () {
521
+ return {
522
+ service,
523
+ apiKey: Redacted.value(yield* apiKey)
524
+ };
525
+ }));
526
+ return new ConfiguredCredentialsService(serviceCredentials);
527
+ }));
528
+ static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
529
+ const dbService = yield* DatabaseService;
530
+ const queryCredentials = async (query) => {
531
+ const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
532
+ return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
533
+ service: accessToken.source,
534
+ apiKey: accessToken.token
535
+ }));
536
+ };
537
+ return {
538
+ getCredential: async (query) => {
539
+ const credentials = await queryCredentials(query);
540
+ if (credentials.length === 0) {
541
+ throw new Error(`Credential not found for service: ${query.service}`);
542
+ }
543
+ return credentials[0];
544
+ },
545
+ queryCredentials: async (query) => {
546
+ return queryCredentials(query);
547
+ }
548
+ };
549
+ }));
550
+ };
551
+ var ConfiguredCredentialsService = class {
552
+ credentials;
553
+ constructor(credentials = []) {
554
+ this.credentials = credentials;
555
+ }
556
+ addCredentials(credentials) {
557
+ this.credentials.push(...credentials);
558
+ return this;
423
559
  }
560
+ async queryCredentials(query) {
561
+ return this.credentials.filter((credential) => credential.service === query.service);
562
+ }
563
+ async getCredential(query) {
564
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
565
+ if (!credential) {
566
+ throw new Error(`Credential not found for service: ${query.service}`);
567
+ }
568
+ return credential;
569
+ }
570
+ };
571
+ var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
572
+ const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
573
+ const authorization = kind ? `${kind} ${key}` : key;
574
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
575
+ }));
576
+
577
+ // src/services/event-logger.ts
578
+ import * as Context3 from "effect/Context";
579
+ import * as Effect7 from "effect/Effect";
580
+ import * as Layer3 from "effect/Layer";
581
+ import * as Schema9 from "effect/Schema";
582
+ import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
583
+ import { invariant } from "@dxos/invariant";
584
+ import { LogLevel, log as log2 } from "@dxos/log";
585
+
586
+ // src/services/tracing.ts
587
+ import * as Context2 from "effect/Context";
588
+ import * as Effect6 from "effect/Effect";
589
+ import * as Layer2 from "effect/Layer";
590
+ import { AgentStatus } from "@dxos/ai";
591
+ import { Obj as Obj6 } from "@dxos/echo";
592
+ import { Message } from "@dxos/types";
593
+ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
594
+ static noop = {
595
+ getTraceContext: () => ({}),
596
+ write: () => {
597
+ }
598
+ };
599
+ static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
424
600
  /**
425
- *
601
+ * Creates a TracingService layer that emits events to the parent tracing service.
426
602
  */
427
- // TODO(dmaretskyi): Invocation context: queue, space, etc...
428
- async invoke(fnDef, input) {
429
- const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
430
- assertInput(input);
431
- const context = {
432
- space: void 0,
433
- getService: this._services.getService.bind(this._services),
434
- getSpace: async (_spaceId) => {
435
- throw new Error("Not available. Use the database service instead.");
603
+ static layerSubframe = (mapContext) => Layer2.effect(_TracingService, Effect6.gen(function* () {
604
+ const tracing = yield* _TracingService;
605
+ const context = mapContext(tracing.getTraceContext());
606
+ return {
607
+ write: (event) => tracing.write(event),
608
+ getTraceContext: () => context
609
+ };
610
+ }));
611
+ /**
612
+ * Emit the current human-readable execution status.
613
+ */
614
+ static emitStatus = Effect6.fnUntraced(function* (data) {
615
+ const tracing = yield* _TracingService;
616
+ tracing.write(Obj6.make(AgentStatus, {
617
+ parentMessage: tracing.getTraceContext().parentMessage,
618
+ toolCallId: tracing.getTraceContext().toolCallId,
619
+ created: (/* @__PURE__ */ new Date()).toISOString(),
620
+ ...data
621
+ }));
622
+ });
623
+ static emitConverationMessage = Effect6.fnUntraced(function* (data) {
624
+ const tracing = yield* _TracingService;
625
+ tracing.write(Obj6.make(Message.Message, {
626
+ parentMessage: tracing.getTraceContext().parentMessage,
627
+ ...data,
628
+ properties: {
629
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
630
+ ...data.properties
436
631
  }
632
+ }));
633
+ });
634
+ };
635
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
636
+
637
+ // src/services/event-logger.ts
638
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
639
+ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
640
+ type: Schema9.Literal("begin-compute"),
641
+ nodeId: Schema9.String,
642
+ /**
643
+ * Names of the inputs begin computed.
644
+ */
645
+ inputs: Schema9.Array(Schema9.String)
646
+ }), Schema9.Struct({
647
+ type: Schema9.Literal("end-compute"),
648
+ nodeId: Schema9.String,
649
+ /**
650
+ * Names of the outputs computed.
651
+ */
652
+ outputs: Schema9.Array(Schema9.String)
653
+ }), Schema9.Struct({
654
+ type: Schema9.Literal("compute-input"),
655
+ nodeId: Schema9.String,
656
+ property: Schema9.String,
657
+ value: Schema9.Any
658
+ }), Schema9.Struct({
659
+ type: Schema9.Literal("compute-output"),
660
+ nodeId: Schema9.String,
661
+ property: Schema9.String,
662
+ value: Schema9.Any
663
+ }), Schema9.Struct({
664
+ type: Schema9.Literal("custom"),
665
+ nodeId: Schema9.String,
666
+ event: Schema9.Any
667
+ }));
668
+ var ComputeEvent = Schema9.Struct({
669
+ payload: ComputeEventPayload
670
+ }).pipe(Type6.Obj({
671
+ typename: "dxos.org/type/ComputeEvent",
672
+ version: "0.1.0"
673
+ }));
674
+ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/functions/ComputeEventLogger")() {
675
+ static noop = {
676
+ log: () => {
677
+ },
678
+ nodeId: void 0
679
+ };
680
+ /**
681
+ * Implements ComputeEventLogger using TracingService.
682
+ */
683
+ static layerFromTracing = Layer3.effect(_ComputeEventLogger, Effect7.gen(function* () {
684
+ const tracing = yield* TracingService;
685
+ return {
686
+ log: (event) => {
687
+ tracing.write(Obj7.make(ComputeEvent, {
688
+ payload: event
689
+ }));
690
+ },
691
+ nodeId: void 0
437
692
  };
438
- const result = fnDef.handler({
439
- context,
440
- data: input
441
- });
442
- let data;
443
- if (Effect.isEffect(result)) {
444
- data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
445
- } else {
446
- data = await result;
447
- }
448
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
449
- assertOutput(data);
450
- return data;
693
+ }));
694
+ };
695
+ var logCustomEvent = (data) => Effect7.gen(function* () {
696
+ const logger = yield* ComputeEventLogger;
697
+ if (!logger.nodeId) {
698
+ throw new Error("logCustomEvent must be called within a node compute function");
451
699
  }
700
+ logger.log({
701
+ type: "custom",
702
+ nodeId: logger.nodeId,
703
+ event: data
704
+ });
705
+ });
706
+ var createDefectLogger = () => Effect7.catchAll((error) => Effect7.gen(function* () {
707
+ log2.error("unhandled effect error", {
708
+ error
709
+ }, {
710
+ F: __dxlog_file,
711
+ L: 102,
712
+ S: this,
713
+ C: (f, a) => f(...a)
714
+ });
715
+ throw error;
716
+ }));
717
+ var createEventLogger = (level, message = "event") => {
718
+ const logFunction = {
719
+ [LogLevel.WARN]: log2.warn,
720
+ [LogLevel.VERBOSE]: log2.verbose,
721
+ [LogLevel.DEBUG]: log2.debug,
722
+ [LogLevel.INFO]: log2.info,
723
+ [LogLevel.ERROR]: log2.error
724
+ }[level];
725
+ invariant(logFunction, void 0, {
726
+ F: __dxlog_file,
727
+ L: 120,
728
+ S: void 0,
729
+ A: [
730
+ "logFunction",
731
+ ""
732
+ ]
733
+ });
734
+ return {
735
+ log: (event) => {
736
+ logFunction(message, event);
737
+ },
738
+ nodeId: void 0
739
+ };
740
+ };
741
+
742
+ // src/services/function-invocation-service.ts
743
+ import * as Context4 from "effect/Context";
744
+ import * as Effect8 from "effect/Effect";
745
+ var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
746
+ static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
452
747
  };
748
+
749
+ // src/services/queues.ts
750
+ import * as Context5 from "effect/Context";
751
+ import * as Effect9 from "effect/Effect";
752
+ import * as Layer4 from "effect/Layer";
753
+ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
754
+ static notAvailable = Layer4.succeed(_QueueService, {
755
+ queues: {
756
+ get(_dxn) {
757
+ throw new Error("Queues not available");
758
+ },
759
+ create() {
760
+ throw new Error("Queues not available");
761
+ }
762
+ },
763
+ queue: void 0
764
+ });
765
+ static make = (queues, queue) => {
766
+ return {
767
+ queues,
768
+ queue
769
+ };
770
+ };
771
+ static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
772
+ /**
773
+ * Gets a queue by its DXN.
774
+ */
775
+ static getQueue = (dxn) => _QueueService.pipe(Effect9.map(({ queues }) => queues.get(dxn)));
776
+ /**
777
+ * Creates a new queue.
778
+ */
779
+ static createQueue = (options) => _QueueService.pipe(Effect9.map(({ queues }) => queues.create(options)));
780
+ static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
781
+ };
782
+ var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
783
+ static layer = (queue) => Layer4.succeed(_ContextQueueService, {
784
+ queue
785
+ });
786
+ };
787
+
788
+ // src/protocol/protocol.ts
789
+ import * as Effect10 from "effect/Effect";
790
+ import * as Layer5 from "effect/Layer";
791
+ import * as Schema10 from "effect/Schema";
792
+ import * as SchemaAST2 from "effect/SchemaAST";
793
+ import { AiService } from "@dxos/ai";
794
+ import { Type as Type7 } from "@dxos/echo";
795
+ import { EchoClient } from "@dxos/echo-db";
796
+ import { acquireReleaseResource } from "@dxos/effect";
797
+ import { failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
798
+ import { PublicKey } from "@dxos/keys";
799
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
800
+ var wrapFunctionHandler = (func) => {
801
+ if (!FunctionDefinition.isFunction(func)) {
802
+ throw new TypeError("Invalid function definition");
803
+ }
804
+ return {
805
+ meta: {
806
+ key: func.key,
807
+ name: func.name,
808
+ description: func.description,
809
+ inputSchema: Type7.toJsonSchema(func.inputSchema),
810
+ outputSchema: func.outputSchema === void 0 ? void 0 : Type7.toJsonSchema(func.outputSchema),
811
+ services: func.services
812
+ },
813
+ handler: async ({ data, context }) => {
814
+ if ((func.services.includes(DatabaseService2.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
815
+ throw new FunctionError({
816
+ message: "Services not provided: dataService, queryService"
817
+ });
818
+ }
819
+ try {
820
+ if (!SchemaAST2.isAnyKeyword(func.inputSchema.ast)) {
821
+ Schema10.validateSync(func.inputSchema)(data);
822
+ }
823
+ let result = await func.handler({
824
+ // TODO(dmaretskyi): Fix the types.
825
+ context,
826
+ data
827
+ });
828
+ if (Effect10.isEffect(result)) {
829
+ result = await Effect10.runPromise(result.pipe(Effect10.orDie, Effect10.provide(createServiceLayer(context))));
830
+ }
831
+ if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
832
+ Schema10.validateSync(func.outputSchema)(result);
833
+ }
834
+ return result;
835
+ } catch (error) {
836
+ if (FunctionError.is(error)) {
837
+ throw error;
838
+ } else {
839
+ throw new FunctionError({
840
+ cause: error,
841
+ context: {
842
+ func: func.key
843
+ }
844
+ });
845
+ }
846
+ }
847
+ }
848
+ };
849
+ };
850
+ var createServiceLayer = (context) => {
851
+ return Layer5.unwrapScoped(Effect10.gen(function* () {
852
+ let client;
853
+ if (context.services.dataService && context.services.queryService) {
854
+ client = yield* acquireReleaseResource(() => {
855
+ invariant2(context.services.dataService && context.services.queryService, void 0, {
856
+ F: __dxlog_file2,
857
+ L: 99,
858
+ S: this,
859
+ A: [
860
+ "context.services.dataService && context.services.queryService",
861
+ ""
862
+ ]
863
+ });
864
+ return new EchoClient().connectToService({
865
+ dataService: context.services.dataService,
866
+ queryService: context.services.queryService,
867
+ queueService: context.services.queueService
868
+ });
869
+ });
870
+ }
871
+ const db = client && context.spaceId ? yield* acquireReleaseResource(() => client.constructDatabase({
872
+ spaceId: context.spaceId ?? failedInvariant2(),
873
+ spaceKey: PublicKey.fromHex(context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
874
+ reactiveSchemaQuery: false
875
+ })) : void 0;
876
+ if (db) {
877
+ console.log("Setting space root", context.spaceRootUrl);
878
+ yield* Effect10.promise(() => db.setSpaceRoot(context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context")));
879
+ }
880
+ const queues = client && context.spaceId ? client.constructQueueFactory(context.spaceId) : void 0;
881
+ const dbLayer = db ? DatabaseService2.layer(db) : DatabaseService2.notAvailable;
882
+ const queuesLayer = queues ? QueueService.layer(queues) : QueueService.notAvailable;
883
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
884
+ const functionInvocationService = MockedFunctionInvocationService;
885
+ const aiService = AiService.notAvailable;
886
+ const tracing = TracingService.layerNoop;
887
+ return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
888
+ }));
889
+ };
890
+ var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
891
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
892
+ });
453
893
  export {
454
894
  ComputeEvent,
455
895
  ComputeEventLogger,
@@ -457,45 +897,32 @@ export {
457
897
  ConfiguredCredentialsService,
458
898
  ContextQueueService,
459
899
  CredentialsService,
460
- DatabaseService,
461
- EmailTriggerOutput,
900
+ DatabaseService2 as DatabaseService,
901
+ Example,
902
+ FUNCTIONS_META_KEY,
462
903
  FUNCTIONS_PRESET_META_KEY,
463
- FUNCTION_TYPES,
904
+ Function_exports as Function,
905
+ FunctionDefinition,
464
906
  FunctionError,
465
- FunctionExecutor,
466
- FunctionManifestSchema,
467
- FunctionTrigger,
468
- FunctionTriggerSchema,
469
- FunctionType,
470
- InvocationOutcome,
471
- InvocationTraceEndEvent,
472
- InvocationTraceEventType,
473
- InvocationTraceStartEvent,
474
- LocalFunctionExecutionService,
907
+ FunctionInvocationService,
908
+ FunctionNotFoundError,
909
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
475
910
  QueueService,
476
- QueueTriggerOutput,
477
- RemoteFunctionExecutionService,
478
- SERVICE_TAGS,
479
- ScriptType,
480
- ServiceContainer,
911
+ Script_exports as Script,
481
912
  ServiceNotAvailableError,
482
- SubscriptionTriggerOutput,
483
- TimerTriggerOutput,
484
- TraceEvent,
485
- TraceEventException,
486
- TraceEventLog,
487
913
  TracingService,
488
- TriggerKind,
489
- TriggerSchema,
490
- WebhookTriggerOutput,
914
+ Trigger_exports as Trigger,
915
+ TriggerEvent_exports as TriggerEvent,
916
+ TriggerStateNotFoundError,
491
917
  createDefectLogger,
492
918
  createEventLogger,
493
- createInvocationSpans,
494
919
  defineFunction,
495
- getInvocationUrl,
496
- getUserFunctionUrlInMetadata,
920
+ deserializeFunction,
921
+ getUserFunctionIdInMetadata,
497
922
  logCustomEvent,
498
- makeFunctionUrl,
499
- setUserFunctionUrlInMetadata
923
+ serializeFunction,
924
+ setUserFunctionIdInMetadata,
925
+ withAuthorization,
926
+ wrapFunctionHandler
500
927
  };
501
928
  //# sourceMappingURL=index.mjs.map