@dxos/functions 0.8.4-main.5ea62a8 → 0.8.4-main.72ec0f3

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