@dxos/functions 0.8.4-main.f9ba587 → 0.8.4-main.fcc0d83b33

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