@dxos/functions 0.8.4-main.7ace549 → 0.8.4-main.937b3ca

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 (52) hide show
  1. package/dist/lib/browser/index.mjs +273 -74
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +273 -74
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +24 -32
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  10. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  11. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  12. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  13. package/dist/types/src/protocol/protocol.d.ts.map +1 -1
  14. package/dist/types/src/sdk.d.ts +18 -4
  15. package/dist/types/src/sdk.d.ts.map +1 -1
  16. package/dist/types/src/services/credentials.d.ts +6 -4
  17. package/dist/types/src/services/credentials.d.ts.map +1 -1
  18. package/dist/types/src/services/event-logger.d.ts +25 -31
  19. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  20. package/dist/types/src/services/function-invocation-service.d.ts +5 -0
  21. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  22. package/dist/types/src/services/index.d.ts +0 -1
  23. package/dist/types/src/services/index.d.ts.map +1 -1
  24. package/dist/types/src/services/tracing.d.ts +37 -3
  25. package/dist/types/src/services/tracing.d.ts.map +1 -1
  26. package/dist/types/src/types/Function.d.ts +33 -44
  27. package/dist/types/src/types/Function.d.ts.map +1 -1
  28. package/dist/types/src/types/Script.d.ts +8 -15
  29. package/dist/types/src/types/Script.d.ts.map +1 -1
  30. package/dist/types/src/types/Trigger.d.ts +37 -57
  31. package/dist/types/src/types/Trigger.d.ts.map +1 -1
  32. package/dist/types/src/types/TriggerEvent.d.ts +33 -2
  33. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
  34. package/dist/types/src/types/url.d.ts +4 -3
  35. package/dist/types/src/types/url.d.ts.map +1 -1
  36. package/dist/types/tsconfig.tsbuildinfo +1 -1
  37. package/package.json +22 -16
  38. package/src/errors.ts +4 -4
  39. package/src/operation-compatibility.test.ts +185 -0
  40. package/src/protocol/functions-ai-http-client.ts +67 -0
  41. package/src/protocol/protocol.ts +118 -12
  42. package/src/sdk.ts +55 -6
  43. package/src/services/credentials.ts +31 -15
  44. package/src/services/event-logger.ts +2 -2
  45. package/src/services/function-invocation-service.ts +14 -0
  46. package/src/services/index.ts +0 -2
  47. package/src/services/tracing.ts +63 -4
  48. package/src/types/Function.ts +12 -10
  49. package/src/types/Script.ts +3 -2
  50. package/src/types/Trigger.ts +9 -6
  51. package/src/types/TriggerEvent.ts +9 -3
  52. package/src/types/url.ts +4 -3
@@ -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",
@@ -211,12 +215,12 @@ var WebhookSpec = Schema3.Struct({
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,6 +231,8 @@ 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
  })),
@@ -246,11 +252,11 @@ var Trigger_ = Schema3.Struct({
246
252
  key: Schema3.String,
247
253
  value: Schema3.Any
248
254
  })))
249
- }).pipe(Type3.Obj({
255
+ }).pipe(Type3.object({
250
256
  typename: "dxos.org/type/Trigger",
251
257
  version: "0.1.0"
252
258
  }), SystemTypeAnnotation2.set(true));
253
- var Trigger = Trigger_;
259
+ var Trigger = TriggerSchema;
254
260
  var make3 = (props) => Obj3.make(Trigger, props);
255
261
 
256
262
  // src/types/TriggerEvent.ts
@@ -260,10 +266,11 @@ __export(TriggerEvent_exports, {
260
266
  QueueEvent: () => QueueEvent,
261
267
  SubscriptionEvent: () => SubscriptionEvent,
262
268
  TimerEvent: () => TimerEvent,
269
+ TriggerEvent: () => TriggerEvent,
263
270
  WebhookEvent: () => WebhookEvent
264
271
  });
265
272
  import * as Schema4 from "effect/Schema";
266
- import { DXN as DXN2, Obj as Obj4, Type as Type4 } from "@dxos/echo";
273
+ import { DXN as DXN2, Type as Type4 } from "@dxos/echo";
267
274
  var EmailEvent = Schema4.mutable(Schema4.Struct({
268
275
  from: Schema4.String,
269
276
  to: Schema4.String,
@@ -285,7 +292,7 @@ var SubscriptionEvent = Schema4.Struct({
285
292
  /**
286
293
  * Reference to the object that was changed or created.
287
294
  */
288
- subject: Type4.Ref(Obj4.Any),
295
+ subject: Type4.Ref(Type4.Obj),
289
296
  /**
290
297
  * @deprecated
291
298
  */
@@ -303,6 +310,7 @@ var WebhookEvent = Schema4.mutable(Schema4.Struct({
303
310
  }),
304
311
  bodyText: Schema4.String
305
312
  }));
313
+ var TriggerEvent = Schema4.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);
306
314
 
307
315
  // src/types/url.ts
308
316
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
@@ -376,10 +384,39 @@ var getServiceKeys = (services) => {
376
384
  if (typeof tag.key === "string") {
377
385
  return tag.key;
378
386
  }
379
- console.log(tag);
380
387
  failedInvariant();
381
388
  });
382
389
  };
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
400
+ }
401
+ });
402
+ const operationHandler = (input) => {
403
+ const result = functionDef.handler({
404
+ context: {},
405
+ data: input
406
+ });
407
+ if (Effect.isEffect(result)) {
408
+ return result;
409
+ }
410
+ if (result instanceof Promise) {
411
+ return Effect.tryPromise(() => result);
412
+ }
413
+ return Effect.succeed(result);
414
+ };
415
+ return {
416
+ ...op,
417
+ handler: operationHandler
418
+ };
419
+ };
383
420
  var FunctionDefinition = {
384
421
  make: defineFunction,
385
422
  isFunction: (value2) => {
@@ -390,9 +427,10 @@ var FunctionDefinition = {
390
427
  return serializeFunction(functionDef);
391
428
  },
392
429
  deserialize: (functionObj) => {
393
- assertArgument(Obj5.instanceOf(Function_exports.Function, functionObj), "functionObj");
430
+ assertArgument(Obj4.instanceOf(Function_exports.Function, functionObj), "functionObj");
394
431
  return deserializeFunction(functionObj);
395
- }
432
+ },
433
+ toOperation
396
434
  };
397
435
  var serializeFunction = (functionDef) => {
398
436
  const fn4 = Function_exports.make({
@@ -405,7 +443,7 @@ var serializeFunction = (functionDef) => {
405
443
  services: functionDef.services
406
444
  });
407
445
  if (functionDef.meta?.deployedFunctionId) {
408
- setUserFunctionIdInMetadata(Obj5.getMeta(fn4), functionDef.meta.deployedFunctionId);
446
+ Obj4.change(fn4, (fn5) => setUserFunctionIdInMetadata(Obj4.getMeta(fn5), functionDef.meta.deployedFunctionId));
409
447
  }
410
448
  return fn4;
411
449
  };
@@ -424,7 +462,7 @@ var deserializeFunction = (functionObj) => {
424
462
  services: functionObj.services ?? [],
425
463
  types: [],
426
464
  meta: {
427
- deployedFunctionId: getUserFunctionIdInMetadata(Obj5.getMeta(functionObj))
465
+ deployedFunctionId: getUserFunctionIdInMetadata(Obj4.getMeta(functionObj))
428
466
  }
429
467
  };
430
468
  };
@@ -501,9 +539,6 @@ var sleep_default = defineFunction({
501
539
  })(Example || (Example = {}));
502
540
  var Example;
503
541
 
504
- // src/services/index.ts
505
- import { DatabaseService as DatabaseService2 } from "@dxos/echo-db";
506
-
507
542
  // src/services/credentials.ts
508
543
  import * as HttpClient from "@effect/platform/HttpClient";
509
544
  import * as HttpClientRequest from "@effect/platform/HttpClientRequest";
@@ -512,7 +547,7 @@ import * as Effect5 from "effect/Effect";
512
547
  import * as Layer from "effect/Layer";
513
548
  import * as Redacted from "effect/Redacted";
514
549
  import { Query } from "@dxos/echo";
515
- import { DatabaseService } from "@dxos/echo-db";
550
+ import { Database } from "@dxos/echo";
516
551
  import { AccessToken } from "@dxos/types";
517
552
  var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/functions/CredentialsService")() {
518
553
  static getCredential = (query) => Effect5.gen(function* () {
@@ -536,14 +571,23 @@ var CredentialsService = class _CredentialsService extends Context.Tag("@dxos/fu
536
571
  }));
537
572
  return new ConfiguredCredentialsService(serviceCredentials);
538
573
  }));
539
- static layerFromDatabase = () => Layer.effect(_CredentialsService, Effect5.gen(function* () {
540
- const dbService = yield* DatabaseService;
574
+ static layerFromDatabase = ({ caching = false } = {}) => Layer.effect(_CredentialsService, Effect5.gen(function* () {
575
+ const dbService = yield* Database.Service;
576
+ const cache = /* @__PURE__ */ new Map();
541
577
  const queryCredentials = async (query) => {
542
- const { objects: accessTokens } = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
543
- return accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
578
+ const cacheKey = JSON.stringify(query);
579
+ if (caching && cache.has(cacheKey)) {
580
+ return cache.get(cacheKey);
581
+ }
582
+ const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();
583
+ const credentials = accessTokens.filter((accessToken) => accessToken.source === query.service).map((accessToken) => ({
544
584
  service: accessToken.source,
545
585
  apiKey: accessToken.token
546
586
  }));
587
+ if (caching) {
588
+ cache.set(cacheKey, credentials);
589
+ }
590
+ return credentials;
547
591
  };
548
592
  return {
549
593
  getCredential: async (query) => {
@@ -579,18 +623,17 @@ var ConfiguredCredentialsService = class {
579
623
  return credential;
580
624
  }
581
625
  };
582
- var withAuthorization = (query, kind) => HttpClient.mapRequestEffect(Effect5.fnUntraced(function* (request) {
583
- const key = yield* CredentialsService.getApiKey(query).pipe(Effect5.map(Redacted.value));
584
- const authorization = kind ? `${kind} ${key}` : key;
626
+ var withAuthorization = (token, kind) => HttpClient.mapRequest((request) => {
627
+ const authorization = kind ? `${kind} ${token}` : token;
585
628
  return HttpClientRequest.setHeader(request, "Authorization", authorization);
586
- }));
629
+ });
587
630
 
588
631
  // src/services/event-logger.ts
589
632
  import * as Context3 from "effect/Context";
590
633
  import * as Effect7 from "effect/Effect";
591
634
  import * as Layer3 from "effect/Layer";
592
635
  import * as Schema9 from "effect/Schema";
593
- import { Obj as Obj7, Type as Type6 } from "@dxos/echo";
636
+ import { Obj as Obj6, Type as Type6 } from "@dxos/echo";
594
637
  import { invariant } from "@dxos/invariant";
595
638
  import { LogLevel, log as log2 } from "@dxos/log";
596
639
 
@@ -599,13 +642,20 @@ import * as Context2 from "effect/Context";
599
642
  import * as Effect6 from "effect/Effect";
600
643
  import * as Layer2 from "effect/Layer";
601
644
  import { AgentStatus } from "@dxos/ai";
602
- import { Obj as Obj6 } from "@dxos/echo";
645
+ import { Obj as Obj5 } from "@dxos/echo";
646
+ import { ObjectId } from "@dxos/keys";
603
647
  import { Message } from "@dxos/types";
604
648
  var TracingService = class _TracingService extends Context2.Tag("@dxos/functions/TracingService")() {
605
649
  static noop = {
606
650
  getTraceContext: () => ({}),
607
651
  write: () => {
608
- }
652
+ },
653
+ traceInvocationStart: () => Effect6.sync(() => ({
654
+ invocationId: ObjectId.random(),
655
+ invocationTraceQueue: void 0
656
+ })),
657
+ traceInvocationEnd: () => Effect6.sync(() => {
658
+ })
609
659
  };
610
660
  static layerNoop = Layer2.succeed(_TracingService, _TracingService.noop);
611
661
  /**
@@ -615,32 +665,43 @@ var TracingService = class _TracingService extends Context2.Tag("@dxos/functions
615
665
  const tracing = yield* _TracingService;
616
666
  const context = mapContext(tracing.getTraceContext());
617
667
  return {
618
- write: (event) => tracing.write(event),
619
- getTraceContext: () => context
668
+ write: (event, context2) => tracing.write(event, context2),
669
+ 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.")
620
672
  };
621
673
  }));
622
674
  /**
675
+ * Create sublayer to trace an invocation.
676
+ * @param data
677
+ * @returns
678
+ */
679
+ static layerInvocation = (data) => _TracingService.layerSubframe((context) => ({
680
+ ...context,
681
+ currentInvocation: data
682
+ }));
683
+ /**
623
684
  * Emit the current human-readable execution status.
624
685
  */
625
686
  static emitStatus = Effect6.fnUntraced(function* (data) {
626
687
  const tracing = yield* _TracingService;
627
- tracing.write(Obj6.make(AgentStatus, {
688
+ tracing.write(Obj5.make(AgentStatus, {
628
689
  parentMessage: tracing.getTraceContext().parentMessage,
629
690
  toolCallId: tracing.getTraceContext().toolCallId,
630
691
  created: (/* @__PURE__ */ new Date()).toISOString(),
631
692
  ...data
632
- }));
693
+ }), tracing.getTraceContext());
633
694
  });
634
695
  static emitConverationMessage = Effect6.fnUntraced(function* (data) {
635
696
  const tracing = yield* _TracingService;
636
- tracing.write(Obj6.make(Message.Message, {
697
+ tracing.write(Obj5.make(Message.Message, {
637
698
  parentMessage: tracing.getTraceContext().parentMessage,
638
699
  ...data,
639
700
  properties: {
640
701
  [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,
641
702
  ...data.properties
642
703
  }
643
- }));
704
+ }), tracing.getTraceContext());
644
705
  });
645
706
  };
646
707
  var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
@@ -678,7 +739,7 @@ var ComputeEventPayload = Schema9.Union(Schema9.Struct({
678
739
  }));
679
740
  var ComputeEvent = Schema9.Struct({
680
741
  payload: ComputeEventPayload
681
- }).pipe(Type6.Obj({
742
+ }).pipe(Type6.object({
682
743
  typename: "dxos.org/type/ComputeEvent",
683
744
  version: "0.1.0"
684
745
  }));
@@ -695,9 +756,9 @@ var ComputeEventLogger = class _ComputeEventLogger extends Context3.Tag("@dxos/f
695
756
  const tracing = yield* TracingService;
696
757
  return {
697
758
  log: (event) => {
698
- tracing.write(Obj7.make(ComputeEvent, {
759
+ tracing.write(Obj6.make(ComputeEvent, {
699
760
  payload: event
700
- }));
761
+ }), tracing.getTraceContext());
701
762
  },
702
763
  nodeId: void 0
703
764
  };
@@ -753,16 +814,22 @@ var createEventLogger = (level, message = "event") => {
753
814
  // src/services/function-invocation-service.ts
754
815
  import * as Context4 from "effect/Context";
755
816
  import * as Effect8 from "effect/Effect";
817
+ import * as Layer4 from "effect/Layer";
756
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.")
822
+ });
757
823
  static invokeFunction = (functionDef, input) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);
824
+ static resolveFunction = (key) => Effect8.serviceFunctionEffect(_FunctionInvocationService, (service) => service.resolveFunction)(key);
758
825
  };
759
826
 
760
827
  // src/services/queues.ts
761
828
  import * as Context5 from "effect/Context";
762
829
  import * as Effect9 from "effect/Effect";
763
- import * as Layer4 from "effect/Layer";
830
+ import * as Layer5 from "effect/Layer";
764
831
  var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/QueueService")() {
765
- static notAvailable = Layer4.succeed(_QueueService, {
832
+ static notAvailable = Layer5.succeed(_QueueService, {
766
833
  queues: {
767
834
  get(_dxn) {
768
835
  throw new Error("Queues not available");
@@ -779,7 +846,7 @@ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/Que
779
846
  queue
780
847
  };
781
848
  };
782
- static layer = (queues, queue) => Layer4.succeed(_QueueService, _QueueService.make(queues, queue));
849
+ static layer = (queues, queue) => Layer5.succeed(_QueueService, _QueueService.make(queues, queue));
783
850
  /**
784
851
  * Gets a queue by its DXN.
785
852
  */
@@ -791,22 +858,83 @@ var QueueService = class _QueueService extends Context5.Tag("@dxos/functions/Que
791
858
  static append = (queue, objects) => Effect9.promise(() => queue.append(objects));
792
859
  };
793
860
  var ContextQueueService = class _ContextQueueService extends Context5.Tag("@dxos/functions/ContextQueueService")() {
794
- static layer = (queue) => Layer4.succeed(_ContextQueueService, {
861
+ static layer = (queue) => Layer5.succeed(_ContextQueueService, {
795
862
  queue
796
863
  });
797
864
  };
798
865
 
799
866
  // src/protocol/protocol.ts
800
- import * as Effect10 from "effect/Effect";
801
- import * as Layer5 from "effect/Layer";
867
+ import * as AnthropicClient from "@effect/ai-anthropic/AnthropicClient";
868
+ import * as Effect11 from "effect/Effect";
869
+ import * as Layer7 from "effect/Layer";
802
870
  import * as Schema10 from "effect/Schema";
803
871
  import * as SchemaAST2 from "effect/SchemaAST";
804
- import { AiService } from "@dxos/ai";
872
+ import { AiModelResolver, AiService } from "@dxos/ai";
873
+ import { AnthropicResolver } from "@dxos/ai/resolvers";
805
874
  import { LifecycleState, Resource } from "@dxos/context";
806
- import { Type as Type7 } from "@dxos/echo";
875
+ import { Database as Database2, Ref as Ref2, Type as Type7 } from "@dxos/echo";
876
+ import { refFromEncodedReference } from "@dxos/echo/internal";
807
877
  import { EchoClient } from "@dxos/echo-db";
878
+ import { runAndForwardErrors } from "@dxos/effect";
808
879
  import { assertState, failedInvariant as failedInvariant2, invariant as invariant2 } from "@dxos/invariant";
809
880
  import { PublicKey } from "@dxos/keys";
881
+
882
+ // src/protocol/functions-ai-http-client.ts
883
+ import * as Headers from "@effect/platform/Headers";
884
+ import * as HttpClient2 from "@effect/platform/HttpClient";
885
+ import * as HttpClientError from "@effect/platform/HttpClientError";
886
+ import * as HttpClientResponse from "@effect/platform/HttpClientResponse";
887
+ import * as Effect10 from "effect/Effect";
888
+ import * as FiberRef from "effect/FiberRef";
889
+ import * as Layer6 from "effect/Layer";
890
+ import * as Stream from "effect/Stream";
891
+ import { log as log3 } from "@dxos/log";
892
+ import { ErrorCodec } from "@dxos/protocols";
893
+ var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/functions-ai-http-client.ts";
894
+ var requestInitTagKey = "@effect/platform/FetchHttpClient/FetchOptions";
895
+ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
896
+ static make = (service) => HttpClient2.make((request, url, signal, fiber) => {
897
+ const context = fiber.getFiberRef(FiberRef.currentContext);
898
+ const options = context.unsafeMap.get(requestInitTagKey) ?? {};
899
+ const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers;
900
+ const send = (body) => Effect10.tryPromise({
901
+ try: () => service.fetch(new Request(url, {
902
+ ...options,
903
+ method: request.method,
904
+ headers,
905
+ body
906
+ })),
907
+ catch: (cause) => {
908
+ log3.error("Failed to fetch", {
909
+ errorSerialized: ErrorCodec.encode(cause)
910
+ }, {
911
+ F: __dxlog_file2,
912
+ L: 43,
913
+ S: this,
914
+ C: (f, a) => f(...a)
915
+ });
916
+ return new HttpClientError.RequestError({
917
+ request,
918
+ reason: "Transport",
919
+ cause
920
+ });
921
+ }
922
+ }).pipe(Effect10.map((response) => HttpClientResponse.fromWeb(request, response)));
923
+ switch (request.body._tag) {
924
+ case "Raw":
925
+ case "Uint8Array":
926
+ return send(request.body.body);
927
+ case "FormData":
928
+ return send(request.body.formData);
929
+ case "Stream":
930
+ return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect10.flatMap(send));
931
+ }
932
+ return send(void 0);
933
+ });
934
+ static layer = (service) => Layer6.succeed(HttpClient2.HttpClient, _FunctionsAiHttpClient.make(service));
935
+ };
936
+
937
+ // src/protocol/protocol.ts
810
938
  function _ts_add_disposable_resource(env, value2, async) {
811
939
  if (value2 !== null && value2 !== void 0) {
812
940
  if (typeof value2 !== "object" && typeof value2 !== "function") throw new TypeError("Object expected.");
@@ -872,7 +1000,7 @@ function _ts_dispose_resources(env) {
872
1000
  return next();
873
1001
  })(env);
874
1002
  }
875
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
1003
+ var __dxlog_file3 = "/__w/dxos/dxos/packages/core/functions/src/protocol/protocol.ts";
876
1004
  var wrapFunctionHandler = (func) => {
877
1005
  if (!FunctionDefinition.isFunction(func)) {
878
1006
  throw new TypeError("Invalid function definition");
@@ -887,7 +1015,7 @@ var wrapFunctionHandler = (func) => {
887
1015
  services: func.services
888
1016
  },
889
1017
  handler: async ({ data, context }) => {
890
- if ((func.services.includes(DatabaseService2.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
1018
+ if ((func.services.includes(Database2.Service.key) || func.services.includes(QueueService.key)) && (!context.services.dataService || !context.services.queryService)) {
891
1019
  throw new FunctionError({
892
1020
  message: "Services not provided: dataService, queryService"
893
1021
  });
@@ -912,23 +1040,24 @@ var wrapFunctionHandler = (func) => {
912
1040
  const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
913
1041
  if (func.types.length > 0) {
914
1042
  invariant2(funcContext.db, "Database is required for functions with types", {
915
- F: __dxlog_file2,
916
- L: 63,
1043
+ F: __dxlog_file3,
1044
+ L: 68,
917
1045
  S: void 0,
918
1046
  A: [
919
1047
  "funcContext.db",
920
1048
  "'Database is required for functions with types'"
921
1049
  ]
922
1050
  });
923
- funcContext.db.graph.schemaRegistry.addSchema(func.types);
1051
+ await funcContext.db.graph.schemaRegistry.register(func.types);
924
1052
  }
1053
+ const dataWithDecodedRefs = funcContext.db && !SchemaAST2.isAnyKeyword(func.inputSchema.ast) ? decodeRefsFromSchema(func.inputSchema.ast, data, funcContext.db) : data;
925
1054
  let result = await func.handler({
926
1055
  // TODO(dmaretskyi): Fix the types.
927
1056
  context,
928
- data
1057
+ data: dataWithDecodedRefs
929
1058
  });
930
- if (Effect10.isEffect(result)) {
931
- result = await Effect10.runPromise(result.pipe(Effect10.orDie, Effect10.provide(funcContext.createLayer())));
1059
+ if (Effect11.isEffect(result)) {
1060
+ result = await runAndForwardErrors(result.pipe(Effect11.orDie, Effect11.provide(funcContext.createLayer())));
932
1061
  }
933
1062
  if (func.outputSchema && !SchemaAST2.isAnyKeyword(func.outputSchema.ast)) {
934
1063
  Schema10.validateSync(func.outputSchema)(result);
@@ -968,7 +1097,8 @@ var FunctionContext = class extends Resource {
968
1097
  this.db = this.client && this.context.spaceId ? this.client.constructDatabase({
969
1098
  spaceId: this.context.spaceId ?? failedInvariant2(),
970
1099
  spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant2("spaceKey missing in context")),
971
- reactiveSchemaQuery: false
1100
+ reactiveSchemaQuery: false,
1101
+ preloadSchemaOnOpen: false
972
1102
  }) : void 0;
973
1103
  await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant2("spaceRootUrl missing in context"));
974
1104
  await this.db?.open();
@@ -980,18 +1110,87 @@ var FunctionContext = class extends Resource {
980
1110
  }
981
1111
  createLayer() {
982
1112
  assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
983
- const dbLayer = this.db ? DatabaseService2.layer(this.db) : DatabaseService2.notAvailable;
1113
+ const dbLayer = this.db ? Database2.Service.layer(this.db) : Database2.Service.notAvailable;
984
1114
  const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
985
- const credentials = dbLayer ? CredentialsService.layerFromDatabase().pipe(Layer5.provide(dbLayer)) : CredentialsService.configuredLayer([]);
1115
+ const credentials = dbLayer ? CredentialsService.layerFromDatabase({
1116
+ caching: true
1117
+ }).pipe(Layer7.provide(dbLayer)) : CredentialsService.configuredLayer([]);
986
1118
  const functionInvocationService = MockedFunctionInvocationService;
987
- const aiService = AiService.notAvailable;
988
1119
  const tracing = TracingService.layerNoop;
989
- return Layer5.mergeAll(dbLayer, queuesLayer, credentials, functionInvocationService, aiService, tracing);
1120
+ const aiLayer = this.context.services.functionsAiService ? AiModelResolver.AiModelResolver.buildAiService.pipe(Layer7.provide(AnthropicResolver.make().pipe(Layer7.provide(AnthropicClient.layer({
1121
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
1122
+ 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);
990
1125
  }
991
1126
  };
992
- var MockedFunctionInvocationService = Layer5.succeed(FunctionInvocationService, {
993
- invokeFunction: () => Effect10.die("Calling functions from functions is not implemented yet.")
1127
+ var MockedFunctionInvocationService = Layer7.succeed(FunctionInvocationService, {
1128
+ invokeFunction: () => Effect11.die("Calling functions from functions is not implemented yet."),
1129
+ resolveFunction: () => Effect11.die("Not implemented.")
994
1130
  });
1131
+ var decodeRefsFromSchema = (ast, value2, db) => {
1132
+ if (value2 == null) {
1133
+ return value2;
1134
+ }
1135
+ const encoded = SchemaAST2.encodedBoundAST(ast);
1136
+ if (Ref2.isRefType(encoded)) {
1137
+ if (Ref2.isRef(value2)) {
1138
+ return value2;
1139
+ }
1140
+ if (typeof value2 === "object" && value2 !== null && typeof value2["/"] === "string") {
1141
+ const resolver = db.graph.createRefResolver({
1142
+ context: {
1143
+ space: db.spaceId
1144
+ }
1145
+ });
1146
+ return refFromEncodedReference(value2, resolver);
1147
+ }
1148
+ return value2;
1149
+ }
1150
+ switch (encoded._tag) {
1151
+ case "TypeLiteral": {
1152
+ if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) {
1153
+ return value2;
1154
+ }
1155
+ const result = {
1156
+ ...value2
1157
+ };
1158
+ 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);
1162
+ }
1163
+ }
1164
+ return result;
1165
+ }
1166
+ case "TupleType": {
1167
+ if (!Array.isArray(value2)) {
1168
+ return value2;
1169
+ }
1170
+ if (encoded.elements.length === 0 && encoded.rest.length === 1) {
1171
+ const elementType = encoded.rest[0].type;
1172
+ return value2.map((item) => decodeRefsFromSchema(elementType, item, db));
1173
+ }
1174
+ return value2;
1175
+ }
1176
+ case "Union": {
1177
+ const nonUndefined = encoded.types.filter((t) => !SchemaAST2.isUndefinedKeyword(t));
1178
+ if (nonUndefined.length === 1) {
1179
+ return decodeRefsFromSchema(nonUndefined[0], value2, db);
1180
+ }
1181
+ return value2;
1182
+ }
1183
+ case "Suspend": {
1184
+ return decodeRefsFromSchema(encoded.f(), value2, db);
1185
+ }
1186
+ case "Refinement": {
1187
+ return decodeRefsFromSchema(encoded.from, value2, db);
1188
+ }
1189
+ default: {
1190
+ return value2;
1191
+ }
1192
+ }
1193
+ };
995
1194
  export {
996
1195
  ComputeEvent,
997
1196
  ComputeEventLogger,
@@ -999,7 +1198,6 @@ export {
999
1198
  ConfiguredCredentialsService,
1000
1199
  ContextQueueService,
1001
1200
  CredentialsService,
1002
- DatabaseService2 as DatabaseService,
1003
1201
  Example,
1004
1202
  FUNCTIONS_META_KEY,
1005
1203
  FUNCTIONS_PRESET_META_KEY,
@@ -1024,6 +1222,7 @@ export {
1024
1222
  logCustomEvent,
1025
1223
  serializeFunction,
1026
1224
  setUserFunctionIdInMetadata,
1225
+ toOperation,
1027
1226
  withAuthorization,
1028
1227
  wrapFunctionHandler
1029
1228
  };