@dxos/functions 0.8.4-main.67995b8 → 0.8.4-main.72ec0f3

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