@dxos/functions 0.8.4-main.b97322e → 0.8.4-main.bcb3aa67d6

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 (191) hide show
  1. package/README.md +4 -6
  2. package/dist/lib/neutral/Trace.mjs +34 -0
  3. package/dist/lib/neutral/Trace.mjs.map +7 -0
  4. package/dist/lib/neutral/chunk-BHLSCAA2.mjs +123 -0
  5. package/dist/lib/neutral/chunk-BHLSCAA2.mjs.map +7 -0
  6. package/dist/lib/neutral/chunk-J5LGTIGS.mjs +10 -0
  7. package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +7 -0
  8. package/dist/lib/neutral/chunk-Z2XDJJVH.mjs +49 -0
  9. package/dist/lib/neutral/chunk-Z2XDJJVH.mjs.map +7 -0
  10. package/dist/lib/neutral/fib-S6PPI4UW.mjs +23 -0
  11. package/dist/lib/neutral/fib-S6PPI4UW.mjs.map +7 -0
  12. package/dist/lib/neutral/index.mjs +1245 -0
  13. package/dist/lib/neutral/index.mjs.map +7 -0
  14. package/dist/lib/neutral/meta.json +1 -0
  15. package/dist/lib/neutral/reply-TOHXEG7V.mjs +19 -0
  16. package/dist/lib/neutral/reply-TOHXEG7V.mjs.map +7 -0
  17. package/dist/lib/neutral/sleep-QPSZDPEH.mjs +15 -0
  18. package/dist/lib/neutral/sleep-QPSZDPEH.mjs.map +7 -0
  19. package/dist/types/src/Trace.d.ts +135 -0
  20. package/dist/types/src/Trace.d.ts.map +1 -0
  21. package/dist/types/src/errors.d.ts +91 -38
  22. package/dist/types/src/errors.d.ts.map +1 -1
  23. package/dist/types/src/example/definitions.d.ts +11 -0
  24. package/dist/types/src/example/definitions.d.ts.map +1 -0
  25. package/dist/types/src/example/fib.d.ts +8 -0
  26. package/dist/types/src/example/fib.d.ts.map +1 -0
  27. package/dist/types/src/example/forex-effect.d.ts +3 -0
  28. package/dist/types/src/example/forex-effect.d.ts.map +1 -0
  29. package/dist/types/src/example/index.d.ts +4 -0
  30. package/dist/types/src/example/index.d.ts.map +1 -0
  31. package/dist/types/src/example/reply.d.ts +4 -0
  32. package/dist/types/src/example/reply.d.ts.map +1 -0
  33. package/dist/types/src/example/sleep.d.ts +6 -0
  34. package/dist/types/src/example/sleep.d.ts.map +1 -0
  35. package/dist/types/src/index.d.ts +9 -7
  36. package/dist/types/src/index.d.ts.map +1 -1
  37. package/dist/types/src/process/Process.d.ts +247 -0
  38. package/dist/types/src/process/Process.d.ts.map +1 -0
  39. package/dist/types/src/process/ServiceResolver.d.ts +74 -0
  40. package/dist/types/src/process/ServiceResolver.d.ts.map +1 -0
  41. package/dist/types/src/process/StorageService.d.ts +58 -0
  42. package/dist/types/src/process/StorageService.d.ts.map +1 -0
  43. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  44. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  45. package/dist/types/src/protocol/index.d.ts +2 -0
  46. package/dist/types/src/protocol/index.d.ts.map +1 -0
  47. package/dist/types/src/protocol/protocol.d.ts +7 -0
  48. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  49. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  50. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  51. package/dist/types/src/sdk.d.ts +14 -0
  52. package/dist/types/src/sdk.d.ts.map +1 -0
  53. package/dist/types/src/services/credentials.d.ts +22 -3
  54. package/dist/types/src/services/credentials.d.ts.map +1 -1
  55. package/dist/types/src/services/event-logger.d.ts +74 -30
  56. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  57. package/dist/types/src/services/function-invocation-service.d.ts +17 -0
  58. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -0
  59. package/dist/types/src/services/index.d.ts +5 -5
  60. package/dist/types/src/services/index.d.ts.map +1 -1
  61. package/dist/types/src/services/queues.d.ts +26 -7
  62. package/dist/types/src/services/queues.d.ts.map +1 -1
  63. package/dist/types/src/services/tracing.d.ts +93 -7
  64. package/dist/types/src/services/tracing.d.ts.map +1 -1
  65. package/dist/types/src/types/Script.d.ts +22 -0
  66. package/dist/types/src/types/Script.d.ts.map +1 -0
  67. package/dist/types/src/types/Trigger.d.ts +120 -0
  68. package/dist/types/src/types/Trigger.d.ts.map +1 -0
  69. package/dist/types/src/types/TriggerEvent.d.ts +75 -0
  70. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -0
  71. package/dist/types/src/types/index.d.ts +5 -0
  72. package/dist/types/src/types/index.d.ts.map +1 -0
  73. package/dist/types/src/types/url.d.ts +13 -0
  74. package/dist/types/src/types/url.d.ts.map +1 -0
  75. package/dist/types/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +32 -69
  77. package/src/Trace.ts +162 -0
  78. package/src/errors.ts +13 -5
  79. package/src/example/definitions.ts +48 -0
  80. package/src/example/fib.ts +22 -0
  81. package/src/example/forex-effect.ts +40 -0
  82. package/src/example/index.ts +12 -0
  83. package/src/example/reply.ts +18 -0
  84. package/src/example/sleep.ts +15 -0
  85. package/src/index.ts +9 -9
  86. package/src/process/Process.ts +457 -0
  87. package/src/process/ServiceResolver.ts +173 -0
  88. package/src/process/StorageService.ts +99 -0
  89. package/src/protocol/functions-ai-http-client.ts +67 -0
  90. package/src/{executor → protocol}/index.ts +1 -1
  91. package/src/protocol/protocol.test.ts +59 -0
  92. package/src/protocol/protocol.ts +268 -0
  93. package/src/sdk.ts +39 -0
  94. package/src/services/credentials.ts +101 -3
  95. package/src/services/event-logger.ts +77 -37
  96. package/src/services/function-invocation-service.ts +38 -0
  97. package/src/services/index.ts +5 -5
  98. package/src/services/queues.ts +46 -11
  99. package/src/services/tracing.ts +172 -14
  100. package/src/types/Script.ts +38 -0
  101. package/src/types/Trigger.ts +154 -0
  102. package/src/types/TriggerEvent.ts +62 -0
  103. package/src/types/index.ts +8 -0
  104. package/src/types/url.ts +32 -0
  105. package/dist/lib/browser/bundler/index.mjs +0 -247
  106. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  107. package/dist/lib/browser/chunk-3NGCSUEW.mjs +0 -328
  108. package/dist/lib/browser/chunk-3NGCSUEW.mjs.map +0 -7
  109. package/dist/lib/browser/edge/index.mjs +0 -69
  110. package/dist/lib/browser/edge/index.mjs.map +0 -7
  111. package/dist/lib/browser/index.mjs +0 -503
  112. package/dist/lib/browser/index.mjs.map +0 -7
  113. package/dist/lib/browser/meta.json +0 -1
  114. package/dist/lib/browser/testing/index.mjs +0 -91
  115. package/dist/lib/browser/testing/index.mjs.map +0 -7
  116. package/dist/lib/node-esm/bundler/index.mjs +0 -249
  117. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  118. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs +0 -330
  119. package/dist/lib/node-esm/chunk-FJ2MU7TL.mjs.map +0 -7
  120. package/dist/lib/node-esm/edge/index.mjs +0 -71
  121. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  122. package/dist/lib/node-esm/index.mjs +0 -504
  123. package/dist/lib/node-esm/index.mjs.map +0 -7
  124. package/dist/lib/node-esm/meta.json +0 -1
  125. package/dist/lib/node-esm/testing/index.mjs +0 -92
  126. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  127. package/dist/types/src/bundler/bundler.d.ts +0 -50
  128. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  129. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  130. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  131. package/dist/types/src/bundler/index.d.ts +0 -2
  132. package/dist/types/src/bundler/index.d.ts.map +0 -1
  133. package/dist/types/src/edge/functions.d.ts +0 -16
  134. package/dist/types/src/edge/functions.d.ts.map +0 -1
  135. package/dist/types/src/edge/index.d.ts +0 -2
  136. package/dist/types/src/edge/index.d.ts.map +0 -1
  137. package/dist/types/src/executor/executor.d.ts +0 -8
  138. package/dist/types/src/executor/executor.d.ts.map +0 -1
  139. package/dist/types/src/executor/index.d.ts +0 -2
  140. package/dist/types/src/executor/index.d.ts.map +0 -1
  141. package/dist/types/src/handler.d.ts +0 -62
  142. package/dist/types/src/handler.d.ts.map +0 -1
  143. package/dist/types/src/schema.d.ts +0 -38
  144. package/dist/types/src/schema.d.ts.map +0 -1
  145. package/dist/types/src/services/database.d.ts +0 -29
  146. package/dist/types/src/services/database.d.ts.map +0 -1
  147. package/dist/types/src/services/function-call-service.d.ts +0 -16
  148. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  149. package/dist/types/src/services/service-container.d.ts +0 -56
  150. package/dist/types/src/services/service-container.d.ts.map +0 -1
  151. package/dist/types/src/services/service-registry.d.ts +0 -29
  152. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  153. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  154. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  155. package/dist/types/src/testing/index.d.ts +0 -3
  156. package/dist/types/src/testing/index.d.ts.map +0 -1
  157. package/dist/types/src/testing/layer.d.ts +0 -10
  158. package/dist/types/src/testing/layer.d.ts.map +0 -1
  159. package/dist/types/src/testing/logger.d.ts +0 -5
  160. package/dist/types/src/testing/logger.d.ts.map +0 -1
  161. package/dist/types/src/testing/services.d.ts +0 -70
  162. package/dist/types/src/testing/services.d.ts.map +0 -1
  163. package/dist/types/src/trace.d.ts +0 -124
  164. package/dist/types/src/trace.d.ts.map +0 -1
  165. package/dist/types/src/translations.d.ts +0 -12
  166. package/dist/types/src/translations.d.ts.map +0 -1
  167. package/dist/types/src/types.d.ts +0 -411
  168. package/dist/types/src/types.d.ts.map +0 -1
  169. package/dist/types/src/url.d.ts +0 -17
  170. package/dist/types/src/url.d.ts.map +0 -1
  171. package/src/bundler/bundler.test.ts +0 -59
  172. package/src/bundler/bundler.ts +0 -292
  173. package/src/bundler/index.ts +0 -5
  174. package/src/edge/functions.ts +0 -64
  175. package/src/edge/index.ts +0 -9
  176. package/src/executor/executor.ts +0 -54
  177. package/src/handler.ts +0 -120
  178. package/src/schema.ts +0 -57
  179. package/src/services/database.ts +0 -70
  180. package/src/services/function-call-service.ts +0 -64
  181. package/src/services/service-container.ts +0 -113
  182. package/src/services/service-registry.test.ts +0 -42
  183. package/src/services/service-registry.ts +0 -56
  184. package/src/testing/index.ts +0 -6
  185. package/src/testing/layer.ts +0 -31
  186. package/src/testing/logger.ts +0 -16
  187. package/src/testing/services.ts +0 -168
  188. package/src/trace.ts +0 -180
  189. package/src/translations.ts +0 -20
  190. package/src/types.ts +0 -211
  191. package/src/url.ts +0 -52
@@ -0,0 +1,1245 @@
1
+ import {
2
+ EventType,
3
+ Trace_exports,
4
+ writerLayerNoop
5
+ } from "./chunk-BHLSCAA2.mjs";
6
+ import {
7
+ Fibonacci,
8
+ Reply,
9
+ Sleep
10
+ } from "./chunk-Z2XDJJVH.mjs";
11
+ import {
12
+ __export
13
+ } from "./chunk-J5LGTIGS.mjs";
14
+
15
+ // src/errors.ts
16
+ import { BaseError } from "@dxos/errors";
17
+ var ServiceNotAvailableError = class extends BaseError.extend("ServiceNotAvailable", "Service not available") {
18
+ constructor(service, options) {
19
+ super({
20
+ context: {
21
+ service
22
+ },
23
+ ...options,
24
+ message: `Service not available: ${service}`
25
+ });
26
+ }
27
+ };
28
+ var FunctionNotFoundError = class extends BaseError.extend("FunctionNotFound", "Function not found") {
29
+ constructor(functionKey, options) {
30
+ super({
31
+ context: {
32
+ function: functionKey
33
+ },
34
+ ...options
35
+ });
36
+ }
37
+ };
38
+ var FunctionError = class extends BaseError.extend("FunctionError", "Function invocation error") {
39
+ };
40
+ var TriggerStateNotFoundError = class extends BaseError.extend("TriggerStateNotFound", "Trigger state not found") {
41
+ };
42
+
43
+ // src/example/index.ts
44
+ import { OperationHandlerSet } from "@dxos/operation";
45
+ var ExampleHandlers = OperationHandlerSet.lazy(() => import("./fib-S6PPI4UW.mjs"), () => import("./reply-TOHXEG7V.mjs"), () => import("./sleep-QPSZDPEH.mjs"));
46
+
47
+ // src/process/Process.ts
48
+ var Process_exports = {};
49
+ __export(Process_exports, {
50
+ ExitedEvent: () => ExitedEvent,
51
+ ID: () => ID,
52
+ ProcessMonitorService: () => ProcessMonitorService,
53
+ ProcessTypeId: () => ProcessTypeId,
54
+ SpawnedEvent: () => SpawnedEvent,
55
+ State: () => State,
56
+ fromOperation: () => fromOperation,
57
+ isProcess: () => isProcess,
58
+ make: () => make,
59
+ prettyProcessTree: () => prettyProcessTree
60
+ });
61
+ import * as Effect from "effect/Effect";
62
+ import * as Schema from "effect/Schema";
63
+ import * as Context from "effect/Context";
64
+ import { OperationHandlerSet as OperationHandlerSet2 } from "@dxos/operation";
65
+ import { assertArgument } from "@dxos/invariant";
66
+ var ID = Schema.String.pipe(Schema.brand("ProcessId"));
67
+ var ProcessTypeId = "~@dxos/functions/Process";
68
+ var isProcess = (executable) => typeof executable === "object" && executable !== null && ProcessTypeId in executable;
69
+ var make = (opts, create) => {
70
+ assertArgument(/^[a-z0-9]([a-z0-9.\-/]*[a-z0-9])?$/i.test(opts.key), "key", "Invalid key");
71
+ return {
72
+ [ProcessTypeId]: {},
73
+ ...opts,
74
+ create: (ctx) => create(ctx).pipe(Effect.map((partial) => ({
75
+ onSpawn: () => Effect.void,
76
+ onInput: () => Effect.void,
77
+ onAlarm: () => Effect.void,
78
+ onChildEvent: () => Effect.void,
79
+ ...partial
80
+ })))
81
+ };
82
+ };
83
+ var fromOperation = (op, handler) => make({
84
+ key: op.meta.key,
85
+ input: op.input,
86
+ output: op.output,
87
+ services: op.services
88
+ }, (ctx) => Effect.gen(function* () {
89
+ const semaphore = yield* Effect.makeSemaphore(1);
90
+ return {
91
+ onInput: (input) => Effect.gen(function* () {
92
+ const opHandler = yield* OperationHandlerSet2.getHandler(handler, op).pipe(Effect.orDie);
93
+ const output = yield* opHandler.handler(input).pipe(Effect.orDie);
94
+ ctx.submitOutput(output);
95
+ ctx.succeed();
96
+ }).pipe(semaphore.withPermits(1))
97
+ };
98
+ }));
99
+ var State = /* @__PURE__ */ (function(State2) {
100
+ State2["RUNNING"] = "RUNNING";
101
+ State2["HYBERNATING"] = "HYBERNATING";
102
+ State2["IDLE"] = "IDLE";
103
+ State2["TERMINATING"] = "TERMINATING";
104
+ State2["TERMINATED"] = "TERMINATED";
105
+ State2["SUCCEEDED"] = "SUCCEEDED";
106
+ State2["FAILED"] = "FAILED";
107
+ return State2;
108
+ })({});
109
+ var ProcessMonitorService = class extends Context.Tag("@dxos/functions/ProcessMonitorService")() {
110
+ };
111
+ var SpawnedEvent = EventType("process.spawned", {
112
+ schema: Schema.Void,
113
+ isEphemeral: false
114
+ });
115
+ var ExitedEvent = EventType("process.exited", {
116
+ schema: Schema.Struct({
117
+ outcome: Schema.Literal("succeeded", "failed", "terminated")
118
+ }),
119
+ isEphemeral: false
120
+ });
121
+ var prettyProcessTree = (tree) => {
122
+ if (tree.length === 0) {
123
+ return "";
124
+ }
125
+ const pidSet = new Set(tree.map((node) => node.pid));
126
+ const childrenByParent = /* @__PURE__ */ new Map();
127
+ const roots = [];
128
+ for (const node of tree) {
129
+ const parent = node.parentPid;
130
+ if (parent === null || !pidSet.has(parent)) {
131
+ roots.push(node);
132
+ continue;
133
+ }
134
+ const key2 = String(parent);
135
+ const siblings = childrenByParent.get(key2) ?? [];
136
+ siblings.push(node);
137
+ childrenByParent.set(key2, siblings);
138
+ }
139
+ const byPid = (a, b) => String(a.pid).localeCompare(String(b.pid));
140
+ roots.sort(byPid);
141
+ for (const siblings of childrenByParent.values()) {
142
+ siblings.sort(byPid);
143
+ }
144
+ const formatLabel = (node) => {
145
+ const idShort = String(node.pid).slice(0, 6);
146
+ const parts = [
147
+ idShort,
148
+ node.state
149
+ ];
150
+ if (node.params.name != null && node.params.name !== "") {
151
+ parts.push(node.params.name);
152
+ }
153
+ if (node.error != null) {
154
+ parts.push(`(${node.error})`);
155
+ }
156
+ const { inputCount, outputCount, wallTime } = node.metrics;
157
+ parts.push(`[in:${inputCount} out:${outputCount} wall:${Math.round(wallTime)}ms]`);
158
+ return parts.join(" ");
159
+ };
160
+ const lines = [];
161
+ const walk = (node, prefix, isLast, isRoot) => {
162
+ if (isRoot) {
163
+ lines.push(`- ${formatLabel(node)}`);
164
+ } else {
165
+ const branch = isLast ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 ";
166
+ lines.push(`${prefix}${branch}${formatLabel(node)}`);
167
+ }
168
+ const children = childrenByParent.get(String(node.pid)) ?? [];
169
+ const nextPrefix = isRoot ? " " : `${prefix}${isLast ? " " : "\u2502 "}`;
170
+ children.forEach((child, index) => {
171
+ walk(child, nextPrefix, index === children.length - 1, false);
172
+ });
173
+ };
174
+ for (const root of roots) {
175
+ walk(root, "", true, true);
176
+ }
177
+ return lines.join("\n");
178
+ };
179
+
180
+ // src/process/ServiceResolver.ts
181
+ var ServiceResolver_exports = {};
182
+ __export(ServiceResolver_exports, {
183
+ ServiceResolver: () => ServiceResolver,
184
+ compose: () => compose,
185
+ empty: () => empty2,
186
+ fromContext: () => fromContext,
187
+ fromRequirements: () => fromRequirements,
188
+ layerRequirements: () => layerRequirements,
189
+ make: () => make3,
190
+ resolve: () => resolve,
191
+ resolveAll: () => resolveAll,
192
+ succeed: () => succeed
193
+ });
194
+ import * as Context2 from "effect/Context";
195
+ import * as Effect2 from "effect/Effect";
196
+ import * as Layer from "effect/Layer";
197
+ import * as Option from "effect/Option";
198
+ import * as Either from "effect/Either";
199
+ var ServiceResolverTypeId = "~@dxos/functions/ServiceResolver";
200
+ var ServiceResolver = Context2.GenericTag("@dxos/functions/ServiceResolver");
201
+ var resolve = Effect2.serviceFunctionEffect(ServiceResolver, (_) => _.resolve);
202
+ var resolveAll = (tags, context) => Effect2.gen(function* () {
203
+ const services = yield* Effect2.forEach(tags, (tag) => resolve(tag, context).pipe(Effect2.map((service) => Context2.make(tag, service))));
204
+ return Context2.mergeAll(...services);
205
+ });
206
+ var succeed = (tag, getService) => {
207
+ return make3((tag1, context) => {
208
+ if (tag1.key !== tag.key) {
209
+ return Effect2.fail(new ServiceNotAvailableError(`Service not available: ${String(tag.key ?? tag)}`));
210
+ }
211
+ const service = getService(context);
212
+ return service;
213
+ });
214
+ };
215
+ var make3 = (resolveFn) => ({
216
+ [ServiceResolverTypeId]: ServiceResolverTypeId,
217
+ resolve: resolveFn
218
+ });
219
+ var fromContext = (ctx) => make3((tag, context) => Effect2.gen(function* () {
220
+ const service = Context2.getOption(ctx, tag);
221
+ if (Option.isNone(service)) {
222
+ return yield* Effect2.fail(new ServiceNotAvailableError(String(tag.key ?? tag)));
223
+ }
224
+ return service.value;
225
+ }));
226
+ var fromRequirements = (...tags) => Effect2.contextWith((parentCtx) => {
227
+ const available = new Set(tags.map((tag) => tag.key));
228
+ return make3((tag, context) => Effect2.gen(function* () {
229
+ let result = Context2.empty();
230
+ if (!available.has(tag.key)) {
231
+ return yield* Effect2.fail(new ServiceNotAvailableError(String(tag.key ?? tag)));
232
+ }
233
+ const service = Context2.getOption(parentCtx, tag);
234
+ if (Option.isNone(service)) {
235
+ return yield* Effect2.fail(new ServiceNotAvailableError(String(tag.key ?? tag)));
236
+ }
237
+ return service.value;
238
+ }));
239
+ });
240
+ var layerRequirements = (...tags) => Layer.effect(ServiceResolver, fromRequirements(...tags));
241
+ var compose = (...resolvers) => make3((tag, context) => Effect2.gen(function* () {
242
+ for (const resolver of resolvers) {
243
+ const single = yield* resolver.resolve(tag, context).pipe(Effect2.either);
244
+ if (Either.isRight(single)) {
245
+ return single.right;
246
+ }
247
+ }
248
+ return yield* Effect2.fail(new ServiceNotAvailableError(String(tag.key ?? tag)));
249
+ }));
250
+ var empty2 = make3((tag, context) => {
251
+ return Effect2.fail(new ServiceNotAvailableError(String(tag.key ?? tag)));
252
+ });
253
+
254
+ // src/process/StorageService.ts
255
+ import * as Pipeable from "effect/Pipeable";
256
+ import * as Context3 from "effect/Context";
257
+ import * as Effect3 from "effect/Effect";
258
+ import * as Option2 from "effect/Option";
259
+ var StorageService = class extends Context3.Tag("@dxos/functions/StorageService")() {
260
+ };
261
+ var get = Effect3.serviceFunctionEffect(StorageService, (_) => _.get);
262
+ var set = Effect3.serviceFunctionEffect(StorageService, (_) => _.set);
263
+ var deleteKey = Effect3.serviceFunctionEffect(StorageService, (_) => _.delete);
264
+ var list = Effect3.serviceFunctionEffect(StorageService, (_) => _.list);
265
+ var clear = Effect3.serviceFunctionEffect(StorageService, (_) => _.clear);
266
+ var key = (schema, key2) => {
267
+ return {
268
+ key: key2,
269
+ get: get(schema, key2),
270
+ set: (value2) => set(schema, key2, value2),
271
+ delete: () => deleteKey(key2),
272
+ pipe(...args) {
273
+ return Pipeable.pipeArguments(this, arguments);
274
+ }
275
+ };
276
+ };
277
+ var withDefault = (getDefault) => (key2) => {
278
+ return {
279
+ key: key2.key,
280
+ get: key2.get.pipe(Effect3.map(Option2.getOrElse(() => getDefault()))),
281
+ set: (value2) => key2.set(value2),
282
+ delete: () => key2.delete(),
283
+ pipe(...args) {
284
+ return Pipeable.pipeArguments(this, arguments);
285
+ }
286
+ };
287
+ };
288
+
289
+ // src/services/credentials.ts
290
+ import * as HttpClient from "@effect/platform/HttpClient";
291
+ import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
292
+ import * as Context4 from "effect/Context";
293
+ import * as Effect4 from "effect/Effect";
294
+ import * as Layer2 from "effect/Layer";
295
+ import * as Redacted from "effect/Redacted";
296
+ import { Query } from "@dxos/echo";
297
+ import { Database } from "@dxos/echo";
298
+ import { AccessToken } from "@dxos/types";
299
+ var CredentialsService = class _CredentialsService extends Context4.Tag("@dxos/functions/CredentialsService")() {
300
+ static getCredential = (query) => Effect4.gen(function* () {
301
+ const credentials = yield* _CredentialsService;
302
+ return yield* Effect4.promise(() => credentials.getCredential(query));
303
+ });
304
+ static getApiKey = (query) => Effect4.gen(function* () {
305
+ const credential = yield* _CredentialsService.getCredential(query);
306
+ if (!credential.apiKey) {
307
+ throw new Error(`API key not found for service: ${query.service}`);
308
+ }
309
+ return Redacted.make(credential.apiKey);
310
+ });
311
+ static configuredLayer = (credentials) => Layer2.succeed(_CredentialsService, new ConfiguredCredentialsService(credentials));
312
+ static layerConfig = (credentials) => Layer2.effect(_CredentialsService, Effect4.gen(function* () {
313
+ const serviceCredentials = yield* Effect4.forEach(credentials, ({ service, apiKey }) => Effect4.gen(function* () {
314
+ return {
315
+ service,
316
+ apiKey: Redacted.value(yield* apiKey)
317
+ };
318
+ }));
319
+ return new ConfiguredCredentialsService(serviceCredentials);
320
+ }));
321
+ static layerFromDatabase = ({ caching = false } = {}) => Layer2.effect(_CredentialsService, Effect4.gen(function* () {
322
+ const dbService = yield* Database.Service;
323
+ const cache = /* @__PURE__ */ new Map();
324
+ const queryCredentials = async (query) => {
325
+ const cacheKey = JSON.stringify(query);
326
+ if (caching && cache.has(cacheKey)) {
327
+ return cache.get(cacheKey);
328
+ }
329
+ const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
330
+ const credentials = accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
331
+ service: accessToken.source,
332
+ apiKey: accessToken.token
333
+ }));
334
+ if (caching) {
335
+ cache.set(cacheKey, credentials);
336
+ }
337
+ return credentials;
338
+ };
339
+ return {
340
+ getCredential: async (query) => {
341
+ const credentials = await queryCredentials(query);
342
+ if (credentials.length === 0) {
343
+ throw new Error(`Credential not found for service: ${query.service}`);
344
+ }
345
+ return credentials[0];
346
+ },
347
+ queryCredentials: async (query) => {
348
+ return queryCredentials(query);
349
+ }
350
+ };
351
+ }));
352
+ };
353
+ var ConfiguredCredentialsService = class {
354
+ credentials;
355
+ constructor(credentials = []) {
356
+ this.credentials = credentials;
357
+ }
358
+ addCredentials(credentials) {
359
+ this.credentials.push(...credentials);
360
+ return this;
361
+ }
362
+ async queryCredentials(query) {
363
+ return this.credentials.filter((credential) => credential.service === query.service);
364
+ }
365
+ async getCredential(query) {
366
+ const credential = this.credentials.find((credential2) => credential2.service === query.service);
367
+ if (!credential) {
368
+ throw new Error(`Credential not found for service: ${query.service}`);
369
+ }
370
+ return credential;
371
+ }
372
+ };
373
+ var withAuthorization = (token, kind) => HttpClient.mapRequest((request) => {
374
+ const authorization = kind ? `${kind} ${token}` : token;
375
+ return HttpClientRequest.setHeader(request, "Authorization", authorization);
376
+ });
377
+
378
+ // src/services/event-logger.ts
379
+ import * as Context6 from "effect/Context";
380
+ import * as Effect6 from "effect/Effect";
381
+ import * as Layer4 from "effect/Layer";
382
+ import * as Schema2 from "effect/Schema";
383
+ import { Obj as Obj2, Type } from "@dxos/echo";
384
+ import { invariant } from "@dxos/invariant";
385
+ import { LogLevel, log } from "@dxos/log";
386
+
387
+ // src/services/tracing.ts
388
+ import * as Context5 from "effect/Context";
389
+ import * as Effect5 from "effect/Effect";
390
+ import * as Layer3 from "effect/Layer";
391
+ import { AgentStatus } from "@dxos/ai";
392
+ import { Obj } from "@dxos/echo";
393
+ import { ObjectId } from "@dxos/keys";
394
+ import { Message } from "@dxos/types";
395
+ var TracingService = class _TracingService extends Context5.Tag("@dxos/functions/TracingService")() {
396
+ static noop = {
397
+ getTraceContext: () => ({}),
398
+ write: () => {
399
+ },
400
+ ephemeral: () => {
401
+ },
402
+ traceInvocationStart: () => Effect5.sync(() => ({
403
+ invocationId: ObjectId.random(),
404
+ invocationTraceQueue: void 0
405
+ })),
406
+ traceInvocationEnd: () => Effect5.sync(() => {
407
+ })
408
+ };
409
+ static layerNoop = Layer3.succeed(_TracingService, _TracingService.noop);
410
+ /**
411
+ * Creates a TracingService layer that emits events to the parent tracing service.
412
+ */
413
+ static layerSubframe = (mapContext) => Layer3.effect(_TracingService, Effect5.gen(function* () {
414
+ const tracing = yield* _TracingService;
415
+ const context = mapContext(tracing.getTraceContext());
416
+ return {
417
+ write: (event, context2) => tracing.write(event, context2),
418
+ ephemeral: (event, context2) => tracing.ephemeral(event, context2),
419
+ getTraceContext: () => context,
420
+ traceInvocationStart: () => Effect5.die("Tracing invocation inside another invocation is not supported."),
421
+ traceInvocationEnd: () => Effect5.die("Tracing invocation inside another invocation is not supported.")
422
+ };
423
+ }));
424
+ /**
425
+ * Create sublayer to trace an invocation.
426
+ * @param data
427
+ * @returns
428
+ */
429
+ static layerInvocation = (data) => _TracingService.layerSubframe((context) => ({
430
+ ...context,
431
+ currentInvocation: data
432
+ }));
433
+ /**
434
+ * Emit the current human-readable execution status.
435
+ */
436
+ static emitStatus = Effect5.fnUntraced(function* (data) {
437
+ const tracing = yield* _TracingService;
438
+ tracing.write(Obj.make(AgentStatus, {
439
+ parentMessage: tracing.getTraceContext().parentMessage,
440
+ toolCallId: tracing.getTraceContext().toolCallId,
441
+ created: (/* @__PURE__ */ new Date()).toISOString(),
442
+ ...data
443
+ }), tracing.getTraceContext());
444
+ });
445
+ static emitConverationMessage = Effect5.fnUntraced(function* (data) {
446
+ const tracing = yield* _TracingService;
447
+ tracing.write(Obj.make(Message.Message, {
448
+ parentMessage: tracing.getTraceContext().parentMessage,
449
+ ...data,
450
+ properties: {
451
+ [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
452
+ ...data.properties
453
+ }
454
+ }), tracing.getTraceContext());
455
+ });
456
+ static emitEphemeralMessage = Effect5.fnUntraced(function* (data) {
457
+ const tracing = yield* _TracingService;
458
+ tracing.ephemeral(data, tracing.getTraceContext());
459
+ });
460
+ };
461
+ var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
462
+
463
+ // src/services/event-logger.ts
464
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
465
+ var ComputeEventPayload = Schema2.Union(Schema2.Struct({
466
+ type: Schema2.Literal("begin-compute"),
467
+ nodeId: Schema2.String,
468
+ /**
469
+ * Names of the inputs begin computed.
470
+ */
471
+ inputs: Schema2.Array(Schema2.String)
472
+ }), Schema2.Struct({
473
+ type: Schema2.Literal("end-compute"),
474
+ nodeId: Schema2.String,
475
+ /**
476
+ * Names of the outputs computed.
477
+ */
478
+ outputs: Schema2.Array(Schema2.String)
479
+ }), Schema2.Struct({
480
+ type: Schema2.Literal("compute-input"),
481
+ nodeId: Schema2.String,
482
+ property: Schema2.String,
483
+ value: Schema2.Any
484
+ }), Schema2.Struct({
485
+ type: Schema2.Literal("compute-output"),
486
+ nodeId: Schema2.String,
487
+ property: Schema2.String,
488
+ value: Schema2.Any
489
+ }), Schema2.Struct({
490
+ type: Schema2.Literal("custom"),
491
+ nodeId: Schema2.String,
492
+ event: Schema2.Any
493
+ }));
494
+ var ComputeEvent = Schema2.Struct({
495
+ payload: ComputeEventPayload
496
+ }).pipe(Type.object({
497
+ typename: "org.dxos.type.computeEvent",
498
+ version: "0.1.0"
499
+ }));
500
+ var ComputeEventLogger = class _ComputeEventLogger extends Context6.Tag("@dxos/functions/ComputeEventLogger")() {
501
+ static noop = {
502
+ log: () => {
503
+ },
504
+ nodeId: void 0
505
+ };
506
+ /**
507
+ * Implements ComputeEventLogger using TracingService.
508
+ */
509
+ static layerFromTracing = Layer4.effect(_ComputeEventLogger, Effect6.gen(function* () {
510
+ const tracing = yield* TracingService;
511
+ return {
512
+ log: (event) => {
513
+ tracing.write(Obj2.make(ComputeEvent, {
514
+ payload: event
515
+ }), tracing.getTraceContext());
516
+ },
517
+ nodeId: void 0
518
+ };
519
+ }));
520
+ };
521
+ var logCustomEvent = (data) => Effect6.gen(function* () {
522
+ const logger = yield* ComputeEventLogger;
523
+ if (!logger.nodeId) {
524
+ throw new Error("logCustomEvent must be called within a node compute function");
525
+ }
526
+ logger.log({
527
+ type: "custom",
528
+ nodeId: logger.nodeId,
529
+ event: data
530
+ });
531
+ });
532
+ var createDefectLogger = () => Effect6.catchAll((error) => Effect6.gen(function* () {
533
+ log.error("unhandled effect error", {
534
+ error
535
+ }, {
536
+ F: __dxlog_file,
537
+ L: 102,
538
+ S: this,
539
+ C: (f, a) => f(...a)
540
+ });
541
+ throw error;
542
+ }));
543
+ var createEventLogger = (level, message = "event") => {
544
+ const logFunction = {
545
+ [LogLevel.WARN]: log.warn,
546
+ [LogLevel.VERBOSE]: log.verbose,
547
+ [LogLevel.DEBUG]: log.debug,
548
+ [LogLevel.INFO]: log.info,
549
+ [LogLevel.ERROR]: log.error
550
+ }[level];
551
+ invariant(logFunction, void 0, {
552
+ F: __dxlog_file,
553
+ L: 120,
554
+ S: void 0,
555
+ A: [
556
+ "logFunction",
557
+ ""
558
+ ]
559
+ });
560
+ return {
561
+ log: (event) => {
562
+ logFunction(message, event);
563
+ },
564
+ nodeId: void 0
565
+ };
566
+ };
567
+
568
+ // src/services/function-invocation-service.ts
569
+ import * as Context7 from "effect/Context";
570
+ import * as Effect7 from "effect/Effect";
571
+ import * as Layer5 from "effect/Layer";
572
+ var FunctionInvocationService = class _FunctionInvocationService extends Context7.Tag("@dxos/functions/FunctionInvocationService")() {
573
+ static layerNotAvailable = Layer5.succeed(_FunctionInvocationService, {
574
+ invokeFunction: () => Effect7.die("FunctionInvocationService is not avaialble."),
575
+ resolveFunction: () => Effect7.die("FunctionInvocationService is not available.")
576
+ });
577
+ static invokeFunction = (functionDef, input) => Effect7.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
578
+ static resolveFunction = (key2) => Effect7.serviceFunctionEffect(_FunctionInvocationService, (service) => service.resolveFunction)(key2);
579
+ };
580
+
581
+ // src/services/queues.ts
582
+ import * as Context8 from "effect/Context";
583
+ import * as Effect8 from "effect/Effect";
584
+ import * as Layer6 from "effect/Layer";
585
+ import { createFeedServiceLayer } from "@dxos/echo-db";
586
+ var QueueService = class _QueueService extends Context8.Tag("@dxos/functions/QueueService")() {
587
+ static notAvailable = Layer6.succeed(_QueueService, {
588
+ queues: {
589
+ get(_dxn) {
590
+ throw new Error("Queues not available");
591
+ },
592
+ create() {
593
+ throw new Error("Queues not available");
594
+ }
595
+ },
596
+ queue: void 0
597
+ });
598
+ static make = (queues, queue) => {
599
+ return {
600
+ queues,
601
+ queue
602
+ };
603
+ };
604
+ static layer = (queues, queue) => Layer6.succeed(_QueueService, _QueueService.make(queues, queue));
605
+ /**
606
+ * Gets a queue by its DXN.
607
+ */
608
+ static getQueue = (dxn) => _QueueService.pipe(Effect8.map(({ queues }) => queues.get(dxn)));
609
+ /**
610
+ * Creates a new queue.
611
+ */
612
+ static createQueue = (options) => _QueueService.pipe(Effect8.map(({ queues }) => queues.create(options)));
613
+ static append = (queue, objects) => Effect8.promise(() => queue.append(objects));
614
+ };
615
+ var ContextQueueService = class _ContextQueueService extends Context8.Tag("@dxos/functions/ContextQueueService")() {
616
+ static layer = (queue) => Layer6.succeed(_ContextQueueService, {
617
+ queue
618
+ });
619
+ };
620
+ var feedServiceFromQueueServiceLayer = Layer6.unwrapEffect(Effect8.gen(function* () {
621
+ const { queues } = yield* QueueService;
622
+ return createFeedServiceLayer(queues);
623
+ }));
624
+
625
+ // src/types/Script.ts
626
+ var Script_exports = {};
627
+ __export(Script_exports, {
628
+ Script: () => Script,
629
+ make: () => make5
630
+ });
631
+ import * as Schema3 from "effect/Schema";
632
+ import { Annotation, Obj as Obj3, Ref, Type as Type2 } from "@dxos/echo";
633
+ import { FormInputAnnotation } from "@dxos/echo/internal";
634
+ import { Text } from "@dxos/schema";
635
+ var Script = Schema3.Struct({
636
+ name: Schema3.String.pipe(Schema3.optional),
637
+ description: Schema3.String.pipe(Schema3.optional),
638
+ // TODO(burdon): Change to hash of deployed content.
639
+ // Whether source has changed since last deploy.
640
+ changed: Schema3.Boolean.pipe(FormInputAnnotation.set(false), Schema3.optional),
641
+ source: Ref.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
642
+ }).pipe(Type2.object({
643
+ typename: "org.dxos.type.script",
644
+ version: "0.1.0"
645
+ }), Annotation.LabelAnnotation.set([
646
+ "name"
647
+ ]), Annotation.IconAnnotation.set({
648
+ icon: "ph--code--regular",
649
+ hue: "sky"
650
+ }));
651
+ var make5 = ({ source = "", ...props } = {}) => Obj3.make(Script, {
652
+ ...props,
653
+ source: Ref.make(Text.make({
654
+ content: source
655
+ }))
656
+ });
657
+
658
+ // src/types/Trigger.ts
659
+ var Trigger_exports = {};
660
+ __export(Trigger_exports, {
661
+ EmailSpec: () => EmailSpec,
662
+ Kinds: () => Kinds,
663
+ QueueSpec: () => QueueSpec,
664
+ Spec: () => Spec,
665
+ SubscriptionSpec: () => SubscriptionSpec,
666
+ TimerSpec: () => TimerSpec,
667
+ Trigger: () => Trigger,
668
+ WebhookSpec: () => WebhookSpec,
669
+ make: () => make6
670
+ });
671
+ import * as Schema4 from "effect/Schema";
672
+ import * as SchemaAST from "effect/SchemaAST";
673
+ import { Annotation as Annotation2, Obj as Obj4, QueryAST, Ref as Ref2, Type as Type3 } from "@dxos/echo";
674
+ import { OptionsAnnotationId, SystemTypeAnnotation } from "@dxos/echo/internal";
675
+ import { DXN } from "@dxos/keys";
676
+ var Kinds = [
677
+ "email",
678
+ "queue",
679
+ "subscription",
680
+ "timer",
681
+ "webhook"
682
+ ];
683
+ var kindLiteralAnnotations = {
684
+ title: "Kind"
685
+ };
686
+ var EmailSpec = Schema4.Struct({
687
+ kind: Schema4.Literal("email").annotations(kindLiteralAnnotations)
688
+ });
689
+ var QueueSpec = Schema4.Struct({
690
+ kind: Schema4.Literal("queue").annotations(kindLiteralAnnotations),
691
+ // TODO(dmaretskyi): Rename to `feed` and change to a reference.
692
+ queue: DXN.Schema
693
+ });
694
+ var SubscriptionSpec = Schema4.Struct({
695
+ kind: Schema4.Literal("subscription").annotations(kindLiteralAnnotations),
696
+ query: Schema4.Struct({
697
+ raw: Schema4.optional(Schema4.String.annotations({
698
+ title: "Query"
699
+ })),
700
+ ast: QueryAST.Query
701
+ }),
702
+ options: Schema4.optional(Schema4.Struct({
703
+ // Watch changes to object (not just creation).
704
+ deep: Schema4.optional(Schema4.Boolean.annotations({
705
+ title: "Nested"
706
+ })),
707
+ // Debounce changes (delay in ms).
708
+ delay: Schema4.optional(Schema4.Number.annotations({
709
+ title: "Delay"
710
+ }))
711
+ }).annotations({
712
+ title: "Options"
713
+ }))
714
+ });
715
+ var TimerSpec = Schema4.Struct({
716
+ kind: Schema4.Literal("timer").annotations(kindLiteralAnnotations),
717
+ cron: Schema4.String.annotations({
718
+ title: "Cron",
719
+ [SchemaAST.ExamplesAnnotationId]: [
720
+ "0 0 * * *"
721
+ ]
722
+ })
723
+ });
724
+ var WebhookSpec = Schema4.Struct({
725
+ kind: Schema4.Literal("webhook").annotations(kindLiteralAnnotations),
726
+ method: Schema4.optional(Schema4.String.annotations({
727
+ title: "Method",
728
+ [OptionsAnnotationId]: [
729
+ "GET",
730
+ "POST"
731
+ ]
732
+ })),
733
+ port: Schema4.optional(Schema4.Number.annotations({
734
+ title: "Port"
735
+ }))
736
+ });
737
+ var Spec = Schema4.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
738
+ title: "Trigger"
739
+ });
740
+ var TriggerSchema = Schema4.Struct({
741
+ /**
742
+ * Function or workflow to invoke.
743
+ */
744
+ // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
745
+ function: Schema4.optional(Ref2.Ref(Obj4.Unknown).annotations({
746
+ title: "Function"
747
+ })),
748
+ /**
749
+ * Only used for workflowSchema.
750
+ * Specifies the input node in the circuit.
751
+ * @deprecated Remove and enforce a single input node in all compute graphSchema.
752
+ */
753
+ inputNodeId: Schema4.optional(Schema4.String.annotations({
754
+ title: "Input Node ID"
755
+ })),
756
+ // TODO(burdon): NO BOOLEAN PROPERTIES (enabld/disabled/paused, etc.)
757
+ // Need lint rule; or agent rule to require PR review for "boolean" key word.
758
+ enabled: Schema4.optional(Schema4.Boolean.annotations({
759
+ title: "Enabled"
760
+ })),
761
+ spec: Schema4.optional(Spec),
762
+ concurrency: Schema4.optional(Schema4.Number.annotations({
763
+ title: "Concurrency",
764
+ default: 1,
765
+ description: "Maximum number of concurrent invocations of the trigger. For Feed triggers, this will process Feed items in parallel."
766
+ })),
767
+ /**
768
+ * Passed as the input data to the function.
769
+ * Must match the function's input schema.
770
+ *
771
+ * @example
772
+ * {
773
+ * item: '{{event.item}}',
774
+ * instructions: 'Summarize and perform entity-extraction'
775
+ * mailbox: { '/': 'dxn:echo:AAA:ZZZ' }
776
+ * }
777
+ */
778
+ input: Schema4.optional(Schema4.Record({
779
+ key: Schema4.String,
780
+ value: Schema4.Any
781
+ }))
782
+ }).pipe(Type3.object({
783
+ typename: "org.dxos.type.trigger",
784
+ version: "0.1.0"
785
+ }), Annotation2.IconAnnotation.set({
786
+ icon: "ph--lightning--regular",
787
+ hue: "yellow"
788
+ }), SystemTypeAnnotation.set(true));
789
+ var Trigger = TriggerSchema;
790
+ var make6 = (props) => Obj4.make(Trigger, props);
791
+
792
+ // src/types/TriggerEvent.ts
793
+ var TriggerEvent_exports = {};
794
+ __export(TriggerEvent_exports, {
795
+ EmailEvent: () => EmailEvent,
796
+ QueueEvent: () => QueueEvent,
797
+ SubscriptionEvent: () => SubscriptionEvent,
798
+ TimerEvent: () => TimerEvent,
799
+ TriggerEvent: () => TriggerEvent,
800
+ WebhookEvent: () => WebhookEvent
801
+ });
802
+ import * as Schema5 from "effect/Schema";
803
+ import { DXN as DXN2, Obj as Obj5, Ref as Ref3 } from "@dxos/echo";
804
+ var EmailEvent = Schema5.Struct({
805
+ from: Schema5.String,
806
+ to: Schema5.String,
807
+ subject: Schema5.String,
808
+ created: Schema5.String,
809
+ body: Schema5.String
810
+ });
811
+ var QueueEvent = Schema5.Struct({
812
+ queue: DXN2.Schema,
813
+ item: Schema5.Any,
814
+ cursor: Schema5.String
815
+ });
816
+ var SubscriptionEvent = Schema5.Struct({
817
+ /**
818
+ * Type of the mutation.
819
+ */
820
+ // TODO(dmaretskyi): Specify enum.
821
+ type: Schema5.String,
822
+ /**
823
+ * Reference to the object that was changed or created.
824
+ */
825
+ subject: Ref3.Ref(Obj5.Unknown),
826
+ /**
827
+ * @deprecated
828
+ */
829
+ changedObjectId: Schema5.optional(Schema5.String)
830
+ });
831
+ var TimerEvent = Schema5.Struct({
832
+ tick: Schema5.Number
833
+ });
834
+ var WebhookEvent = Schema5.Struct({
835
+ url: Schema5.String,
836
+ method: Schema5.Literal("GET", "POST"),
837
+ headers: Schema5.Record({
838
+ key: Schema5.String,
839
+ value: Schema5.String
840
+ }),
841
+ bodyText: Schema5.String
842
+ });
843
+ var TriggerEvent = Schema5.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);
844
+
845
+ // src/types/url.ts
846
+ var FUNCTIONS_META_KEY = "org.dxos.service.function";
847
+ var FUNCTIONS_PRESET_META_KEY = "org.dxos.service.function-preset";
848
+ var getUserFunctionIdInMetadata = (meta) => {
849
+ return meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY)?.id;
850
+ };
851
+ var setUserFunctionIdInMetadata = (meta, functionId) => {
852
+ const key2 = meta.keys.find((key3) => key3.source === FUNCTIONS_META_KEY);
853
+ if (key2) {
854
+ if (key2.id !== functionId) {
855
+ throw new Error("Metadata mismatch");
856
+ }
857
+ } else {
858
+ meta.keys.push({
859
+ source: FUNCTIONS_META_KEY,
860
+ id: functionId
861
+ });
862
+ }
863
+ };
864
+
865
+ // src/protocol/protocol.ts
866
+ import * as AnthropicClient from "@effect/ai-anthropic/AnthropicClient";
867
+ import * as Effect10 from "effect/Effect";
868
+ import * as Layer8 from "effect/Layer";
869
+ import * as Schema6 from "effect/Schema";
870
+ import * as SchemaAST2 from "effect/SchemaAST";
871
+ import { AiModelResolver, AiService } from "@dxos/ai";
872
+ import { AnthropicResolver } from "@dxos/ai/resolvers";
873
+ import { LifecycleState, Resource } from "@dxos/context";
874
+ import { Database as Database2, Feed, JsonSchema, Ref as Ref4 } from "@dxos/echo";
875
+ import { refFromEncodedReference } from "@dxos/echo/internal";
876
+ import { EchoClient, createFeedServiceLayer as createFeedServiceLayer2 } from "@dxos/echo-db";
877
+ import { runAndForwardErrors } from "@dxos/effect";
878
+ import { assertState, failedInvariant, invariant as invariant2 } from "@dxos/invariant";
879
+ import { PublicKey } from "@dxos/keys";
880
+ import { Operation } from "@dxos/operation";
881
+
882
+ // src/protocol/functions-ai-http-client.ts
883
+ import * as Headers from "@effect/platform/Headers";
884
+ import * as HttpClient2 from "@effect/platform/HttpClient";
885
+ import * as HttpClientError from "@effect/platform/HttpClientError";
886
+ import * as HttpClientResponse from "@effect/platform/HttpClientResponse";
887
+ import * as Effect9 from "effect/Effect";
888
+ import * as FiberRef from "effect/FiberRef";
889
+ import * as Layer7 from "effect/Layer";
890
+ import * as Stream from "effect/Stream";
891
+ import { log as log2 } from "@dxos/log";
892
+ import { ErrorCodec } from "@dxos/protocols";
893
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/functions-ai-http-client.ts";
894
+ var requestInitTagKey = "@effect/platform/FetchHttpClient/FetchOptions";
895
+ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
896
+ static make = (service) => HttpClient2.make((request, url, signal, fiber) => {
897
+ const context = fiber.getFiberRef(FiberRef.currentContext);
898
+ const options = context.unsafeMap.get(requestInitTagKey) ?? {};
899
+ const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers;
900
+ const send = (body) => Effect9.tryPromise({
901
+ try: () => service.fetch(new Request(url, {
902
+ ...options,
903
+ method: request.method,
904
+ headers,
905
+ body
906
+ })),
907
+ catch: (cause) => {
908
+ log2.error("Failed to fetch", {
909
+ errorSerialized: ErrorCodec.encode(cause)
910
+ }, {
911
+ F: __dxlog_file2,
912
+ L: 43,
913
+ S: this,
914
+ C: (f, a) => f(...a)
915
+ });
916
+ return new HttpClientError.RequestError({
917
+ request,
918
+ reason: "Transport",
919
+ cause
920
+ });
921
+ }
922
+ }).pipe(Effect9.map((response) => HttpClientResponse.fromWeb(request, response)));
923
+ switch (request.body._tag) {
924
+ case "Raw":
925
+ case "Uint8Array":
926
+ return send(request.body.body);
927
+ case "FormData":
928
+ return send(request.body.formData);
929
+ case "Stream":
930
+ return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect9.flatMap(send));
931
+ }
932
+ return send(void 0);
933
+ });
934
+ static layer = (service) => Layer7.succeed(HttpClient2.HttpClient, _FunctionsAiHttpClient.make(service));
935
+ };
936
+
937
+ // src/protocol/protocol.ts
938
+ function _ts_add_disposable_resource(env, value2, async) {
939
+ if (value2 !== null && value2 !== void 0) {
940
+ if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
941
+ var dispose, inner;
942
+ if (async) {
943
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
944
+ dispose = value2[Symbol.asyncDispose];
945
+ }
946
+ if (dispose === void 0) {
947
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
948
+ dispose = value2[Symbol.dispose];
949
+ if (async) inner = dispose;
950
+ }
951
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
952
+ if (inner) dispose = function() {
953
+ try {
954
+ inner.call(this);
955
+ } catch (e) {
956
+ return Promise.reject(e);
957
+ }
958
+ };
959
+ env.stack.push({
960
+ value: value2,
961
+ dispose,
962
+ async
963
+ });
964
+ } else if (async) {
965
+ env.stack.push({
966
+ async: true
967
+ });
968
+ }
969
+ return value2;
970
+ }
971
+ function _ts_dispose_resources(env) {
972
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
973
+ var e = new Error(message);
974
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
975
+ };
976
+ return (_ts_dispose_resources = function _ts_dispose_resources2(env2) {
977
+ function fail2(e) {
978
+ env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
979
+ env2.hasError = true;
980
+ }
981
+ var r, s = 0;
982
+ function next() {
983
+ while (r = env2.stack.pop()) {
984
+ try {
985
+ if (!r.async && s === 1) return s = 0, env2.stack.push(r), Promise.resolve().then(next);
986
+ if (r.dispose) {
987
+ var result = r.dispose.call(r.value);
988
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
989
+ fail2(e);
990
+ return next();
991
+ });
992
+ } else s |= 1;
993
+ } catch (e) {
994
+ fail2(e);
995
+ }
996
+ }
997
+ if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
998
+ if (env2.hasError) throw env2.error;
999
+ }
1000
+ return next();
1001
+ })(env);
1002
+ }
1003
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
1004
+ var wrapFunctionHandler = (func) => {
1005
+ if (!Operation.isOperationWithHandler(func)) {
1006
+ throw new TypeError("Expected operation with handler");
1007
+ }
1008
+ const serviceTags = func.services.map((service) => service.key);
1009
+ return {
1010
+ meta: {
1011
+ key: func.meta.key,
1012
+ name: func.meta.name,
1013
+ description: func.meta.description,
1014
+ inputSchema: JsonSchema.toJsonSchema(func.input),
1015
+ outputSchema: func.output === void 0 ? void 0 : JsonSchema.toJsonSchema(func.output),
1016
+ services: func.services.map((service) => service.key)
1017
+ },
1018
+ handler: async ({ data, context }) => {
1019
+ if ((serviceTags.includes(Database2.Service.key) || serviceTags.includes(QueueService.key) || serviceTags.includes(Feed.Service.key)) && (!context.services.dataService || !context.services.queryService)) {
1020
+ throw new FunctionError({
1021
+ message: "Services not provided: dataService, queryService"
1022
+ });
1023
+ }
1024
+ try {
1025
+ const env = {
1026
+ stack: [],
1027
+ error: void 0,
1028
+ hasError: false
1029
+ };
1030
+ try {
1031
+ if (!SchemaAST2.isAnyKeyword(func.input.ast)) {
1032
+ try {
1033
+ Schema6.validateSync(func.input)(data);
1034
+ } catch (error) {
1035
+ throw new FunctionError({
1036
+ message: "Invalid input schema",
1037
+ cause: error
1038
+ });
1039
+ }
1040
+ }
1041
+ const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
1042
+ if (func.types.length > 0) {
1043
+ invariant2(funcContext.db, "Database is required for functions with types", {
1044
+ F: __dxlog_file3,
1045
+ L: 74,
1046
+ S: void 0,
1047
+ A: [
1048
+ "funcContext.db",
1049
+ "'Database is required for functions with types'"
1050
+ ]
1051
+ });
1052
+ await funcContext.db.graph.schemaRegistry.register(func.types);
1053
+ }
1054
+ const dataWithDecodedRefs = funcContext.db && !SchemaAST2.isAnyKeyword(func.input.ast) ? decodeRefsFromSchema(func.input.ast, data, funcContext.db) : data;
1055
+ let result = await func.handler(dataWithDecodedRefs);
1056
+ if (Effect10.isEffect(result)) {
1057
+ result = await runAndForwardErrors(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
1058
+ }
1059
+ if (func.output && !SchemaAST2.isAnyKeyword(func.output.ast)) {
1060
+ Schema6.validateSync(func.output)(result);
1061
+ }
1062
+ return result;
1063
+ } catch (e) {
1064
+ env.error = e;
1065
+ env.hasError = true;
1066
+ } finally {
1067
+ const result = _ts_dispose_resources(env);
1068
+ if (result) await result;
1069
+ }
1070
+ } catch (error) {
1071
+ throw error;
1072
+ }
1073
+ }
1074
+ };
1075
+ };
1076
+ var FunctionContext = class extends Resource {
1077
+ context;
1078
+ client;
1079
+ db;
1080
+ queues;
1081
+ constructor(context) {
1082
+ super();
1083
+ this.context = context;
1084
+ if (context.services.dataService && context.services.queryService) {
1085
+ this.client = new EchoClient().connectToService({
1086
+ dataService: context.services.dataService,
1087
+ queryService: context.services.queryService,
1088
+ queueService: context.services.queueService
1089
+ });
1090
+ }
1091
+ }
1092
+ async _open() {
1093
+ await this.client?.open();
1094
+ this.db = this.client && this.context.spaceId ? this.client.constructDatabase({
1095
+ spaceId: this.context.spaceId ?? failedInvariant(),
1096
+ spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant("spaceKey missing in context")),
1097
+ reactiveSchemaQuery: false,
1098
+ preloadSchemaOnOpen: false
1099
+ }) : void 0;
1100
+ await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant("spaceRootUrl missing in context"));
1101
+ await this.db?.open();
1102
+ this.queues = this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : void 0;
1103
+ }
1104
+ async _close() {
1105
+ await this.db?.close();
1106
+ await this.client?.close();
1107
+ }
1108
+ createLayer() {
1109
+ assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
1110
+ const dbLayer = this.db ? Database2.layer(this.db) : Database2.notAvailable;
1111
+ const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
1112
+ const feedLayer = this.queues ? createFeedServiceLayer2(this.queues) : Feed.notAvailable;
1113
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase({
1114
+ caching: true
1115
+ }).pipe(Layer8.provide(dbLayer)) : CredentialsService.configuredLayer([]);
1116
+ const functionInvocationService = MockedFunctionInvocationService;
1117
+ const tracing = TracingService.layerNoop;
1118
+ const aiLayer = this.context.services.functionsAiService ? AiModelResolver.AiModelResolver.buildAiService.pipe(Layer8.provide(AnthropicResolver.make().pipe(Layer8.provide(AnthropicClient.layer({
1119
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
1120
+ apiUrl: "http://internal/provider/anthropic"
1121
+ }).pipe(Layer8.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))))))) : AiService.notAvailable;
1122
+ return Layer8.mergeAll(
1123
+ dbLayer,
1124
+ queuesLayer,
1125
+ feedLayer,
1126
+ credentials,
1127
+ functionInvocationService,
1128
+ aiLayer,
1129
+ tracing,
1130
+ writerLayerNoop
1131
+ );
1132
+ }
1133
+ };
1134
+ var MockedFunctionInvocationService = Layer8.succeed(FunctionInvocationService, {
1135
+ invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet."),
1136
+ resolveFunction: () => Effect10.die("Not implemented.")
1137
+ });
1138
+ var decodeRefsFromSchema = (ast, value2, db) => {
1139
+ if (value2 == null) {
1140
+ return value2;
1141
+ }
1142
+ const encoded = SchemaAST2.encodedBoundAST(ast);
1143
+ if (Ref4.isRefType(encoded)) {
1144
+ if (Ref4.isRef(value2)) {
1145
+ return value2;
1146
+ }
1147
+ if (typeof value2 === "object" && value2 !== null && typeof value2["/"] === "string") {
1148
+ const resolver = db.graph.createRefResolver({
1149
+ context: {
1150
+ space: db.spaceId
1151
+ }
1152
+ });
1153
+ return refFromEncodedReference(value2, resolver);
1154
+ }
1155
+ return value2;
1156
+ }
1157
+ switch (encoded._tag) {
1158
+ case "TypeLiteral": {
1159
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
1160
+ return value2;
1161
+ }
1162
+ const result = {
1163
+ ...value2
1164
+ };
1165
+ for (const prop of SchemaAST2.getPropertySignatures(encoded)) {
1166
+ const key2 = prop.name.toString();
1167
+ if (key2 in result) {
1168
+ result[key2] = decodeRefsFromSchema(prop.type, result[key2], db);
1169
+ }
1170
+ }
1171
+ return result;
1172
+ }
1173
+ case "TupleType": {
1174
+ if (!Array.isArray(value2)) {
1175
+ return value2;
1176
+ }
1177
+ if (encoded.elements.length === 0 && encoded.rest.length === 1) {
1178
+ const elementType = encoded.rest[0].type;
1179
+ return value2.map((item) => decodeRefsFromSchema(elementType, item, db));
1180
+ }
1181
+ return value2;
1182
+ }
1183
+ case "Union": {
1184
+ const nonUndefined = encoded.types.filter((t) => !SchemaAST2.isUndefinedKeyword(t));
1185
+ if (nonUndefined.length === 1) {
1186
+ return decodeRefsFromSchema(nonUndefined[0], value2, db);
1187
+ }
1188
+ return value2;
1189
+ }
1190
+ case "Suspend": {
1191
+ return decodeRefsFromSchema(encoded.f(), value2, db);
1192
+ }
1193
+ case "Refinement": {
1194
+ return decodeRefsFromSchema(encoded.from, value2, db);
1195
+ }
1196
+ default: {
1197
+ return value2;
1198
+ }
1199
+ }
1200
+ };
1201
+ export {
1202
+ ComputeEvent,
1203
+ ComputeEventLogger,
1204
+ ComputeEventPayload,
1205
+ ConfiguredCredentialsService,
1206
+ ContextQueueService,
1207
+ CredentialsService,
1208
+ ExampleHandlers,
1209
+ FUNCTIONS_META_KEY,
1210
+ FUNCTIONS_PRESET_META_KEY,
1211
+ Fibonacci,
1212
+ FunctionError,
1213
+ FunctionInvocationService,
1214
+ FunctionNotFoundError,
1215
+ MESSAGE_PROPERTY_TOOL_CALL_ID,
1216
+ Process_exports as Process,
1217
+ QueueService,
1218
+ Reply,
1219
+ Script_exports as Script,
1220
+ ServiceNotAvailableError,
1221
+ ServiceResolver_exports as ServiceResolver,
1222
+ Sleep,
1223
+ StorageService,
1224
+ Trace_exports as Trace,
1225
+ TracingService,
1226
+ Trigger_exports as Trigger,
1227
+ TriggerEvent_exports as TriggerEvent,
1228
+ TriggerStateNotFoundError,
1229
+ clear,
1230
+ createDefectLogger,
1231
+ createEventLogger,
1232
+ deleteKey,
1233
+ feedServiceFromQueueServiceLayer,
1234
+ get,
1235
+ getUserFunctionIdInMetadata,
1236
+ key,
1237
+ list,
1238
+ logCustomEvent,
1239
+ set,
1240
+ setUserFunctionIdInMetadata,
1241
+ withAuthorization,
1242
+ withDefault,
1243
+ wrapFunctionHandler
1244
+ };
1245
+ //# sourceMappingURL=index.mjs.map