@dxos/functions 0.8.4-main.67995b8 → 0.8.4-main.70d3990

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