@dxos/functions 0.8.4-main.74a063c4e0 → 0.8.4-main.765dc60934
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.
- package/LICENSE +102 -5
- package/README.md +1 -1
- package/dist/lib/neutral/index.mjs +261 -930
- package/dist/lib/neutral/index.mjs.map +4 -4
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/types/src/index.d.ts +0 -6
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -1
- package/dist/types/src/protocol/functions-ai-http-client.test.d.ts +2 -0
- package/dist/types/src/protocol/functions-ai-http-client.test.d.ts.map +1 -0
- package/dist/types/src/protocol/protocol.d.ts +14 -2
- package/dist/types/src/protocol/protocol.d.ts.map +1 -1
- package/dist/types/src/sdk.d.ts +3 -7
- package/dist/types/src/sdk.d.ts.map +1 -1
- package/dist/types/src/services/credentials.d.ts +15 -38
- package/dist/types/src/services/credentials.d.ts.map +1 -1
- package/dist/types/src/services/function-invocation-service.d.ts +3 -5
- package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
- package/dist/types/src/services/index.d.ts +1 -4
- package/dist/types/src/services/index.d.ts.map +1 -1
- package/dist/types/src/services/queues.d.ts +1 -49
- package/dist/types/src/services/queues.d.ts.map +1 -1
- package/dist/types/src/services/tracing.d.ts +1 -107
- package/dist/types/src/services/tracing.d.ts.map +1 -1
- package/dist/types/src/types/index.d.ts +0 -3
- package/dist/types/src/types/index.d.ts.map +1 -1
- package/dist/types/src/types/url.d.ts +1 -1
- package/dist/types/src/types/url.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +16 -21
- package/src/index.ts +0 -6
- package/src/protocol/functions-ai-http-client.test.ts +105 -0
- package/src/protocol/functions-ai-http-client.ts +75 -1
- package/src/protocol/protocol.test.ts +10 -10
- package/src/protocol/protocol.ts +213 -40
- package/src/sdk.ts +7 -15
- package/src/services/credentials.ts +76 -120
- package/src/services/function-invocation-service.ts +3 -9
- package/src/services/index.ts +1 -4
- package/src/services/queues.ts +1 -87
- package/src/services/tracing.ts +0 -192
- package/src/types/index.ts +0 -3
- package/src/types/url.ts +1 -1
- package/dist/lib/neutral/Trace.mjs +0 -38
- package/dist/lib/neutral/Trace.mjs.map +0 -7
- package/dist/lib/neutral/chunk-5T7GOX2V.mjs +0 -149
- package/dist/lib/neutral/chunk-5T7GOX2V.mjs.map +0 -7
- package/dist/lib/neutral/chunk-IVDUS56O.mjs +0 -49
- package/dist/lib/neutral/chunk-IVDUS56O.mjs.map +0 -7
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs +0 -10
- package/dist/lib/neutral/chunk-J5LGTIGS.mjs.map +0 -7
- package/dist/lib/neutral/fib-N45KAC7C.mjs +0 -23
- package/dist/lib/neutral/fib-N45KAC7C.mjs.map +0 -7
- package/dist/lib/neutral/reply-EUEPKNJF.mjs +0 -19
- package/dist/lib/neutral/reply-EUEPKNJF.mjs.map +0 -7
- package/dist/lib/neutral/sleep-PUK3D4FF.mjs +0 -15
- package/dist/lib/neutral/sleep-PUK3D4FF.mjs.map +0 -7
- package/dist/types/src/Trace.d.ts +0 -155
- package/dist/types/src/Trace.d.ts.map +0 -1
- package/dist/types/src/errors.d.ts +0 -121
- package/dist/types/src/errors.d.ts.map +0 -1
- package/dist/types/src/example/definitions.d.ts +0 -11
- package/dist/types/src/example/definitions.d.ts.map +0 -1
- package/dist/types/src/example/fib.d.ts +0 -8
- package/dist/types/src/example/fib.d.ts.map +0 -1
- package/dist/types/src/example/forex-effect.d.ts +0 -3
- package/dist/types/src/example/forex-effect.d.ts.map +0 -1
- package/dist/types/src/example/index.d.ts +0 -4
- package/dist/types/src/example/index.d.ts.map +0 -1
- package/dist/types/src/example/reply.d.ts +0 -4
- package/dist/types/src/example/reply.d.ts.map +0 -1
- package/dist/types/src/example/sleep.d.ts +0 -6
- package/dist/types/src/example/sleep.d.ts.map +0 -1
- package/dist/types/src/process/Process.d.ts +0 -247
- package/dist/types/src/process/Process.d.ts.map +0 -1
- package/dist/types/src/process/ServiceResolver.d.ts +0 -74
- package/dist/types/src/process/ServiceResolver.d.ts.map +0 -1
- package/dist/types/src/process/StorageService.d.ts +0 -58
- package/dist/types/src/process/StorageService.d.ts.map +0 -1
- package/dist/types/src/services/event-logger.d.ts +0 -81
- package/dist/types/src/services/event-logger.d.ts.map +0 -1
- package/dist/types/src/types/Script.d.ts +0 -22
- package/dist/types/src/types/Script.d.ts.map +0 -1
- package/dist/types/src/types/Trigger.d.ts +0 -120
- package/dist/types/src/types/Trigger.d.ts.map +0 -1
- package/dist/types/src/types/TriggerEvent.d.ts +0 -75
- package/dist/types/src/types/TriggerEvent.d.ts.map +0 -1
- package/src/Trace.ts +0 -202
- package/src/errors.ts +0 -21
- package/src/example/definitions.ts +0 -49
- package/src/example/fib.ts +0 -23
- package/src/example/forex-effect.ts +0 -40
- package/src/example/index.ts +0 -12
- package/src/example/reply.ts +0 -19
- package/src/example/sleep.ts +0 -17
- package/src/process/Process.ts +0 -486
- package/src/process/ServiceResolver.ts +0 -174
- package/src/process/StorageService.ts +0 -99
- package/src/services/event-logger.ts +0 -127
- package/src/types/Script.ts +0 -38
- package/src/types/Trigger.ts +0 -154
- package/src/types/TriggerEvent.ts +0 -62
|
@@ -1,376 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
EventType,
|
|
3
|
-
OperationEnd,
|
|
4
|
-
OperationStart,
|
|
5
|
-
Trace_exports,
|
|
6
|
-
write,
|
|
7
|
-
writerLayerNoop
|
|
8
|
-
} from "./chunk-5T7GOX2V.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);
|
|
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
1
|
// src/services/credentials.ts
|
|
311
2
|
import * as HttpClient from "@effect/platform/HttpClient";
|
|
312
3
|
import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
|
|
313
|
-
import * as
|
|
314
|
-
import * as
|
|
315
|
-
import * as Layer2 from "effect/Layer";
|
|
4
|
+
import * as Effect from "effect/Effect";
|
|
5
|
+
import * as Layer from "effect/Layer";
|
|
316
6
|
import * as Redacted from "effect/Redacted";
|
|
317
|
-
import {
|
|
318
|
-
import { Database } from "@dxos/echo";
|
|
7
|
+
import { Credential } from "@dxos/compute";
|
|
8
|
+
import { Database, Query } from "@dxos/echo";
|
|
319
9
|
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
10
|
var ConfiguredCredentialsService = class {
|
|
375
11
|
credentials;
|
|
376
12
|
constructor(credentials = []) {
|
|
@@ -395,484 +31,77 @@ var withAuthorization = (token, kind) => HttpClient.mapRequest((request) => {
|
|
|
395
31
|
const authorization = kind ? `${kind} ${token}` : token;
|
|
396
32
|
return HttpClientRequest.setHeader(request, "Authorization", authorization);
|
|
397
33
|
});
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
import * as Effect6 from "effect/Effect";
|
|
402
|
-
import * as Layer4 from "effect/Layer";
|
|
403
|
-
import * as Schema2 from "effect/Schema";
|
|
404
|
-
import { Obj as Obj2, Type } from "@dxos/echo";
|
|
405
|
-
import { invariant } from "@dxos/invariant";
|
|
406
|
-
import { LogLevel, log } from "@dxos/log";
|
|
407
|
-
|
|
408
|
-
// src/services/tracing.ts
|
|
409
|
-
import * as Context5 from "effect/Context";
|
|
410
|
-
import * as Effect5 from "effect/Effect";
|
|
411
|
-
import * as Layer3 from "effect/Layer";
|
|
412
|
-
import { AgentStatus } from "@dxos/ai";
|
|
413
|
-
import { Obj } from "@dxos/echo";
|
|
414
|
-
import { ObjectId } from "@dxos/keys";
|
|
415
|
-
import { Message } from "@dxos/types";
|
|
416
|
-
var TracingService = class _TracingService extends Context5.Tag("@dxos/functions/TracingService")() {
|
|
417
|
-
static noop = {
|
|
418
|
-
getTraceContext: () => ({}),
|
|
419
|
-
write: () => {
|
|
420
|
-
},
|
|
421
|
-
ephemeral: () => {
|
|
422
|
-
},
|
|
423
|
-
traceInvocationStart: () => Effect5.sync(() => ({
|
|
424
|
-
invocationId: ObjectId.random(),
|
|
425
|
-
invocationTraceQueue: void 0
|
|
426
|
-
})),
|
|
427
|
-
traceInvocationEnd: () => Effect5.sync(() => {
|
|
428
|
-
})
|
|
429
|
-
};
|
|
430
|
-
static layerNoop = Layer3.succeed(_TracingService, _TracingService.noop);
|
|
431
|
-
/**
|
|
432
|
-
* Creates a TracingService layer that emits events to the parent tracing service.
|
|
433
|
-
*/
|
|
434
|
-
static layerSubframe = (mapContext) => Layer3.effect(_TracingService, Effect5.gen(function* () {
|
|
435
|
-
const tracing = yield* _TracingService;
|
|
436
|
-
const context = mapContext(tracing.getTraceContext());
|
|
34
|
+
var configuredCredentialsLayer = (credentials) => Layer.succeed(Credential.CredentialsService, new ConfiguredCredentialsService(credentials));
|
|
35
|
+
var credentialsLayerConfig = (credentials) => Layer.effect(Credential.CredentialsService, Effect.gen(function* () {
|
|
36
|
+
const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) => Effect.gen(function* () {
|
|
437
37
|
return {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
getTraceContext: () => context,
|
|
441
|
-
traceInvocationStart: () => Effect5.die("Tracing invocation inside another invocation is not supported."),
|
|
442
|
-
traceInvocationEnd: () => Effect5.die("Tracing invocation inside another invocation is not supported.")
|
|
38
|
+
service,
|
|
39
|
+
apiKey: Redacted.value(yield* apiKey)
|
|
443
40
|
};
|
|
444
41
|
}));
|
|
445
|
-
|
|
446
|
-
* Create sublayer to trace an invocation.
|
|
447
|
-
* @param data
|
|
448
|
-
* @returns
|
|
449
|
-
*/
|
|
450
|
-
static layerInvocation = (data) => _TracingService.layerSubframe((context) => ({
|
|
451
|
-
...context,
|
|
452
|
-
currentInvocation: data
|
|
453
|
-
}));
|
|
454
|
-
/**
|
|
455
|
-
* Emit the current human-readable execution status.
|
|
456
|
-
*/
|
|
457
|
-
static emitStatus = Effect5.fnUntraced(function* (data) {
|
|
458
|
-
const tracing = yield* _TracingService;
|
|
459
|
-
tracing.write(Obj.make(AgentStatus, {
|
|
460
|
-
parentMessage: tracing.getTraceContext().parentMessage,
|
|
461
|
-
toolCallId: tracing.getTraceContext().toolCallId,
|
|
462
|
-
created: (/* @__PURE__ */ new Date()).toISOString(),
|
|
463
|
-
...data
|
|
464
|
-
}), tracing.getTraceContext());
|
|
465
|
-
});
|
|
466
|
-
static emitConverationMessage = Effect5.fnUntraced(function* (data) {
|
|
467
|
-
const tracing = yield* _TracingService;
|
|
468
|
-
tracing.write(Obj.make(Message.Message, {
|
|
469
|
-
parentMessage: tracing.getTraceContext().parentMessage,
|
|
470
|
-
...data,
|
|
471
|
-
properties: {
|
|
472
|
-
[MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
|
|
473
|
-
...data.properties
|
|
474
|
-
}
|
|
475
|
-
}), tracing.getTraceContext());
|
|
476
|
-
});
|
|
477
|
-
static emitEphemeralMessage = Effect5.fnUntraced(function* (data) {
|
|
478
|
-
const tracing = yield* _TracingService;
|
|
479
|
-
tracing.ephemeral(data, tracing.getTraceContext());
|
|
480
|
-
});
|
|
481
|
-
};
|
|
482
|
-
var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
|
|
483
|
-
|
|
484
|
-
// src/services/event-logger.ts
|
|
485
|
-
var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/services/event-logger.ts";
|
|
486
|
-
var ComputeEventPayload = Schema2.Union(Schema2.Struct({
|
|
487
|
-
type: Schema2.Literal("begin-compute"),
|
|
488
|
-
nodeId: Schema2.String,
|
|
489
|
-
/**
|
|
490
|
-
* Names of the inputs begin computed.
|
|
491
|
-
*/
|
|
492
|
-
inputs: Schema2.Array(Schema2.String)
|
|
493
|
-
}), Schema2.Struct({
|
|
494
|
-
type: Schema2.Literal("end-compute"),
|
|
495
|
-
nodeId: Schema2.String,
|
|
496
|
-
/**
|
|
497
|
-
* Names of the outputs computed.
|
|
498
|
-
*/
|
|
499
|
-
outputs: Schema2.Array(Schema2.String)
|
|
500
|
-
}), Schema2.Struct({
|
|
501
|
-
type: Schema2.Literal("compute-input"),
|
|
502
|
-
nodeId: Schema2.String,
|
|
503
|
-
property: Schema2.String,
|
|
504
|
-
value: Schema2.Any
|
|
505
|
-
}), Schema2.Struct({
|
|
506
|
-
type: Schema2.Literal("compute-output"),
|
|
507
|
-
nodeId: Schema2.String,
|
|
508
|
-
property: Schema2.String,
|
|
509
|
-
value: Schema2.Any
|
|
510
|
-
}), Schema2.Struct({
|
|
511
|
-
type: Schema2.Literal("custom"),
|
|
512
|
-
nodeId: Schema2.String,
|
|
513
|
-
event: Schema2.Any
|
|
514
|
-
}));
|
|
515
|
-
var ComputeEvent = Schema2.Struct({
|
|
516
|
-
payload: ComputeEventPayload
|
|
517
|
-
}).pipe(Type.object({
|
|
518
|
-
typename: "org.dxos.type.computeEvent",
|
|
519
|
-
version: "0.1.0"
|
|
42
|
+
return new ConfiguredCredentialsService(serviceCredentials);
|
|
520
43
|
}));
|
|
521
|
-
var
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
44
|
+
var credentialsLayerFromDatabase = ({ caching = false } = {}) => Layer.effect(Credential.CredentialsService, Effect.gen(function* () {
|
|
45
|
+
const dbService = yield* Database.Service;
|
|
46
|
+
const cache = /* @__PURE__ */ new Map();
|
|
47
|
+
const queryCredentials = async (query) => {
|
|
48
|
+
const cacheKey = JSON.stringify(query);
|
|
49
|
+
if (caching && cache.has(cacheKey)) {
|
|
50
|
+
return cache.get(cacheKey);
|
|
51
|
+
}
|
|
52
|
+
const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
|
|
53
|
+
const credentials = accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
|
|
54
|
+
service: accessToken.source,
|
|
55
|
+
apiKey: accessToken.token
|
|
56
|
+
}));
|
|
57
|
+
if (caching) {
|
|
58
|
+
cache.set(cacheKey, credentials);
|
|
59
|
+
}
|
|
60
|
+
return credentials;
|
|
526
61
|
};
|
|
527
|
-
/**
|
|
528
|
-
* Implements ComputeEventLogger using TracingService.
|
|
529
|
-
*/
|
|
530
|
-
static layerFromTracing = Layer4.effect(_ComputeEventLogger, Effect6.gen(function* () {
|
|
531
|
-
const tracing = yield* TracingService;
|
|
532
|
-
return {
|
|
533
|
-
log: (event) => {
|
|
534
|
-
tracing.write(Obj2.make(ComputeEvent, {
|
|
535
|
-
payload: event
|
|
536
|
-
}), tracing.getTraceContext());
|
|
537
|
-
},
|
|
538
|
-
nodeId: void 0
|
|
539
|
-
};
|
|
540
|
-
}));
|
|
541
|
-
};
|
|
542
|
-
var logCustomEvent = (data) => Effect6.gen(function* () {
|
|
543
|
-
const logger = yield* ComputeEventLogger;
|
|
544
|
-
if (!logger.nodeId) {
|
|
545
|
-
throw new Error("logCustomEvent must be called within a node compute function");
|
|
546
|
-
}
|
|
547
|
-
logger.log({
|
|
548
|
-
type: "custom",
|
|
549
|
-
nodeId: logger.nodeId,
|
|
550
|
-
event: data
|
|
551
|
-
});
|
|
552
|
-
});
|
|
553
|
-
var createDefectLogger = () => Effect6.catchAll((error) => Effect6.gen(function* () {
|
|
554
|
-
log.error("unhandled effect error", {
|
|
555
|
-
error
|
|
556
|
-
}, {
|
|
557
|
-
F: __dxlog_file,
|
|
558
|
-
L: 102,
|
|
559
|
-
S: this,
|
|
560
|
-
C: (f, a) => f(...a)
|
|
561
|
-
});
|
|
562
|
-
throw error;
|
|
563
|
-
}));
|
|
564
|
-
var createEventLogger = (level, message = "event") => {
|
|
565
|
-
const logFunction = {
|
|
566
|
-
[LogLevel.WARN]: log.warn,
|
|
567
|
-
[LogLevel.VERBOSE]: log.verbose,
|
|
568
|
-
[LogLevel.DEBUG]: log.debug,
|
|
569
|
-
[LogLevel.INFO]: log.info,
|
|
570
|
-
[LogLevel.ERROR]: log.error
|
|
571
|
-
}[level];
|
|
572
|
-
invariant(logFunction, void 0, {
|
|
573
|
-
F: __dxlog_file,
|
|
574
|
-
L: 120,
|
|
575
|
-
S: void 0,
|
|
576
|
-
A: [
|
|
577
|
-
"logFunction",
|
|
578
|
-
""
|
|
579
|
-
]
|
|
580
|
-
});
|
|
581
62
|
return {
|
|
582
|
-
|
|
583
|
-
|
|
63
|
+
getCredential: async (query) => {
|
|
64
|
+
const credentials = await queryCredentials(query);
|
|
65
|
+
if (credentials.length === 0) {
|
|
66
|
+
throw new Error(`Credential not found for service: ${query.service}`);
|
|
67
|
+
}
|
|
68
|
+
return credentials[0];
|
|
584
69
|
},
|
|
585
|
-
|
|
70
|
+
queryCredentials: async (query) => {
|
|
71
|
+
return queryCredentials(query);
|
|
72
|
+
}
|
|
586
73
|
};
|
|
587
|
-
};
|
|
74
|
+
}));
|
|
588
75
|
|
|
589
76
|
// src/services/function-invocation-service.ts
|
|
590
|
-
import * as
|
|
591
|
-
import * as
|
|
592
|
-
import * as
|
|
593
|
-
var FunctionInvocationService = class _FunctionInvocationService extends
|
|
594
|
-
static layerNotAvailable =
|
|
595
|
-
invokeFunction: () =>
|
|
596
|
-
resolveFunction: () =>
|
|
77
|
+
import * as Context from "effect/Context";
|
|
78
|
+
import * as Effect2 from "effect/Effect";
|
|
79
|
+
import * as Layer2 from "effect/Layer";
|
|
80
|
+
var FunctionInvocationService = class _FunctionInvocationService extends Context.Tag("@dxos/functions/FunctionInvocationService")() {
|
|
81
|
+
static layerNotAvailable = Layer2.succeed(_FunctionInvocationService, {
|
|
82
|
+
invokeFunction: () => Effect2.die("FunctionInvocationService is not avaialble."),
|
|
83
|
+
resolveFunction: () => Effect2.die("FunctionInvocationService is not available.")
|
|
597
84
|
});
|
|
598
|
-
static invokeFunction = (functionDef, input) =>
|
|
599
|
-
static resolveFunction = (
|
|
85
|
+
static invokeFunction = (functionDef, input) => Effect2.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
|
|
86
|
+
static resolveFunction = (key) => Effect2.serviceFunctionEffect(_FunctionInvocationService, (service) => service.resolveFunction)(key);
|
|
600
87
|
};
|
|
601
88
|
|
|
602
89
|
// src/services/queues.ts
|
|
603
|
-
import
|
|
604
|
-
import * as Effect8 from "effect/Effect";
|
|
605
|
-
import * as Layer6 from "effect/Layer";
|
|
606
|
-
import { createFeedServiceLayer } from "@dxos/echo-db";
|
|
607
|
-
var QueueService = class _QueueService extends Context8.Tag("@dxos/functions/QueueService")() {
|
|
608
|
-
static notAvailable = Layer6.succeed(_QueueService, {
|
|
609
|
-
queues: {
|
|
610
|
-
get(_dxn) {
|
|
611
|
-
throw new Error("Queues not available");
|
|
612
|
-
},
|
|
613
|
-
create() {
|
|
614
|
-
throw new Error("Queues not available");
|
|
615
|
-
}
|
|
616
|
-
},
|
|
617
|
-
queue: void 0
|
|
618
|
-
});
|
|
619
|
-
static make = (queues, queue) => {
|
|
620
|
-
return {
|
|
621
|
-
queues,
|
|
622
|
-
queue
|
|
623
|
-
};
|
|
624
|
-
};
|
|
625
|
-
static layer = (queues, queue) => Layer6.succeed(_QueueService, _QueueService.make(queues, queue));
|
|
626
|
-
/**
|
|
627
|
-
* Gets a queue by its DXN.
|
|
628
|
-
*/
|
|
629
|
-
static getQueue = (dxn) => _QueueService.pipe(Effect8.map(({ queues }) => queues.get(dxn)));
|
|
630
|
-
/**
|
|
631
|
-
* Creates a new queue.
|
|
632
|
-
*/
|
|
633
|
-
static createQueue = (options) => _QueueService.pipe(Effect8.map(({ queues }) => queues.create(options)));
|
|
634
|
-
static append = (queue, objects) => Effect8.promise(() => queue.append(objects));
|
|
635
|
-
};
|
|
636
|
-
var ContextQueueService = class _ContextQueueService extends Context8.Tag("@dxos/functions/ContextQueueService")() {
|
|
637
|
-
static layer = (queue) => Layer6.succeed(_ContextQueueService, {
|
|
638
|
-
queue
|
|
639
|
-
});
|
|
640
|
-
};
|
|
641
|
-
var feedServiceFromQueueServiceLayer = Layer6.unwrapEffect(Effect8.gen(function* () {
|
|
642
|
-
const { queues } = yield* QueueService;
|
|
643
|
-
return createFeedServiceLayer(queues);
|
|
644
|
-
}));
|
|
645
|
-
|
|
646
|
-
// src/types/Script.ts
|
|
647
|
-
var Script_exports = {};
|
|
648
|
-
__export(Script_exports, {
|
|
649
|
-
Script: () => Script,
|
|
650
|
-
make: () => make5
|
|
651
|
-
});
|
|
652
|
-
import * as Schema3 from "effect/Schema";
|
|
653
|
-
import { Annotation, Obj as Obj3, Ref, Type as Type2 } from "@dxos/echo";
|
|
654
|
-
import { FormInputAnnotation } from "@dxos/echo/internal";
|
|
655
|
-
import { Text } from "@dxos/schema";
|
|
656
|
-
var Script = Schema3.Struct({
|
|
657
|
-
name: Schema3.String.pipe(Schema3.optional),
|
|
658
|
-
description: Schema3.String.pipe(Schema3.optional),
|
|
659
|
-
// TODO(burdon): Change to hash of deployed content.
|
|
660
|
-
// Whether source has changed since last deploy.
|
|
661
|
-
changed: Schema3.Boolean.pipe(FormInputAnnotation.set(false), Schema3.optional),
|
|
662
|
-
source: Ref.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
|
|
663
|
-
}).pipe(Type2.object({
|
|
664
|
-
typename: "org.dxos.type.script",
|
|
665
|
-
version: "0.1.0"
|
|
666
|
-
}), Annotation.LabelAnnotation.set([
|
|
667
|
-
"name"
|
|
668
|
-
]), Annotation.IconAnnotation.set({
|
|
669
|
-
icon: "ph--code--regular",
|
|
670
|
-
hue: "sky"
|
|
671
|
-
}));
|
|
672
|
-
var make5 = ({ source = "", ...props } = {}) => Obj3.make(Script, {
|
|
673
|
-
...props,
|
|
674
|
-
source: Ref.make(Text.make({
|
|
675
|
-
content: source
|
|
676
|
-
}))
|
|
677
|
-
});
|
|
678
|
-
|
|
679
|
-
// src/types/Trigger.ts
|
|
680
|
-
var Trigger_exports = {};
|
|
681
|
-
__export(Trigger_exports, {
|
|
682
|
-
EmailSpec: () => EmailSpec,
|
|
683
|
-
Kinds: () => Kinds,
|
|
684
|
-
QueueSpec: () => QueueSpec,
|
|
685
|
-
Spec: () => Spec,
|
|
686
|
-
SubscriptionSpec: () => SubscriptionSpec,
|
|
687
|
-
TimerSpec: () => TimerSpec,
|
|
688
|
-
Trigger: () => Trigger,
|
|
689
|
-
WebhookSpec: () => WebhookSpec,
|
|
690
|
-
make: () => make6
|
|
691
|
-
});
|
|
692
|
-
import * as Schema4 from "effect/Schema";
|
|
693
|
-
import * as SchemaAST from "effect/SchemaAST";
|
|
694
|
-
import { Annotation as Annotation2, Obj as Obj4, QueryAST, Ref as Ref2, Type as Type3 } from "@dxos/echo";
|
|
695
|
-
import { OptionsAnnotationId, SystemTypeAnnotation } from "@dxos/echo/internal";
|
|
696
|
-
import { DXN } from "@dxos/keys";
|
|
697
|
-
var Kinds = [
|
|
698
|
-
"email",
|
|
699
|
-
"queue",
|
|
700
|
-
"subscription",
|
|
701
|
-
"timer",
|
|
702
|
-
"webhook"
|
|
703
|
-
];
|
|
704
|
-
var kindLiteralAnnotations = {
|
|
705
|
-
title: "Kind"
|
|
706
|
-
};
|
|
707
|
-
var EmailSpec = Schema4.Struct({
|
|
708
|
-
kind: Schema4.Literal("email").annotations(kindLiteralAnnotations)
|
|
709
|
-
});
|
|
710
|
-
var QueueSpec = Schema4.Struct({
|
|
711
|
-
kind: Schema4.Literal("queue").annotations(kindLiteralAnnotations),
|
|
712
|
-
// TODO(dmaretskyi): Rename to `feed` and change to a reference.
|
|
713
|
-
queue: DXN.Schema
|
|
714
|
-
});
|
|
715
|
-
var SubscriptionSpec = Schema4.Struct({
|
|
716
|
-
kind: Schema4.Literal("subscription").annotations(kindLiteralAnnotations),
|
|
717
|
-
query: Schema4.Struct({
|
|
718
|
-
raw: Schema4.optional(Schema4.String.annotations({
|
|
719
|
-
title: "Query"
|
|
720
|
-
})),
|
|
721
|
-
ast: QueryAST.Query
|
|
722
|
-
}),
|
|
723
|
-
options: Schema4.optional(Schema4.Struct({
|
|
724
|
-
// Watch changes to object (not just creation).
|
|
725
|
-
deep: Schema4.optional(Schema4.Boolean.annotations({
|
|
726
|
-
title: "Nested"
|
|
727
|
-
})),
|
|
728
|
-
// Debounce changes (delay in ms).
|
|
729
|
-
delay: Schema4.optional(Schema4.Number.annotations({
|
|
730
|
-
title: "Delay"
|
|
731
|
-
}))
|
|
732
|
-
}).annotations({
|
|
733
|
-
title: "Options"
|
|
734
|
-
}))
|
|
735
|
-
});
|
|
736
|
-
var TimerSpec = Schema4.Struct({
|
|
737
|
-
kind: Schema4.Literal("timer").annotations(kindLiteralAnnotations),
|
|
738
|
-
cron: Schema4.String.annotations({
|
|
739
|
-
title: "Cron",
|
|
740
|
-
[SchemaAST.ExamplesAnnotationId]: [
|
|
741
|
-
"0 0 * * *"
|
|
742
|
-
]
|
|
743
|
-
})
|
|
744
|
-
});
|
|
745
|
-
var WebhookSpec = Schema4.Struct({
|
|
746
|
-
kind: Schema4.Literal("webhook").annotations(kindLiteralAnnotations),
|
|
747
|
-
method: Schema4.optional(Schema4.String.annotations({
|
|
748
|
-
title: "Method",
|
|
749
|
-
[OptionsAnnotationId]: [
|
|
750
|
-
"GET",
|
|
751
|
-
"POST"
|
|
752
|
-
]
|
|
753
|
-
})),
|
|
754
|
-
port: Schema4.optional(Schema4.Number.annotations({
|
|
755
|
-
title: "Port"
|
|
756
|
-
}))
|
|
757
|
-
});
|
|
758
|
-
var Spec = Schema4.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
|
|
759
|
-
title: "Trigger"
|
|
760
|
-
});
|
|
761
|
-
var TriggerSchema = Schema4.Struct({
|
|
762
|
-
/**
|
|
763
|
-
* Function or workflow to invoke.
|
|
764
|
-
*/
|
|
765
|
-
// TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
|
|
766
|
-
function: Schema4.optional(Ref2.Ref(Obj4.Unknown).annotations({
|
|
767
|
-
title: "Function"
|
|
768
|
-
})),
|
|
769
|
-
/**
|
|
770
|
-
* Only used for workflowSchema.
|
|
771
|
-
* Specifies the input node in the circuit.
|
|
772
|
-
* @deprecated Remove and enforce a single input node in all compute graphSchema.
|
|
773
|
-
*/
|
|
774
|
-
inputNodeId: Schema4.optional(Schema4.String.annotations({
|
|
775
|
-
title: "Input Node ID"
|
|
776
|
-
})),
|
|
777
|
-
// TODO(burdon): NO BOOLEAN PROPERTIES (enabld/disabled/paused, etc.)
|
|
778
|
-
// Need lint rule; or agent rule to require PR review for "boolean" key word.
|
|
779
|
-
enabled: Schema4.optional(Schema4.Boolean.annotations({
|
|
780
|
-
title: "Enabled"
|
|
781
|
-
})),
|
|
782
|
-
spec: Schema4.optional(Spec),
|
|
783
|
-
concurrency: Schema4.optional(Schema4.Number.annotations({
|
|
784
|
-
title: "Concurrency",
|
|
785
|
-
default: 1,
|
|
786
|
-
description: "Maximum number of concurrent invocations of the trigger. For Feed triggers, this will process Feed items in parallel."
|
|
787
|
-
})),
|
|
788
|
-
/**
|
|
789
|
-
* Passed as the input data to the function.
|
|
790
|
-
* Must match the function's input schema.
|
|
791
|
-
*
|
|
792
|
-
* @example
|
|
793
|
-
* {
|
|
794
|
-
* item: '{{event.item}}',
|
|
795
|
-
* instructions: 'Summarize and perform entity-extraction'
|
|
796
|
-
* mailbox: { '/': 'dxn:echo:AAA:ZZZ' }
|
|
797
|
-
* }
|
|
798
|
-
*/
|
|
799
|
-
input: Schema4.optional(Schema4.Record({
|
|
800
|
-
key: Schema4.String,
|
|
801
|
-
value: Schema4.Any
|
|
802
|
-
}))
|
|
803
|
-
}).pipe(Type3.object({
|
|
804
|
-
typename: "org.dxos.type.trigger",
|
|
805
|
-
version: "0.1.0"
|
|
806
|
-
}), Annotation2.IconAnnotation.set({
|
|
807
|
-
icon: "ph--lightning--regular",
|
|
808
|
-
hue: "yellow"
|
|
809
|
-
}), SystemTypeAnnotation.set(true));
|
|
810
|
-
var Trigger = TriggerSchema;
|
|
811
|
-
var make6 = (props) => Obj4.make(Trigger, props);
|
|
90
|
+
import { QueueService, feedServiceFromQueueServiceLayer } from "@dxos/echo-db";
|
|
812
91
|
|
|
813
|
-
// src/
|
|
814
|
-
var
|
|
815
|
-
__export(TriggerEvent_exports, {
|
|
816
|
-
EmailEvent: () => EmailEvent,
|
|
817
|
-
QueueEvent: () => QueueEvent,
|
|
818
|
-
SubscriptionEvent: () => SubscriptionEvent,
|
|
819
|
-
TimerEvent: () => TimerEvent,
|
|
820
|
-
TriggerEvent: () => TriggerEvent,
|
|
821
|
-
WebhookEvent: () => WebhookEvent
|
|
822
|
-
});
|
|
823
|
-
import * as Schema5 from "effect/Schema";
|
|
824
|
-
import { DXN as DXN2, Obj as Obj5, Ref as Ref3 } from "@dxos/echo";
|
|
825
|
-
var EmailEvent = Schema5.Struct({
|
|
826
|
-
from: Schema5.String,
|
|
827
|
-
to: Schema5.String,
|
|
828
|
-
subject: Schema5.String,
|
|
829
|
-
created: Schema5.String,
|
|
830
|
-
body: Schema5.String
|
|
831
|
-
});
|
|
832
|
-
var QueueEvent = Schema5.Struct({
|
|
833
|
-
queue: DXN2.Schema,
|
|
834
|
-
item: Schema5.Any,
|
|
835
|
-
cursor: Schema5.String
|
|
836
|
-
});
|
|
837
|
-
var SubscriptionEvent = Schema5.Struct({
|
|
838
|
-
/**
|
|
839
|
-
* Type of the mutation.
|
|
840
|
-
*/
|
|
841
|
-
// TODO(dmaretskyi): Specify enum.
|
|
842
|
-
type: Schema5.String,
|
|
843
|
-
/**
|
|
844
|
-
* Reference to the object that was changed or created.
|
|
845
|
-
*/
|
|
846
|
-
subject: Ref3.Ref(Obj5.Unknown),
|
|
847
|
-
/**
|
|
848
|
-
* @deprecated
|
|
849
|
-
*/
|
|
850
|
-
changedObjectId: Schema5.optional(Schema5.String)
|
|
851
|
-
});
|
|
852
|
-
var TimerEvent = Schema5.Struct({
|
|
853
|
-
tick: Schema5.Number
|
|
854
|
-
});
|
|
855
|
-
var WebhookEvent = Schema5.Struct({
|
|
856
|
-
url: Schema5.String,
|
|
857
|
-
method: Schema5.Literal("GET", "POST"),
|
|
858
|
-
headers: Schema5.Record({
|
|
859
|
-
key: Schema5.String,
|
|
860
|
-
value: Schema5.String
|
|
861
|
-
}),
|
|
862
|
-
bodyText: Schema5.String
|
|
863
|
-
});
|
|
864
|
-
var TriggerEvent = Schema5.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);
|
|
92
|
+
// src/services/tracing.ts
|
|
93
|
+
var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
|
|
865
94
|
|
|
866
95
|
// src/types/url.ts
|
|
867
96
|
var FUNCTIONS_META_KEY = "org.dxos.service.function";
|
|
868
97
|
var FUNCTIONS_PRESET_META_KEY = "org.dxos.service.function-preset";
|
|
869
98
|
var getUserFunctionIdInMetadata = (meta) => {
|
|
870
|
-
return meta.keys.find((
|
|
99
|
+
return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;
|
|
871
100
|
};
|
|
872
101
|
var setUserFunctionIdInMetadata = (meta, functionId) => {
|
|
873
|
-
const
|
|
874
|
-
if (
|
|
875
|
-
if (
|
|
102
|
+
const key = meta.keys.find((key2) => key2.source === FUNCTIONS_META_KEY);
|
|
103
|
+
if (key) {
|
|
104
|
+
if (key.id !== functionId) {
|
|
876
105
|
throw new Error("Metadata mismatch");
|
|
877
106
|
}
|
|
878
107
|
} else {
|
|
@@ -885,40 +114,44 @@ var setUserFunctionIdInMetadata = (meta, functionId) => {
|
|
|
885
114
|
|
|
886
115
|
// src/protocol/protocol.ts
|
|
887
116
|
import * as AnthropicClient from "@effect/ai-anthropic/AnthropicClient";
|
|
888
|
-
import * as
|
|
889
|
-
import * as
|
|
890
|
-
import * as
|
|
891
|
-
import * as
|
|
892
|
-
import
|
|
117
|
+
import * as Effect4 from "effect/Effect";
|
|
118
|
+
import * as Layer4 from "effect/Layer";
|
|
119
|
+
import * as Option from "effect/Option";
|
|
120
|
+
import * as Schema from "effect/Schema";
|
|
121
|
+
import * as SchemaAST from "effect/SchemaAST";
|
|
122
|
+
import { AiModelResolver, AiService, OpaqueToolkit } from "@dxos/ai";
|
|
893
123
|
import { AnthropicResolver } from "@dxos/ai/resolvers";
|
|
124
|
+
import { FunctionError, InvalidOperationInputError, InvalidOperationOutputError, Operation, OperationRegistry, Trace } from "@dxos/compute";
|
|
894
125
|
import { LifecycleState, Resource } from "@dxos/context";
|
|
895
|
-
import { Database as Database2, Feed, JsonSchema, Ref
|
|
896
|
-
import {
|
|
126
|
+
import { Database as Database2, Feed, JsonSchema, Ref } from "@dxos/echo";
|
|
127
|
+
import { createFeedServiceLayer, EchoClient } from "@dxos/echo-db";
|
|
897
128
|
import { refFromEncodedReference } from "@dxos/echo/internal";
|
|
898
129
|
import { runAndForwardErrors } from "@dxos/effect";
|
|
899
|
-
import { assertState, failedInvariant, invariant
|
|
130
|
+
import { assertState, failedInvariant, invariant } from "@dxos/invariant";
|
|
900
131
|
import { PublicKey } from "@dxos/keys";
|
|
901
|
-
import {
|
|
132
|
+
import { log as log2 } from "@dxos/log";
|
|
133
|
+
import { ErrorCodec as ErrorCodec2 } from "@dxos/protocols";
|
|
902
134
|
|
|
903
135
|
// src/protocol/functions-ai-http-client.ts
|
|
904
136
|
import * as Headers from "@effect/platform/Headers";
|
|
905
137
|
import * as HttpClient2 from "@effect/platform/HttpClient";
|
|
906
138
|
import * as HttpClientError from "@effect/platform/HttpClientError";
|
|
907
139
|
import * as HttpClientResponse from "@effect/platform/HttpClientResponse";
|
|
908
|
-
import * as
|
|
140
|
+
import * as Effect3 from "effect/Effect";
|
|
909
141
|
import * as FiberRef from "effect/FiberRef";
|
|
910
|
-
import * as
|
|
142
|
+
import * as Layer3 from "effect/Layer";
|
|
911
143
|
import * as Stream from "effect/Stream";
|
|
912
|
-
import {
|
|
144
|
+
import { FunctionsAiMemoizationMissError, FunctionsAiUpstreamError } from "@dxos/compute";
|
|
145
|
+
import { log } from "@dxos/log";
|
|
913
146
|
import { ErrorCodec } from "@dxos/protocols";
|
|
914
|
-
var
|
|
147
|
+
var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/functions/src/protocol/functions-ai-http-client.ts";
|
|
915
148
|
var requestInitTagKey = "@effect/platform/FetchHttpClient/FetchOptions";
|
|
916
149
|
var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
|
|
917
150
|
static make = (service) => HttpClient2.make((request, url, signal, fiber) => {
|
|
918
151
|
const context = fiber.getFiberRef(FiberRef.currentContext);
|
|
919
152
|
const options = context.unsafeMap.get(requestInitTagKey) ?? {};
|
|
920
153
|
const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers;
|
|
921
|
-
const send = (body) =>
|
|
154
|
+
const send = (body) => Effect3.tryPromise({
|
|
922
155
|
try: () => service.fetch(new Request(url, {
|
|
923
156
|
...options,
|
|
924
157
|
method: request.method,
|
|
@@ -926,21 +159,21 @@ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
|
|
|
926
159
|
body
|
|
927
160
|
})),
|
|
928
161
|
catch: (cause) => {
|
|
929
|
-
|
|
162
|
+
log.error("Failed to fetch", {
|
|
930
163
|
errorSerialized: ErrorCodec.encode(cause)
|
|
931
|
-
}, {
|
|
932
|
-
F: __dxlog_file2,
|
|
933
|
-
L: 43,
|
|
934
|
-
S: this,
|
|
935
|
-
C: (f, a) => f(...a)
|
|
936
|
-
});
|
|
164
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 31, S: this });
|
|
937
165
|
return new HttpClientError.RequestError({
|
|
938
166
|
request,
|
|
939
167
|
reason: "Transport",
|
|
940
168
|
cause
|
|
941
169
|
});
|
|
942
170
|
}
|
|
943
|
-
}).pipe(
|
|
171
|
+
}).pipe(Effect3.flatMap((response) => (
|
|
172
|
+
// Inspect the body before handing the response to `@effect/ai` so that structured
|
|
173
|
+
// upstream errors surface as typed defects (`FunctionsAiUpstreamError` and friends)
|
|
174
|
+
// rather than as the generic `HttpResponseError` from `@effect/ai/AiError`.
|
|
175
|
+
Effect3.flatMap(Effect3.promise(() => parseUpstreamError(response)), (typedError) => typedError ? Effect3.die(typedError) : Effect3.succeed(HttpClientResponse.fromWeb(request, response)))
|
|
176
|
+
)));
|
|
944
177
|
switch (request.body._tag) {
|
|
945
178
|
case "Raw":
|
|
946
179
|
case "Uint8Array":
|
|
@@ -948,14 +181,54 @@ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
|
|
|
948
181
|
case "FormData":
|
|
949
182
|
return send(request.body.formData);
|
|
950
183
|
case "Stream":
|
|
951
|
-
return Stream.toReadableStreamEffect(request.body.stream).pipe(
|
|
184
|
+
return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect3.flatMap(send));
|
|
952
185
|
}
|
|
953
186
|
return send(void 0);
|
|
954
187
|
});
|
|
955
|
-
static layer = (service) =>
|
|
188
|
+
static layer = (service) => Layer3.succeed(HttpClient2.HttpClient, _FunctionsAiHttpClient.make(service));
|
|
189
|
+
};
|
|
190
|
+
var parseUpstreamError = async (response) => {
|
|
191
|
+
if (response.ok) {
|
|
192
|
+
return void 0;
|
|
193
|
+
}
|
|
194
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
195
|
+
if (!contentType.toLowerCase().includes("application/json")) {
|
|
196
|
+
return void 0;
|
|
197
|
+
}
|
|
198
|
+
let body;
|
|
199
|
+
try {
|
|
200
|
+
body = await response.clone().json();
|
|
201
|
+
} catch {
|
|
202
|
+
return void 0;
|
|
203
|
+
}
|
|
204
|
+
if (!body || body.type !== "error" || typeof body.error !== "object" || body.error === null) {
|
|
205
|
+
return void 0;
|
|
206
|
+
}
|
|
207
|
+
const inner = body.error;
|
|
208
|
+
const message = inner.message ?? `Upstream AI service responded with HTTP ${response.status}`;
|
|
209
|
+
if (inner.type === "memoization_miss" && typeof inner.cacheKey === "string") {
|
|
210
|
+
return new FunctionsAiMemoizationMissError({
|
|
211
|
+
message,
|
|
212
|
+
context: {
|
|
213
|
+
cacheKey: inner.cacheKey,
|
|
214
|
+
status: response.status
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
return new FunctionsAiUpstreamError({
|
|
219
|
+
message,
|
|
220
|
+
context: {
|
|
221
|
+
type: inner.type,
|
|
222
|
+
status: response.status,
|
|
223
|
+
...inner.cacheKey ? {
|
|
224
|
+
cacheKey: inner.cacheKey
|
|
225
|
+
} : {}
|
|
226
|
+
}
|
|
227
|
+
});
|
|
956
228
|
};
|
|
957
229
|
|
|
958
230
|
// src/protocol/protocol.ts
|
|
231
|
+
var __dxlog_file2 = "/__w/dxos/dxos/packages/core/compute/functions/src/protocol/protocol.ts";
|
|
959
232
|
function _ts_add_disposable_resource(env, value2, async) {
|
|
960
233
|
if (value2 !== null && value2 !== void 0) {
|
|
961
234
|
if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
|
|
@@ -995,7 +268,7 @@ function _ts_dispose_resources(env) {
|
|
|
995
268
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
996
269
|
};
|
|
997
270
|
return (_ts_dispose_resources = function _ts_dispose_resources2(env2) {
|
|
998
|
-
function
|
|
271
|
+
function fail(e) {
|
|
999
272
|
env2.error = env2.hasError ? new _SuppressedError(e, env2.error, "An error was suppressed during disposal.") : e;
|
|
1000
273
|
env2.hasError = true;
|
|
1001
274
|
}
|
|
@@ -1007,12 +280,12 @@ function _ts_dispose_resources(env) {
|
|
|
1007
280
|
if (r.dispose) {
|
|
1008
281
|
var result = r.dispose.call(r.value);
|
|
1009
282
|
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
|
|
1010
|
-
|
|
283
|
+
fail(e);
|
|
1011
284
|
return next();
|
|
1012
285
|
});
|
|
1013
286
|
} else s |= 1;
|
|
1014
287
|
} catch (e) {
|
|
1015
|
-
|
|
288
|
+
fail(e);
|
|
1016
289
|
}
|
|
1017
290
|
}
|
|
1018
291
|
if (s === 1) return env2.hasError ? Promise.reject(env2.error) : Promise.resolve();
|
|
@@ -1021,8 +294,7 @@ function _ts_dispose_resources(env) {
|
|
|
1021
294
|
return next();
|
|
1022
295
|
})(env);
|
|
1023
296
|
}
|
|
1024
|
-
var
|
|
1025
|
-
var wrapFunctionHandler = (func) => {
|
|
297
|
+
var wrapFunctionHandler = (func, opts = {}) => {
|
|
1026
298
|
if (!Operation.isOperationWithHandler(func)) {
|
|
1027
299
|
throw new TypeError("Expected operation with handler");
|
|
1028
300
|
}
|
|
@@ -1049,36 +321,49 @@ var wrapFunctionHandler = (func) => {
|
|
|
1049
321
|
hasError: false
|
|
1050
322
|
};
|
|
1051
323
|
try {
|
|
1052
|
-
if (!
|
|
324
|
+
if (!SchemaAST.isAnyKeyword(func.input.ast)) {
|
|
1053
325
|
try {
|
|
1054
|
-
|
|
326
|
+
Schema.validateSync(func.input, {
|
|
327
|
+
onExcessProperty: "error"
|
|
328
|
+
})(data);
|
|
1055
329
|
} catch (error) {
|
|
1056
|
-
throw new
|
|
1057
|
-
message:
|
|
330
|
+
throw new InvalidOperationInputError({
|
|
331
|
+
message: `Operation input did not match schema (${func.meta.key}): ${error.message}`,
|
|
1058
332
|
cause: error
|
|
1059
333
|
});
|
|
1060
334
|
}
|
|
1061
335
|
}
|
|
1062
|
-
const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
"'Database is required for functions with types'"
|
|
1071
|
-
]
|
|
1072
|
-
});
|
|
1073
|
-
await funcContext.db.graph.schemaRegistry.register(func.types);
|
|
336
|
+
const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context, opts).open(), true);
|
|
337
|
+
const types = [
|
|
338
|
+
...opts.types ?? [],
|
|
339
|
+
...func.types ?? []
|
|
340
|
+
];
|
|
341
|
+
if (types.length > 0) {
|
|
342
|
+
invariant(funcContext.db, "Database is required for functions with types", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 137, S: void 0, A: ["funcContext.db", "'Database is required for functions with types'"] });
|
|
343
|
+
await funcContext.db.graph.schemaRegistry.register(types);
|
|
1074
344
|
}
|
|
1075
|
-
const dataWithDecodedRefs = funcContext.db && !
|
|
345
|
+
const dataWithDecodedRefs = funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast) ? decodeRefsFromSchema(func.input.ast, data, funcContext.db) : data;
|
|
1076
346
|
let result = await func.handler(dataWithDecodedRefs);
|
|
1077
|
-
if (
|
|
1078
|
-
result = await runAndForwardErrors(result.pipe(
|
|
347
|
+
if (Effect4.isEffect(result)) {
|
|
348
|
+
result = await runAndForwardErrors(result.pipe(Effect4.orDie, Effect4.provide(funcContext.createLayer())));
|
|
1079
349
|
}
|
|
1080
|
-
if (
|
|
1081
|
-
|
|
350
|
+
if (serviceTags.includes(Database2.Service.key) && funcContext.db) {
|
|
351
|
+
await funcContext.db.flush({
|
|
352
|
+
disk: true,
|
|
353
|
+
indexes: false
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {
|
|
357
|
+
try {
|
|
358
|
+
Schema.validateSync(func.output, {
|
|
359
|
+
onExcessProperty: "error"
|
|
360
|
+
})(result);
|
|
361
|
+
} catch (error) {
|
|
362
|
+
throw new InvalidOperationOutputError({
|
|
363
|
+
message: `Operation output did not match schema (${func.meta.key}): ${error.message}`,
|
|
364
|
+
cause: error
|
|
365
|
+
});
|
|
366
|
+
}
|
|
1082
367
|
}
|
|
1083
368
|
return result;
|
|
1084
369
|
} catch (e) {
|
|
@@ -1099,9 +384,11 @@ var FunctionContext = class extends Resource {
|
|
|
1099
384
|
client;
|
|
1100
385
|
db;
|
|
1101
386
|
queues;
|
|
1102
|
-
|
|
387
|
+
opts;
|
|
388
|
+
constructor(context, opts) {
|
|
1103
389
|
super();
|
|
1104
390
|
this.context = context;
|
|
391
|
+
this.opts = opts;
|
|
1105
392
|
if (context.services.dataService && context.services.queryService) {
|
|
1106
393
|
this.client = new EchoClient().connectToService({
|
|
1107
394
|
dataService: context.services.dataService,
|
|
@@ -1130,39 +417,111 @@ var FunctionContext = class extends Resource {
|
|
|
1130
417
|
assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
|
|
1131
418
|
const dbLayer = this.db ? Database2.layer(this.db) : Database2.notAvailable;
|
|
1132
419
|
const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
|
|
1133
|
-
const feedLayer = this.queues ?
|
|
1134
|
-
const credentials = dbLayer ?
|
|
420
|
+
const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
|
|
421
|
+
const credentials = dbLayer ? credentialsLayerFromDatabase({
|
|
1135
422
|
caching: true
|
|
1136
|
-
}).pipe(
|
|
1137
|
-
const
|
|
1138
|
-
const
|
|
1139
|
-
const
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
423
|
+
}).pipe(Layer4.provide(dbLayer)) : configuredCredentialsLayer([]);
|
|
424
|
+
const aiLayer = this.context.services.functionsAiService ? InternalAiServiceLayer(this.context.services.functionsAiService) : AiService.notAvailable;
|
|
425
|
+
const operationServiceLayer = this.context.services.functionsService ? makeOperationServiceLayer(this.context.services.functionsService) : unavailableOperationServiceLayer;
|
|
426
|
+
const operationRegistryLayer = this.context.services.functionsService ? makeOperationRegistryLayer(this.context.services.functionsService, this.context.spaceId) : emptyOperationRegistryLayer;
|
|
427
|
+
const traceWriterLayer = this.context.services.traceService ? makeTraceWriterLayer(this.context.services.traceService) : Trace.writerLayerNoop;
|
|
428
|
+
log2("Creating function context layer", {
|
|
429
|
+
traceService: !!this.context.services.traceService,
|
|
430
|
+
functionsService: !!this.context.services.functionsService,
|
|
431
|
+
functionsAiService: !!this.context.services.functionsAiService,
|
|
432
|
+
spaceId: this.context.spaceId,
|
|
433
|
+
spaceRootUrl: this.context.spaceRootUrl,
|
|
434
|
+
toolkits: this.opts.toolkits?.length ?? 0,
|
|
435
|
+
types: this.opts.types?.length ?? 0
|
|
436
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 234, S: this });
|
|
437
|
+
return Layer4.mergeAll(
|
|
1144
438
|
dbLayer,
|
|
1145
439
|
queuesLayer,
|
|
1146
440
|
feedLayer,
|
|
1147
441
|
credentials,
|
|
1148
|
-
|
|
442
|
+
operationServiceLayer,
|
|
443
|
+
operationRegistryLayer,
|
|
1149
444
|
aiLayer,
|
|
1150
|
-
|
|
1151
|
-
|
|
445
|
+
OpaqueToolkit.providerLayer(OpaqueToolkit.merge(...this.opts.toolkits ?? [])),
|
|
446
|
+
traceWriterLayer,
|
|
447
|
+
// `FunctionInvocationService` is deprecated; new code should yield `Operation.Service`.
|
|
448
|
+
// The cloudflare wrapper provides only the unavailable layer to satisfy the (still-present)
|
|
449
|
+
// type union — handlers that yield it will die at invocation time.
|
|
450
|
+
FunctionInvocationService.layerNotAvailable
|
|
1152
451
|
);
|
|
1153
452
|
}
|
|
1154
453
|
};
|
|
1155
|
-
var
|
|
1156
|
-
|
|
1157
|
-
|
|
454
|
+
var makeTraceWriterLayer = (traceService) => Layer4.succeed(Trace.TraceService, {
|
|
455
|
+
write: (eventType, payload) => {
|
|
456
|
+
log2("Writing trace event", {
|
|
457
|
+
eventType: eventType.key
|
|
458
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 254, S: void 0 });
|
|
459
|
+
traceService.write([
|
|
460
|
+
{
|
|
461
|
+
key: eventType.key,
|
|
462
|
+
isEphemeral: eventType.isEphemeral,
|
|
463
|
+
data: payload
|
|
464
|
+
}
|
|
465
|
+
]);
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
var InternalAiServiceLayer = (functionsAiService) => AiModelResolver.AiModelResolver.buildAiService.pipe(Layer4.provide(AnthropicResolver.make().pipe(Layer4.provide(AnthropicClient.layer({
|
|
469
|
+
// Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
|
|
470
|
+
apiUrl: "http://internal/provider/anthropic"
|
|
471
|
+
}).pipe(Layer4.provide(FunctionsAiHttpClient.layer(functionsAiService)))))));
|
|
472
|
+
var makeOperationServiceLayer = (functionsService) => {
|
|
473
|
+
const invokeRemote = async (op, input, options) => {
|
|
474
|
+
invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 278, S: void 0, A: ["op.meta.deployedId", "`Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`"] });
|
|
475
|
+
const result = await functionsService.invoke(op.meta.deployedId, input, {
|
|
476
|
+
spaceId: options?.spaceId
|
|
477
|
+
});
|
|
478
|
+
if (result._kind === "success") {
|
|
479
|
+
return {
|
|
480
|
+
data: result.data
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
return {
|
|
484
|
+
error: ErrorCodec2.decode(result.error)
|
|
485
|
+
};
|
|
486
|
+
};
|
|
487
|
+
return Layer4.succeed(Operation.Service, {
|
|
488
|
+
invoke: (op, input, options) => Effect4.tryPromise(() => invokeRemote(op, input, options)).pipe(Effect4.orDie, Effect4.flatMap((outcome) => outcome.error ? Effect4.die(outcome.error) : Effect4.succeed(outcome.data))),
|
|
489
|
+
schedule: (op, input) => Effect4.sync(() => {
|
|
490
|
+
invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 294, S: void 0, A: ["op.meta.deployedId", "`Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`"] });
|
|
491
|
+
void functionsService.invoke(op.meta.deployedId, input).catch(() => {
|
|
492
|
+
});
|
|
493
|
+
}),
|
|
494
|
+
invokePromise: (op, input, options) => invokeRemote(op, input, options).catch((error) => ({
|
|
495
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
496
|
+
}))
|
|
497
|
+
});
|
|
498
|
+
};
|
|
499
|
+
var unavailableOperationServiceLayer = Layer4.succeed(Operation.Service, {
|
|
500
|
+
invoke: () => Effect4.die("Operation.Service is not available: missing functionsService in EDGE context."),
|
|
501
|
+
schedule: () => Effect4.die("Operation.Service is not available: missing functionsService in EDGE context."),
|
|
502
|
+
invokePromise: async () => ({
|
|
503
|
+
error: new Error("Operation.Service is not available: missing functionsService in EDGE context.")
|
|
504
|
+
})
|
|
505
|
+
});
|
|
506
|
+
var makeOperationRegistryLayer = (functionsService, spaceId) => Layer4.succeed(OperationRegistry.Service, {
|
|
507
|
+
resolve: (key) => Effect4.gen(function* () {
|
|
508
|
+
const records = yield* Effect4.tryPromise(() => functionsService.query({
|
|
509
|
+
spaceId
|
|
510
|
+
})).pipe(Effect4.orDie);
|
|
511
|
+
const match = records.find((record) => Operation.getKey(record) === key);
|
|
512
|
+
return match ? Option.some(Operation.deserialize(match)) : Option.none();
|
|
513
|
+
})
|
|
514
|
+
});
|
|
515
|
+
var emptyOperationRegistryLayer = Layer4.succeed(OperationRegistry.Service, {
|
|
516
|
+
resolve: () => Effect4.succeed(Option.none())
|
|
1158
517
|
});
|
|
1159
518
|
var decodeRefsFromSchema = (ast, value2, db) => {
|
|
1160
519
|
if (value2 == null) {
|
|
1161
520
|
return value2;
|
|
1162
521
|
}
|
|
1163
|
-
const encoded =
|
|
1164
|
-
if (
|
|
1165
|
-
if (
|
|
522
|
+
const encoded = SchemaAST.encodedBoundAST(ast);
|
|
523
|
+
if (Ref.isRefType(encoded)) {
|
|
524
|
+
if (Ref.isRef(value2)) {
|
|
1166
525
|
return value2;
|
|
1167
526
|
}
|
|
1168
527
|
if (typeof value2 === "object" && value2 !== null && typeof value2["/"] === "string") {
|
|
@@ -1183,10 +542,10 @@ var decodeRefsFromSchema = (ast, value2, db) => {
|
|
|
1183
542
|
const result = {
|
|
1184
543
|
...value2
|
|
1185
544
|
};
|
|
1186
|
-
for (const prop of
|
|
1187
|
-
const
|
|
1188
|
-
if (
|
|
1189
|
-
result[
|
|
545
|
+
for (const prop of SchemaAST.getPropertySignatures(encoded)) {
|
|
546
|
+
const key = prop.name.toString();
|
|
547
|
+
if (key in result) {
|
|
548
|
+
result[key] = decodeRefsFromSchema(prop.type, result[key], db);
|
|
1190
549
|
}
|
|
1191
550
|
}
|
|
1192
551
|
return result;
|
|
@@ -1202,7 +561,7 @@ var decodeRefsFromSchema = (ast, value2, db) => {
|
|
|
1202
561
|
return value2;
|
|
1203
562
|
}
|
|
1204
563
|
case "Union": {
|
|
1205
|
-
const nonUndefined = encoded.types.filter((t) => !
|
|
564
|
+
const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));
|
|
1206
565
|
if (nonUndefined.length === 1) {
|
|
1207
566
|
return decodeRefsFromSchema(nonUndefined[0], value2, db);
|
|
1208
567
|
}
|
|
@@ -1220,47 +579,19 @@ var decodeRefsFromSchema = (ast, value2, db) => {
|
|
|
1220
579
|
}
|
|
1221
580
|
};
|
|
1222
581
|
export {
|
|
1223
|
-
ComputeEvent,
|
|
1224
|
-
ComputeEventLogger,
|
|
1225
|
-
ComputeEventPayload,
|
|
1226
582
|
ConfiguredCredentialsService,
|
|
1227
|
-
ContextQueueService,
|
|
1228
|
-
CredentialsService,
|
|
1229
|
-
ExampleHandlers,
|
|
1230
583
|
FUNCTIONS_META_KEY,
|
|
1231
584
|
FUNCTIONS_PRESET_META_KEY,
|
|
1232
|
-
Fibonacci,
|
|
1233
|
-
FunctionError,
|
|
1234
585
|
FunctionInvocationService,
|
|
1235
|
-
FunctionNotFoundError,
|
|
1236
586
|
MESSAGE_PROPERTY_TOOL_CALL_ID,
|
|
1237
|
-
Process_exports as Process,
|
|
1238
587
|
QueueService,
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
ServiceResolver_exports as ServiceResolver,
|
|
1243
|
-
Sleep,
|
|
1244
|
-
StorageService,
|
|
1245
|
-
Trace_exports as Trace,
|
|
1246
|
-
TracingService,
|
|
1247
|
-
Trigger_exports as Trigger,
|
|
1248
|
-
TriggerEvent_exports as TriggerEvent,
|
|
1249
|
-
TriggerStateNotFoundError,
|
|
1250
|
-
clear,
|
|
1251
|
-
createDefectLogger,
|
|
1252
|
-
createEventLogger,
|
|
1253
|
-
deleteKey,
|
|
588
|
+
configuredCredentialsLayer,
|
|
589
|
+
credentialsLayerConfig,
|
|
590
|
+
credentialsLayerFromDatabase,
|
|
1254
591
|
feedServiceFromQueueServiceLayer,
|
|
1255
|
-
get,
|
|
1256
592
|
getUserFunctionIdInMetadata,
|
|
1257
|
-
key,
|
|
1258
|
-
list,
|
|
1259
|
-
logCustomEvent,
|
|
1260
|
-
set,
|
|
1261
593
|
setUserFunctionIdInMetadata,
|
|
1262
594
|
withAuthorization,
|
|
1263
|
-
withDefault,
|
|
1264
595
|
wrapFunctionHandler
|
|
1265
596
|
};
|
|
1266
597
|
//# sourceMappingURL=index.mjs.map
|