@dxos/functions 0.8.4-main.5ea62a8 → 0.8.4-main.66e292d

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