@dxos/functions 0.8.4-main.3c1ae3b → 0.8.4-main.3eb6e50203

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 (51) hide show
  1. package/dist/lib/{browser → neutral}/index.mjs +281 -82
  2. package/dist/lib/neutral/index.mjs.map +7 -0
  3. package/dist/lib/neutral/meta.json +1 -0
  4. package/dist/types/src/errors.d.ts +24 -32
  5. package/dist/types/src/errors.d.ts.map +1 -1
  6. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  7. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  8. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  9. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  10. package/dist/types/src/protocol/protocol.d.ts.map +1 -1
  11. package/dist/types/src/sdk.d.ts +15 -1
  12. package/dist/types/src/sdk.d.ts.map +1 -1
  13. package/dist/types/src/services/credentials.d.ts +5 -3
  14. package/dist/types/src/services/credentials.d.ts.map +1 -1
  15. package/dist/types/src/services/event-logger.d.ts +25 -31
  16. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  17. package/dist/types/src/services/function-invocation-service.d.ts +5 -0
  18. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  19. package/dist/types/src/services/tracing.d.ts +37 -3
  20. package/dist/types/src/services/tracing.d.ts.map +1 -1
  21. package/dist/types/src/types/Function.d.ts +33 -44
  22. package/dist/types/src/types/Function.d.ts.map +1 -1
  23. package/dist/types/src/types/Script.d.ts +8 -15
  24. package/dist/types/src/types/Script.d.ts.map +1 -1
  25. package/dist/types/src/types/Trigger.d.ts +59 -78
  26. package/dist/types/src/types/Trigger.d.ts.map +1 -1
  27. package/dist/types/src/types/TriggerEvent.d.ts +43 -12
  28. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
  29. package/dist/types/src/types/url.d.ts +4 -3
  30. package/dist/types/src/types/url.d.ts.map +1 -1
  31. package/dist/types/tsconfig.tsbuildinfo +1 -1
  32. package/package.json +23 -18
  33. package/src/errors.ts +4 -4
  34. package/src/operation-compatibility.test.ts +185 -0
  35. package/src/protocol/functions-ai-http-client.ts +67 -0
  36. package/src/protocol/protocol.ts +113 -9
  37. package/src/sdk.ts +52 -3
  38. package/src/services/credentials.ts +12 -12
  39. package/src/services/event-logger.ts +2 -2
  40. package/src/services/function-invocation-service.ts +14 -0
  41. package/src/services/tracing.ts +63 -4
  42. package/src/types/Function.ts +12 -10
  43. package/src/types/Script.ts +3 -2
  44. package/src/types/Trigger.ts +24 -13
  45. package/src/types/TriggerEvent.ts +29 -29
  46. package/src/types/url.ts +4 -3
  47. package/dist/lib/browser/index.mjs.map +0 -7
  48. package/dist/lib/browser/meta.json +0 -1
  49. package/dist/lib/node-esm/index.mjs +0 -1036
  50. package/dist/lib/node-esm/index.mjs.map +0 -7
  51. package/dist/lib/node-esm/meta.json +0 -1
@@ -6,7 +6,7 @@ var __export = (target, all) => {
6
6
 
7
7
  // src/errors.ts
8
8
  import { BaseError } from "@dxos/errors";
9
- var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAILABLE", "Service not available") {
9
+ var ServiceNotAvailableError = class extends BaseError.extend("ServiceNotAvailable", "Service not available") {
10
10
  constructor(service, options) {
11
11
  super({
12
12
  context: {
@@ -16,7 +16,7 @@ var ServiceNotAvailableError = class extends BaseError.extend("SERVICE_NOT_AVAIL
16
16
  });
17
17
  }
18
18
  };
19
- var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND", "Function not found") {
19
+ var FunctionNotFoundError = class extends BaseError.extend("FunctionNotFound", "Function not found") {
20
20
  constructor(functionKey, options) {
21
21
  super({
22
22
  context: {
@@ -26,9 +26,9 @@ var FunctionNotFoundError = class extends BaseError.extend("FUNCTION_NOT_FOUND",
26
26
  });
27
27
  }
28
28
  };
29
- var FunctionError = class extends BaseError.extend("FUNCTION_ERROR", "Function invocation error") {
29
+ var FunctionError = class extends BaseError.extend("FunctionError", "Function invocation error") {
30
30
  };
31
- var TriggerStateNotFoundError = class extends BaseError.extend("TRIGGER_STATE_NOT_FOUND", "Trigger state not found") {
31
+ var TriggerStateNotFoundError = class extends BaseError.extend("TriggerStateNotFound", "Trigger state not found") {
32
32
  };
33
33
 
34
34
  // src/example/fib.ts
@@ -38,8 +38,9 @@ import * as Schema6 from "effect/Schema";
38
38
  // src/sdk.ts
39
39
  import * as Effect from "effect/Effect";
40
40
  import * as Schema5 from "effect/Schema";
41
- import { Obj as Obj5, Type as Type5 } from "@dxos/echo";
41
+ import { Obj as Obj4, Type as Type5 } from "@dxos/echo";
42
42
  import { assertArgument, failedInvariant } from "@dxos/invariant";
43
+ import { Operation } from "@dxos/operation";
43
44
 
44
45
  // src/types/Function.ts
45
46
  var Function_exports = {};
@@ -69,7 +70,7 @@ var Script = Schema.Struct({
69
70
  // Whether source has changed since last deploy.
70
71
  changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),
71
72
  source: Type.Ref(Text.Text).pipe(FormInputAnnotation.set(false))
72
- }).pipe(Type.Obj({
73
+ }).pipe(Type.object({
73
74
  typename: "dxos.org/type/Script",
74
75
  version: "0.1.0"
75
76
  }), Annotation.LabelAnnotation.set([
@@ -111,7 +112,7 @@ var Function = Schema2.Struct({
111
112
  services: Schema2.optional(Schema2.Array(Schema2.String)),
112
113
  // Local binding to a function name.
113
114
  binding: Schema2.optional(Schema2.String)
114
- }).pipe(Type2.Obj({
115
+ }).pipe(Type2.object({
115
116
  typename: "dxos.org/type/Function",
116
117
  version: "0.1.0"
117
118
  }), Annotation2.LabelAnnotation.set([
@@ -119,14 +120,16 @@ var Function = Schema2.Struct({
119
120
  ]), SystemTypeAnnotation.set(true));
120
121
  var make2 = (props) => Obj2.make(Function, props);
121
122
  var setFrom = (target, source) => {
122
- target.key = source.key ?? target.key;
123
- target.name = source.name ?? target.name;
124
- target.version = source.version;
125
- target.description = source.description;
126
- target.updated = source.updated;
127
- target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : void 0;
128
- target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : void 0;
129
- Obj2.getMeta(target).keys = JSON.parse(JSON.stringify(Obj2.getMeta(source).keys));
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
+ });
130
133
  };
131
134
 
132
135
  // src/types/Trigger.ts
@@ -147,6 +150,7 @@ import * as SchemaAST from "effect/SchemaAST";
147
150
  import { Obj as Obj3, QueryAST, Type as Type3 } from "@dxos/echo";
148
151
  import { OptionsAnnotationId, SystemTypeAnnotation as SystemTypeAnnotation2 } from "@dxos/echo/internal";
149
152
  import { DXN } from "@dxos/keys";
153
+ import { Expando } from "@dxos/schema";
150
154
  var Kinds = [
151
155
  "email",
152
156
  "queue",
@@ -159,12 +163,12 @@ var kindLiteralAnnotations = {
159
163
  };
160
164
  var EmailSpec = Schema3.Struct({
161
165
  kind: Schema3.Literal("email").annotations(kindLiteralAnnotations)
162
- }).pipe(Schema3.mutable);
166
+ });
163
167
  var QueueSpec = Schema3.Struct({
164
168
  kind: Schema3.Literal("queue").annotations(kindLiteralAnnotations),
165
169
  // TODO(dmaretskyi): Change to a reference.
166
170
  queue: DXN.Schema
167
- }).pipe(Schema3.mutable);
171
+ });
168
172
  var SubscriptionSpec = Schema3.Struct({
169
173
  kind: Schema3.Literal("subscription").annotations(kindLiteralAnnotations),
170
174
  query: Schema3.Struct({
@@ -172,7 +176,7 @@ var SubscriptionSpec = Schema3.Struct({
172
176
  title: "Query"
173
177
  })),
174
178
  ast: QueryAST.Query
175
- }).pipe(Schema3.mutable),
179
+ }),
176
180
  options: Schema3.optional(Schema3.Struct({
177
181
  // Watch changes to object (not just creation).
178
182
  deep: Schema3.optional(Schema3.Boolean.annotations({
@@ -185,7 +189,7 @@ var SubscriptionSpec = Schema3.Struct({
185
189
  }).annotations({
186
190
  title: "Options"
187
191
  }))
188
- }).pipe(Schema3.mutable);
192
+ });
189
193
  var TimerSpec = Schema3.Struct({
190
194
  kind: Schema3.Literal("timer").annotations(kindLiteralAnnotations),
191
195
  cron: Schema3.String.annotations({
@@ -194,7 +198,7 @@ var TimerSpec = Schema3.Struct({
194
198
  "0 0 * * *"
195
199
  ]
196
200
  })
197
- }).pipe(Schema3.mutable);
201
+ });
198
202
  var WebhookSpec = Schema3.Struct({
199
203
  kind: Schema3.Literal("webhook").annotations(kindLiteralAnnotations),
200
204
  method: Schema3.optional(Schema3.String.annotations({
@@ -207,16 +211,16 @@ var WebhookSpec = Schema3.Struct({
207
211
  port: Schema3.optional(Schema3.Number.annotations({
208
212
  title: "Port"
209
213
  }))
210
- }).pipe(Schema3.mutable);
214
+ });
211
215
  var Spec = Schema3.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({
212
216
  title: "Trigger"
213
217
  });
214
- var Trigger_ = Schema3.Struct({
218
+ var TriggerSchema = Schema3.Struct({
215
219
  /**
216
220
  * Function or workflow to invoke.
217
221
  */
218
222
  // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).
219
- function: Schema3.optional(Type3.Ref(Type3.Expando).annotations({
223
+ function: Schema3.optional(Type3.Ref(Expando.Expando).annotations({
220
224
  title: "Function"
221
225
  })),
222
226
  /**
@@ -227,10 +231,17 @@ var Trigger_ = Schema3.Struct({
227
231
  inputNodeId: Schema3.optional(Schema3.String.annotations({
228
232
  title: "Input Node ID"
229
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.
230
236
  enabled: Schema3.optional(Schema3.Boolean.annotations({
231
237
  title: "Enabled"
232
238
  })),
233
239
  spec: Schema3.optional(Spec),
240
+ concurrency: Schema3.optional(Schema3.Number.annotations({
241
+ title: "Concurrency",
242
+ default: 1,
243
+ description: "Maximum number of concurrent invocations of the trigger. For queue triggers, this will process queue items in parallel."
244
+ })),
234
245
  /**
235
246
  * Passed as the input data to the function.
236
247
  * Must match the function's input schema.
@@ -242,15 +253,15 @@ var Trigger_ = Schema3.Struct({
242
253
  * mailbox: { '/': 'dxn:echo:AAA:ZZZ' }
243
254
  * }
244
255
  */
245
- input: Schema3.optional(Schema3.mutable(Schema3.Record({
256
+ input: Schema3.optional(Schema3.Record({
246
257
  key: Schema3.String,
247
258
  value: Schema3.Any
248
- })))
249
- }).pipe(Type3.Obj({
259
+ }))
260
+ }).pipe(Type3.object({
250
261
  typename: "dxos.org/type/Trigger",
251
262
  version: "0.1.0"
252
263
  }), SystemTypeAnnotation2.set(true));
253
- var Trigger = Trigger_;
264
+ var Trigger = TriggerSchema;
254
265
  var make3 = (props) => Obj3.make(Trigger, props);
255
266
 
256
267
  // src/types/TriggerEvent.ts
@@ -260,22 +271,23 @@ __export(TriggerEvent_exports, {
260
271
  QueueEvent: () => QueueEvent,
261
272
  SubscriptionEvent: () => SubscriptionEvent,
262
273
  TimerEvent: () => TimerEvent,
274
+ TriggerEvent: () => TriggerEvent,
263
275
  WebhookEvent: () => WebhookEvent
264
276
  });
265
277
  import * as Schema4 from "effect/Schema";
266
- import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
267
- var EmailEvent = Schema4.mutable(Schema4.Struct({
278
+ import { DXN as DXN2, Type as Type4 } from "@dxos/echo";
279
+ var EmailEvent = Schema4.Struct({
268
280
  from: Schema4.String,
269
281
  to: Schema4.String,
270
282
  subject: Schema4.String,
271
283
  created: Schema4.String,
272
284
  body: Schema4.String
273
- }));
274
- var QueueEvent = Schema4.mutable(Schema4.Struct({
285
+ });
286
+ var QueueEvent = Schema4.Struct({
275
287
  queue: DXN2.Schema,
276
288
  item: Schema4.Any,
277
289
  cursor: Schema4.String
278
- }));
290
+ });
279
291
  var SubscriptionEvent = Schema4.Struct({
280
292
  /**
281
293
  * Type of the mutation.
@@ -285,16 +297,16 @@ var SubscriptionEvent = Schema4.Struct({
285
297
  /**
286
298
  * Reference to the object that was changed or created.
287
299
  */
288
- subject: Type4.Ref(Obj4.Any),
300
+ subject: Type4.Ref(Type4.Obj),
289
301
  /**
290
302
  * @deprecated
291
303
  */
292
304
  changedObjectId: Schema4.optional(Schema4.String)
293
- }).pipe(Schema4.mutable);
294
- var TimerEvent = Schema4.mutable(Schema4.Struct({
305
+ });
306
+ var TimerEvent = Schema4.Struct({
295
307
  tick: Schema4.Number
296
- }));
297
- var WebhookEvent = Schema4.mutable(Schema4.Struct({
308
+ });
309
+ var WebhookEvent = Schema4.Struct({
298
310
  url: Schema4.String,
299
311
  method: Schema4.Literal("GET", "POST"),
300
312
  headers: Schema4.Record({
@@ -302,7 +314,8 @@ var WebhookEvent = Schema4.mutable(Schema4.Struct({
302
314
  value: Schema4.String
303
315
  }),
304
316
  bodyText: Schema4.String
305
- }));
317
+ });
318
+ var TriggerEvent = Schema4.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);
306
319
 
307
320
  // src/types/url.ts
308
321
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
@@ -376,10 +389,39 @@ var getServiceKeys = (services) => {
376
389
  if (typeof tag.key === "string") {
377
390
  return tag.key;
378
391
  }
379
- console.log(tag);
380
392
  failedInvariant();
381
393
  });
382
394
  };
395
+ var toOperation = (functionDef) => {
396
+ const op = Operation.make({
397
+ schema: {
398
+ input: functionDef.inputSchema,
399
+ output: functionDef.outputSchema ?? Schema5.Any
400
+ },
401
+ meta: {
402
+ key: functionDef.key,
403
+ name: functionDef.name,
404
+ description: functionDef.description
405
+ }
406
+ });
407
+ const operationHandler = (input) => {
408
+ const result = functionDef.handler({
409
+ context: {},
410
+ data: input
411
+ });
412
+ if (Effect.isEffect(result)) {
413
+ return result;
414
+ }
415
+ if (result instanceof Promise) {
416
+ return Effect.tryPromise(() => result);
417
+ }
418
+ return Effect.succeed(result);
419
+ };
420
+ return {
421
+ ...op,
422
+ handler: operationHandler
423
+ };
424
+ };
383
425
  var FunctionDefinition = {
384
426
  make: defineFunction,
385
427
  isFunction: (value2) => {
@@ -390,9 +432,10 @@ var FunctionDefinition = {
390
432
  return serializeFunction(functionDef);
391
433
  },
392
434
  deserialize: (functionObj) => {
393
- assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
435
+ assertArgument(Obj4.instanceOf(Function_exports.Function, functionObj), "functionObj");
394
436
  return deserializeFunction(functionObj);
395
- }
437
+ },
438
+ toOperation
396
439
  };
397
440
  var serializeFunction = (functionDef) => {
398
441
  const fn4 = Function_exports.make({
@@ -405,7 +448,7 @@ var serializeFunction = (functionDef) => {
405
448
  services: functionDef.services
406
449
  });
407
450
  if (functionDef.meta?.deployedFunctionId) {
408
- setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
451
+ Obj4.change(fn4, (fn5) => setUserFunctionIdInMetadata(Obj4.getMeta(fn5), functionDef.meta.deployedFunctionId));
409
452
  }
410
453
  return fn4;
411
454
  };
@@ -424,7 +467,7 @@ var deserializeFunction = (functionObj) => {
424
467
  services: functionObj.services ?? [],
425
468
  types: [],
426
469
  meta: {
427
- deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
470
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj4.getMeta(functionObj))
428
471
  }
429
472
  };
430
473
  };
@@ -533,12 +576,12 @@ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/fu
533
576
  }));
534
577
  return new ConfiguredCredentialsService(serviceCredentials);
535
578
  }));
536
- static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
579
+ static layerFromDatabase = ({ caching = false } = {}) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
537
580
  const dbService = yield* Database.Service;
538
581
  const cache = /* @__PURE__ */ new Map();
539
582
  const queryCredentials = async (query) => {
540
583
  const cacheKey = JSON.stringify(query);
541
- if (cache.has(cacheKey)) {
584
+ if (caching && cache.has(cacheKey)) {
542
585
  return cache.get(cacheKey);
543
586
  }
544
587
  const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
@@ -546,7 +589,9 @@ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/fu
546
589
  service: accessToken.source,
547
590
  apiKey: accessToken.token
548
591
  }));
549
- cache.set(cacheKey, credentials);
592
+ if (caching) {
593
+ cache.set(cacheKey, credentials);
594
+ }
550
595
  return credentials;
551
596
  };
552
597
  return {
@@ -583,18 +628,17 @@ var ConfiguredCredentialsService = class {
583
628
  return credential;
584
629
  }
585
630
  };
586
- var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
587
- const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
588
- const authorization = kind ? `${kind} ${key}` : key;
631
+ var withAuthorization = (token, kind) => HttpClient.mapRequest((request) => {
632
+ const authorization = kind ? `${kind} ${token}` : token;
589
633
  return HttpClientRequest.setHeader(request, "Authorization", authorization);
590
- }));
634
+ });
591
635
 
592
636
  // src/services/event-logger.ts
593
637
  import * as Context3 from "effect/Context";
594
638
  import * as Effect7 from "effect/Effect";
595
639
  import * as Layer3 from "effect/Layer";
596
640
  import * as Schema9 from "effect/Schema";
597
- import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
641
+ import { Obj as Obj6, Type as Type6 } from "@dxos/echo";
598
642
  import { invariant } from "@dxos/invariant";
599
643
  import { LogLevel, log as log2 } from "@dxos/log";
600
644
 
@@ -603,13 +647,20 @@ import * as Context2 from "effect/Context";
603
647
  import * as Effect6 from "effect/Effect";
604
648
  import * as Layer2 from "effect/Layer";
605
649
  import { AgentStatus } from "@dxos/ai";
606
- import { Obj as Obj6 } from "@dxos/echo";
650
+ import { Obj as Obj5 } from "@dxos/echo";
651
+ import { ObjectId } from "@dxos/keys";
607
652
  import { Message } from "@dxos/types";
608
653
  var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
609
654
  static noop = {
610
655
  getTraceContext: () => ({}),
611
656
  write: () => {
612
- }
657
+ },
658
+ traceInvocationStart: () => Effect6.sync(() => ({
659
+ invocationId: ObjectId.random(),
660
+ invocationTraceQueue: void 0
661
+ })),
662
+ traceInvocationEnd: () => Effect6.sync(() => {
663
+ })
613
664
  };
614
665
  static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
615
666
  /**
@@ -619,32 +670,43 @@ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions
619
670
  const tracing = yield* _TracingService;
620
671
  const context = mapContext(tracing.getTraceContext());
621
672
  return {
622
- write: (event) => tracing.write(event),
623
- getTraceContext: () => context
673
+ write: (event, context2) => tracing.write(event, context2),
674
+ getTraceContext: () => context,
675
+ traceInvocationStart: () => Effect6.die("Tracing invocation inside another invocation is not supported."),
676
+ traceInvocationEnd: () => Effect6.die("Tracing invocation inside another invocation is not supported.")
624
677
  };
625
678
  }));
626
679
  /**
680
+ * Create sublayer to trace an invocation.
681
+ * @param data
682
+ * @returns
683
+ */
684
+ static layerInvocation = (data) => _TracingService.layerSubframe((context) => ({
685
+ ...context,
686
+ currentInvocation: data
687
+ }));
688
+ /**
627
689
  * Emit the current human-readable execution status.
628
690
  */
629
691
  static emitStatus = Effect6.fnUntraced(function* (data) {
630
692
  const tracing = yield* _TracingService;
631
- tracing.write(Obj6.make(AgentStatus, {
693
+ tracing.write(Obj5.make(AgentStatus, {
632
694
  parentMessage: tracing.getTraceContext().parentMessage,
633
695
  toolCallId: tracing.getTraceContext().toolCallId,
634
696
  created: (/* @__PURE__ */ new Date()).toISOString(),
635
697
  ...data
636
- }));
698
+ }), tracing.getTraceContext());
637
699
  });
638
700
  static emitConverationMessage = Effect6.fnUntraced(function* (data) {
639
701
  const tracing = yield* _TracingService;
640
- tracing.write(Obj6.make(Message.Message, {
702
+ tracing.write(Obj5.make(Message.Message, {
641
703
  parentMessage: tracing.getTraceContext().parentMessage,
642
704
  ...data,
643
705
  properties: {
644
706
  [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
645
707
  ...data.properties
646
708
  }
647
- }));
709
+ }), tracing.getTraceContext());
648
710
  });
649
711
  };
650
712
  var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
@@ -682,7 +744,7 @@ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
682
744
  }));
683
745
  var ComputeEvent = Schema9.Struct({
684
746
  payload: ComputeEventPayload
685
- }).pipe(Type6.Obj({
747
+ }).pipe(Type6.object({
686
748
  typename: "dxos.org/type/ComputeEvent",
687
749
  version: "0.1.0"
688
750
  }));
@@ -699,9 +761,9 @@ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/f
699
761
  const tracing = yield* TracingService;
700
762
  return {
701
763
  log: (event) => {
702
- tracing.write(Obj7.make(ComputeEvent, {
764
+ tracing.write(Obj6.make(ComputeEvent, {
703
765
  payload: event
704
- }));
766
+ }), tracing.getTraceContext());
705
767
  },
706
768
  nodeId: void 0
707
769
  };
@@ -757,16 +819,22 @@ var createEventLogger = (level, message = "event") => {
757
819
  // src/services/function-invocation-service.ts
758
820
  import * as Context4 from "effect/Context";
759
821
  import * as Effect8 from "effect/Effect";
822
+ import * as Layer4 from "effect/Layer";
760
823
  var FunctionInvocationService = class _FunctionInvocationService extends Context4.Tag("@dxos/functions/FunctionInvocationService")() {
824
+ static layerNotAvailable = Layer4.succeed(_FunctionInvocationService, {
825
+ invokeFunction: () => Effect8.die("FunctionInvocationService is not avaialble."),
826
+ resolveFunction: () => Effect8.die("FunctionInvocationService is not available.")
827
+ });
761
828
  static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
829
+ static resolveFunction = (key) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.resolveFunction)(key);
762
830
  };
763
831
 
764
832
  // src/services/queues.ts
765
833
  import * as Context5 from "effect/Context";
766
834
  import * as Effect9 from "effect/Effect";
767
- import * as Layer4 from "effect/Layer";
835
+ import * as Layer5 from "effect/Layer";
768
836
  var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
769
- static notAvailable = Layer4.succeed(_QueueService, {
837
+ static notAvailable = Layer5.succeed(_QueueService, {
770
838
  queues: {
771
839
  get(_dxn) {
772
840
  throw new Error("Queues not available");
@@ -783,7 +851,7 @@ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/Que
783
851
  queue
784
852
  };
785
853
  };
786
- static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
854
+ static layer = (queues, queue) => Layer5.succeed(_QueueService, _QueueService.make(queues, queue));
787
855
  /**
788
856
  * Gets a queue by its DXN.
789
857
  */
@@ -795,23 +863,83 @@ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/Que
795
863
  static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
796
864
  };
797
865
  var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
798
- static layer = (queue) => Layer4.succeed(_ContextQueueService, {
866
+ static layer = (queue) => Layer5.succeed(_ContextQueueService, {
799
867
  queue
800
868
  });
801
869
  };
802
870
 
803
871
  // src/protocol/protocol.ts
804
- import * as Effect10 from "effect/Effect";
805
- import * as Layer5 from "effect/Layer";
872
+ import * as AnthropicClient from "@effect/ai-anthropic/AnthropicClient";
873
+ import * as Effect11 from "effect/Effect";
874
+ import * as Layer7 from "effect/Layer";
806
875
  import * as Schema10 from "effect/Schema";
807
876
  import * as SchemaAST2 from "effect/SchemaAST";
808
- import { AiService } from "@dxos/ai";
877
+ import { AiModelResolver, AiService } from "@dxos/ai";
878
+ import { AnthropicResolver } from "@dxos/ai/resolvers";
809
879
  import { LifecycleState, Resource } from "@dxos/context";
810
- import { Database as Database2, Type as Type7 } from "@dxos/echo";
880
+ import { Database as Database2, Ref as Ref2, Type as Type7 } from "@dxos/echo";
881
+ import { refFromEncodedReference } from "@dxos/echo/internal";
811
882
  import { EchoClient } from "@dxos/echo-db";
812
883
  import { runAndForwardErrors } from "@dxos/effect";
813
884
  import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
814
885
  import { PublicKey } from "@dxos/keys";
886
+
887
+ // src/protocol/functions-ai-http-client.ts
888
+ import * as Headers from "@effect/platform/Headers";
889
+ import * as HttpClient2 from "@effect/platform/HttpClient";
890
+ import * as HttpClientError from "@effect/platform/HttpClientError";
891
+ import * as HttpClientResponse from "@effect/platform/HttpClientResponse";
892
+ import * as Effect10 from "effect/Effect";
893
+ import * as FiberRef from "effect/FiberRef";
894
+ import * as Layer6 from "effect/Layer";
895
+ import * as Stream from "effect/Stream";
896
+ import { log as log3 } from "@dxos/log";
897
+ import { ErrorCodec } from "@dxos/protocols";
898
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/functions-ai-http-client.ts";
899
+ var requestInitTagKey = "@effect/platform/FetchHttpClient/FetchOptions";
900
+ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
901
+ static make = (service) => HttpClient2.make((request, url, signal, fiber) => {
902
+ const context = fiber.getFiberRef(FiberRef.currentContext);
903
+ const options = context.unsafeMap.get(requestInitTagKey) ?? {};
904
+ const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers;
905
+ const send = (body) => Effect10.tryPromise({
906
+ try: () => service.fetch(new Request(url, {
907
+ ...options,
908
+ method: request.method,
909
+ headers,
910
+ body
911
+ })),
912
+ catch: (cause) => {
913
+ log3.error("Failed to fetch", {
914
+ errorSerialized: ErrorCodec.encode(cause)
915
+ }, {
916
+ F: __dxlog_file2,
917
+ L: 43,
918
+ S: this,
919
+ C: (f, a) => f(...a)
920
+ });
921
+ return new HttpClientError.RequestError({
922
+ request,
923
+ reason: "Transport",
924
+ cause
925
+ });
926
+ }
927
+ }).pipe(Effect10.map((response) => HttpClientResponse.fromWeb(request, response)));
928
+ switch (request.body._tag) {
929
+ case "Raw":
930
+ case "Uint8Array":
931
+ return send(request.body.body);
932
+ case "FormData":
933
+ return send(request.body.formData);
934
+ case "Stream":
935
+ return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect10.flatMap(send));
936
+ }
937
+ return send(void 0);
938
+ });
939
+ static layer = (service) => Layer6.succeed(HttpClient2.HttpClient, _FunctionsAiHttpClient.make(service));
940
+ };
941
+
942
+ // src/protocol/protocol.ts
815
943
  function _ts_add_disposable_resource(env, value2, async) {
816
944
  if (value2 !== null && value2 !== void 0) {
817
945
  if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
@@ -877,7 +1005,7 @@ function _ts_dispose_resources(env) {
877
1005
  return next();
878
1006
  })(env);
879
1007
  }
880
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
1008
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
881
1009
  var wrapFunctionHandler = (func) => {
882
1010
  if (!FunctionDefinition.isFunction(func)) {
883
1011
  throw new TypeError("Invalid function definition");
@@ -917,8 +1045,8 @@ var wrapFunctionHandler = (func) => {
917
1045
  const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
918
1046
  if (func.types.length > 0) {
919
1047
  invariant2(funcContext.db, "Database is required for functions with types", {
920
- F: __dxlog_file2,
921
- L: 64,
1048
+ F: __dxlog_file3,
1049
+ L: 68,
922
1050
  S: void 0,
923
1051
  A: [
924
1052
  "funcContext.db",
@@ -927,13 +1055,14 @@ var wrapFunctionHandler = (func) => {
927
1055
  });
928
1056
  await funcContext.db.graph.schemaRegistry.register(func.types);
929
1057
  }
1058
+ const dataWithDecodedRefs = funcContext.db && !SchemaAST2.isAnyKeyword(func.inputSchema.ast) ? decodeRefsFromSchema(func.inputSchema.ast, data, funcContext.db) : data;
930
1059
  let result = await func.handler({
931
1060
  // TODO(dmaretskyi): Fix the types.
932
1061
  context,
933
- data
1062
+ data: dataWithDecodedRefs
934
1063
  });
935
- if (Effect10.isEffect(result)) {
936
- result = await runAndForwardErrors(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
1064
+ if (Effect11.isEffect(result)) {
1065
+ result = await runAndForwardErrors(result.pipe(Effect11.orDie, Effect11.provide(funcContext.createLayer())));
937
1066
  }
938
1067
  if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
939
1068
  Schema10.validateSync(func.outputSchema)(result);
@@ -986,18 +1115,87 @@ var FunctionContext = class extends Resource {
986
1115
  }
987
1116
  createLayer() {
988
1117
  assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
989
- const dbLayer = this.db ? Database2.Service.layer(this.db) : Database2.Service.notAvailable;
1118
+ const dbLayer = this.db ? Database2.layer(this.db) : Database2.notAvailable;
990
1119
  const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
991
- const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
1120
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase({
1121
+ caching: true
1122
+ }).pipe(Layer7.provide(dbLayer)) : CredentialsService.configuredLayer([]);
992
1123
  const functionInvocationService = MockedFunctionInvocationService;
993
- const aiService = AiService.notAvailable;
994
1124
  const tracing = TracingService.layerNoop;
995
- return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
1125
+ const aiLayer = this.context.services.functionsAiService ? AiModelResolver.AiModelResolver.buildAiService.pipe(Layer7.provide(AnthropicResolver.make().pipe(Layer7.provide(AnthropicClient.layer({
1126
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
1127
+ apiUrl: "http://internal/provider/anthropic"
1128
+ }).pipe(Layer7.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))))))) : AiService.notAvailable;
1129
+ return Layer7.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiLayer, tracing);
996
1130
  }
997
1131
  };
998
- var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
999
- invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
1132
+ var MockedFunctionInvocationService = Layer7.succeed(FunctionInvocationService, {
1133
+ invokeFunction: () => Effect11.die("Calling functions from functions is not implemented yet."),
1134
+ resolveFunction: () => Effect11.die("Not implemented.")
1000
1135
  });
1136
+ var decodeRefsFromSchema = (ast, value2, db) => {
1137
+ if (value2 == null) {
1138
+ return value2;
1139
+ }
1140
+ const encoded = SchemaAST2.encodedBoundAST(ast);
1141
+ if (Ref2.isRefType(encoded)) {
1142
+ if (Ref2.isRef(value2)) {
1143
+ return value2;
1144
+ }
1145
+ if (typeof value2 === "object" && value2 !== null && typeof value2["/"] === "string") {
1146
+ const resolver = db.graph.createRefResolver({
1147
+ context: {
1148
+ space: db.spaceId
1149
+ }
1150
+ });
1151
+ return refFromEncodedReference(value2, resolver);
1152
+ }
1153
+ return value2;
1154
+ }
1155
+ switch (encoded._tag) {
1156
+ case "TypeLiteral": {
1157
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
1158
+ return value2;
1159
+ }
1160
+ const result = {
1161
+ ...value2
1162
+ };
1163
+ for (const prop of SchemaAST2.getPropertySignatures(encoded)) {
1164
+ const key = prop.name.toString();
1165
+ if (key in result) {
1166
+ result[key] = decodeRefsFromSchema(prop.type, result[key], db);
1167
+ }
1168
+ }
1169
+ return result;
1170
+ }
1171
+ case "TupleType": {
1172
+ if (!Array.isArray(value2)) {
1173
+ return value2;
1174
+ }
1175
+ if (encoded.elements.length === 0 && encoded.rest.length === 1) {
1176
+ const elementType = encoded.rest[0].type;
1177
+ return value2.map((item) => decodeRefsFromSchema(elementType, item, db));
1178
+ }
1179
+ return value2;
1180
+ }
1181
+ case "Union": {
1182
+ const nonUndefined = encoded.types.filter((t) => !SchemaAST2.isUndefinedKeyword(t));
1183
+ if (nonUndefined.length === 1) {
1184
+ return decodeRefsFromSchema(nonUndefined[0], value2, db);
1185
+ }
1186
+ return value2;
1187
+ }
1188
+ case "Suspend": {
1189
+ return decodeRefsFromSchema(encoded.f(), value2, db);
1190
+ }
1191
+ case "Refinement": {
1192
+ return decodeRefsFromSchema(encoded.from, value2, db);
1193
+ }
1194
+ default: {
1195
+ return value2;
1196
+ }
1197
+ }
1198
+ };
1001
1199
  export {
1002
1200
  ComputeEvent,
1003
1201
  ComputeEventLogger,
@@ -1029,6 +1227,7 @@ export {
1029
1227
  logCustomEvent,
1030
1228
  serializeFunction,
1031
1229
  setUserFunctionIdInMetadata,
1230
+ toOperation,
1032
1231
  withAuthorization,
1033
1232
  wrapFunctionHandler
1034
1233
  };