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

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