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

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