@dxos/functions 0.8.4-main.cb12b3f963 → 0.8.4-main.d05539e30a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,8 +1,105 @@
1
- MIT License
2
- Copyright (c) 2022 DXOS
1
+ # Functional Source License, Version 1.1, ALv2 Future License
3
2
 
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
3
+ ## Abbreviation
5
4
 
6
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5
+ FSL-1.1-Apache-2.0
7
6
 
8
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
7
+ ## Notice
8
+
9
+ Copyright 2026 DXOS
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under
20
+ these Terms and Conditions, as indicated by our inclusion of these Terms and
21
+ Conditions with the Software.
22
+
23
+ ### License Grant
24
+
25
+ Subject to your compliance with this License Grant and the Patents,
26
+ Redistribution and Trademark clauses below, we hereby grant you the right to
27
+ use, copy, modify, create derivative works, publicly perform, publicly display
28
+ and redistribute the Software for any Permitted Purpose identified below.
29
+
30
+ ### Permitted Purpose
31
+
32
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
33
+ means making the Software available to others in a commercial product or
34
+ service that:
35
+
36
+ 1. substitutes for the Software;
37
+
38
+ 2. substitutes for any other product or service we offer using the Software
39
+ that exists as of the date we make the Software available; or
40
+
41
+ 3. offers the same or substantially similar functionality as the Software.
42
+
43
+ Permitted Purposes specifically include using the Software:
44
+
45
+ 1. for your internal use and access;
46
+
47
+ 2. for non-commercial education;
48
+
49
+ 3. for non-commercial research; and
50
+
51
+ 4. in connection with professional services that you provide to a licensee
52
+ using the Software in accordance with these Terms and Conditions.
53
+
54
+ ### Patents
55
+
56
+ To the extent your use for a Permitted Purpose would necessarily infringe our
57
+ patents, the license grant above includes a license under our patents. If you
58
+ make a claim against any party that the Software infringes or contributes to
59
+ the infringement of any patent, then your patent license to the Software ends
60
+ immediately.
61
+
62
+ ### Redistribution
63
+
64
+ The Terms and Conditions apply to all copies, modifications and derivatives of
65
+ the Software.
66
+
67
+ If you redistribute any copies, modifications or derivatives of the Software,
68
+ you must include a copy of or a link to these Terms and Conditions and not
69
+ remove any copyright notices provided in or with the Software.
70
+
71
+ ### Disclaimer
72
+
73
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
74
+ IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
75
+ PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
76
+
77
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
78
+ SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
79
+ EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
80
+
81
+ ### Trademarks
82
+
83
+ Except for displaying the License Details and identifying us as the origin of
84
+ the Software, you have no right under these Terms and Conditions to use our
85
+ trademarks, trade names, service marks or product names.
86
+
87
+ ## Grant of Future License
88
+
89
+ We hereby irrevocably grant you an additional license to use the Software under
90
+ the Apache License, Version 2.0 that is effective on the second anniversary of
91
+ the date we make the Software available. On or after that date, you may use the
92
+ Software under the Apache License, Version 2.0, in which case the following
93
+ will apply:
94
+
95
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
96
+ this file except in compliance with the License.
97
+
98
+ You may obtain a copy of the License at
99
+
100
+ http://www.apache.org/licenses/LICENSE-2.0
101
+
102
+ Unless required by applicable law or agreed to in writing, software distributed
103
+ under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
+ CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
+ specific language governing permissions and limitations under the License.
package/README.md CHANGED
@@ -80,4 +80,4 @@ curl http://localhost:7001/dev/hello -X POST -H 'Content-Type: application/json'
80
80
 
81
81
  Your ideas, issues, and code are most welcome. Please take a look at our [community code of conduct](https://github.com/dxos/dxos/blob/main/CODE_OF_CONDUCT.md), the [issue guide](https://github.com/dxos/dxos/blob/main/CONTRIBUTING.md#submitting-issues), and the [PR contribution guide](https://github.com/dxos/dxos/blob/main/CONTRIBUTING.md#submitting-prs).
82
82
 
83
- License: [MIT](./LICENSE) Copyright 2022 © DXOS
83
+ License: [FSL-1.1-Apache-2.0](./LICENSE) Copyright 2022 © DXOS
@@ -5,8 +5,7 @@ import * as Effect from "effect/Effect";
5
5
  import * as Layer from "effect/Layer";
6
6
  import * as Redacted from "effect/Redacted";
7
7
  import { Credential } from "@dxos/compute";
8
- import { Query } from "@dxos/echo";
9
- import { Database } from "@dxos/echo";
8
+ import { Database, Query } from "@dxos/echo";
10
9
  import { AccessToken } from "@dxos/types";
11
10
  var ConfiguredCredentialsService = class {
12
11
  credentials;
@@ -88,7 +87,7 @@ var FunctionInvocationService = class _FunctionInvocationService extends Context
88
87
  };
89
88
 
90
89
  // src/services/queues.ts
91
- import { ContextQueueService, QueueService, feedServiceFromQueueServiceLayer } from "@dxos/echo-db";
90
+ import { QueueService, feedServiceFromQueueServiceLayer } from "@dxos/echo-db";
92
91
 
93
92
  // src/services/tracing.ts
94
93
  var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
@@ -117,18 +116,21 @@ var setUserFunctionIdInMetadata = (meta, functionId) => {
117
116
  import * as AnthropicClient from "@effect/ai-anthropic/AnthropicClient";
118
117
  import * as Effect4 from "effect/Effect";
119
118
  import * as Layer4 from "effect/Layer";
119
+ import * as Option from "effect/Option";
120
120
  import * as Schema from "effect/Schema";
121
121
  import * as SchemaAST from "effect/SchemaAST";
122
- import { AiModelResolver, AiService } from "@dxos/ai";
122
+ import { AiModelResolver, AiService, OpaqueToolkit } from "@dxos/ai";
123
123
  import { AnthropicResolver } from "@dxos/ai/resolvers";
124
- import { FunctionError, InvalidOperationInputError, InvalidOperationOutputError, Operation, Trace } from "@dxos/compute";
124
+ import { Blueprint, FunctionError, InvalidOperationInputError, InvalidOperationOutputError, Operation, OperationRegistry, Trace } from "@dxos/compute";
125
125
  import { LifecycleState, Resource } from "@dxos/context";
126
126
  import { Database as Database2, Feed, JsonSchema, Ref } from "@dxos/echo";
127
- import { EchoClient, createFeedServiceLayer } from "@dxos/echo-db";
127
+ import { createFeedServiceLayer, EchoClient } from "@dxos/echo-db";
128
128
  import { refFromEncodedReference } from "@dxos/echo/internal";
129
129
  import { runAndForwardErrors } from "@dxos/effect";
130
130
  import { assertState, failedInvariant, invariant } from "@dxos/invariant";
131
131
  import { PublicKey } from "@dxos/keys";
132
+ import { log as log2 } from "@dxos/log";
133
+ import { ErrorCodec as ErrorCodec2 } from "@dxos/protocols";
132
134
 
133
135
  // src/protocol/functions-ai-http-client.ts
134
136
  import * as Headers from "@effect/platform/Headers";
@@ -139,6 +141,7 @@ import * as Effect3 from "effect/Effect";
139
141
  import * as FiberRef from "effect/FiberRef";
140
142
  import * as Layer3 from "effect/Layer";
141
143
  import * as Stream from "effect/Stream";
144
+ import { FunctionsAiMemoizationMissError, FunctionsAiUpstreamError } from "@dxos/compute";
142
145
  import { log } from "@dxos/log";
143
146
  import { ErrorCodec } from "@dxos/protocols";
144
147
  var __dxlog_file = "/__w/dxos/dxos/packages/core/compute/functions/src/protocol/functions-ai-http-client.ts";
@@ -158,14 +161,19 @@ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
158
161
  catch: (cause) => {
159
162
  log.error("Failed to fetch", {
160
163
  errorSerialized: ErrorCodec.encode(cause)
161
- }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 30, S: this });
164
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 31, S: this });
162
165
  return new HttpClientError.RequestError({
163
166
  request,
164
167
  reason: "Transport",
165
168
  cause
166
169
  });
167
170
  }
168
- }).pipe(Effect3.map((response) => HttpClientResponse.fromWeb(request, response)));
171
+ }).pipe(Effect3.flatMap((response) => (
172
+ // Inspect the body before handing the response to `@effect/ai` so that structured
173
+ // upstream errors surface as typed defects (`FunctionsAiUpstreamError` and friends)
174
+ // rather than as the generic `HttpResponseError` from `@effect/ai/AiError`.
175
+ Effect3.flatMap(Effect3.promise(() => parseUpstreamError(response)), (typedError) => typedError ? Effect3.die(typedError) : Effect3.succeed(HttpClientResponse.fromWeb(request, response)))
176
+ )));
169
177
  switch (request.body._tag) {
170
178
  case "Raw":
171
179
  case "Uint8Array":
@@ -179,6 +187,45 @@ var FunctionsAiHttpClient = class _FunctionsAiHttpClient {
179
187
  });
180
188
  static layer = (service) => Layer3.succeed(HttpClient2.HttpClient, _FunctionsAiHttpClient.make(service));
181
189
  };
190
+ var parseUpstreamError = async (response) => {
191
+ if (response.ok) {
192
+ return void 0;
193
+ }
194
+ const contentType = response.headers.get("content-type") ?? "";
195
+ if (!contentType.toLowerCase().includes("application/json")) {
196
+ return void 0;
197
+ }
198
+ let body;
199
+ try {
200
+ body = await response.clone().json();
201
+ } catch {
202
+ return void 0;
203
+ }
204
+ if (!body || body.type !== "error" || typeof body.error !== "object" || body.error === null) {
205
+ return void 0;
206
+ }
207
+ const inner = body.error;
208
+ const message = inner.message ?? `Upstream AI service responded with HTTP ${response.status}`;
209
+ if (inner.type === "memoization_miss" && typeof inner.cacheKey === "string") {
210
+ return new FunctionsAiMemoizationMissError({
211
+ message,
212
+ context: {
213
+ cacheKey: inner.cacheKey,
214
+ status: response.status
215
+ }
216
+ });
217
+ }
218
+ return new FunctionsAiUpstreamError({
219
+ message,
220
+ context: {
221
+ type: inner.type,
222
+ status: response.status,
223
+ ...inner.cacheKey ? {
224
+ cacheKey: inner.cacheKey
225
+ } : {}
226
+ }
227
+ });
228
+ };
182
229
 
183
230
  // src/protocol/protocol.ts
184
231
  var __dxlog_file2 = "/__w/dxos/dxos/packages/core/compute/functions/src/protocol/protocol.ts";
@@ -247,7 +294,7 @@ function _ts_dispose_resources(env) {
247
294
  return next();
248
295
  })(env);
249
296
  }
250
- var wrapFunctionHandler = (func) => {
297
+ var wrapFunctionHandler = (func, opts = {}) => {
251
298
  if (!Operation.isOperationWithHandler(func)) {
252
299
  throw new TypeError("Expected operation with handler");
253
300
  }
@@ -286,16 +333,26 @@ var wrapFunctionHandler = (func) => {
286
333
  });
287
334
  }
288
335
  }
289
- const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context).open(), true);
290
- if (func.types.length > 0) {
291
- invariant(funcContext.db, "Database is required for functions with types", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 130, S: void 0, A: ["funcContext.db", "'Database is required for functions with types'"] });
292
- await funcContext.db.graph.schemaRegistry.register(func.types);
336
+ const funcContext = _ts_add_disposable_resource(env, await new FunctionContext(context, opts).open(), true);
337
+ const types = [
338
+ ...opts.types ?? [],
339
+ ...func.types ?? []
340
+ ];
341
+ if (types.length > 0) {
342
+ invariant(funcContext.db, "Database is required for functions with types", { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 137, S: void 0, A: ["funcContext.db", "'Database is required for functions with types'"] });
343
+ await funcContext.db.graph.schemaRegistry.register(types);
293
344
  }
294
345
  const dataWithDecodedRefs = funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast) ? decodeRefsFromSchema(func.input.ast, data, funcContext.db) : data;
295
346
  let result = await func.handler(dataWithDecodedRefs);
296
347
  if (Effect4.isEffect(result)) {
297
348
  result = await runAndForwardErrors(result.pipe(Effect4.orDie, Effect4.provide(funcContext.createLayer())));
298
349
  }
350
+ if (serviceTags.includes(Database2.Service.key) && funcContext.db) {
351
+ await funcContext.db.flush({
352
+ disk: true,
353
+ indexes: false
354
+ });
355
+ }
299
356
  if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {
300
357
  try {
301
358
  Schema.validateSync(func.output, {
@@ -327,9 +384,11 @@ var FunctionContext = class extends Resource {
327
384
  client;
328
385
  db;
329
386
  queues;
330
- constructor(context) {
387
+ opts;
388
+ constructor(context, opts) {
331
389
  super();
332
390
  this.context = context;
391
+ this.opts = opts;
333
392
  if (context.services.dataService && context.services.queryService) {
334
393
  this.client = new EchoClient().connectToService({
335
394
  dataService: context.services.dataService,
@@ -362,36 +421,105 @@ var FunctionContext = class extends Resource {
362
421
  const credentials = dbLayer ? credentialsLayerFromDatabase({
363
422
  caching: true
364
423
  }).pipe(Layer4.provide(dbLayer)) : configuredCredentialsLayer([]);
365
- const functionInvocationService = MockedFunctionInvocationService;
366
- const operationServiceLayer = MockedOperationServiceLayer;
367
- const aiLayer = this.context.services.functionsAiService ? AiModelResolver.AiModelResolver.buildAiService.pipe(Layer4.provide(AnthropicResolver.make().pipe(Layer4.provide(AnthropicClient.layer({
368
- // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
369
- apiUrl: "http://internal/provider/anthropic"
370
- }).pipe(Layer4.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))))))) : AiService.notAvailable;
424
+ const aiLayer = this.context.services.functionsAiService ? InternalAiServiceLayer(this.context.services.functionsAiService) : AiService.notAvailable;
425
+ const operationServiceLayer = this.context.services.functionsService ? makeOperationServiceLayer(this.context.services.functionsService) : unavailableOperationServiceLayer;
426
+ const operationRegistryLayer = this.context.services.functionsService ? makeOperationRegistryLayer(this.context.services.functionsService, this.context.spaceId) : emptyOperationRegistryLayer;
427
+ const traceWriterLayer = this.context.services.traceService ? makeTraceWriterLayer(this.context.services.traceService) : Trace.writerLayerNoop;
428
+ log2("Creating function context layer", {
429
+ traceService: !!this.context.services.traceService,
430
+ functionsService: !!this.context.services.functionsService,
431
+ functionsAiService: !!this.context.services.functionsAiService,
432
+ spaceId: this.context.spaceId,
433
+ spaceRootUrl: this.context.spaceRootUrl,
434
+ toolkits: this.opts.toolkits?.length ?? 0,
435
+ types: this.opts.types?.length ?? 0
436
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 234, S: this });
437
+ const blueprintRegistryLayer = this.opts.blueprintRegistry ? Layer4.succeed(Blueprint.RegistryService, this.opts.blueprintRegistry) : Blueprint.RegistryService.notAvailable;
371
438
  return Layer4.mergeAll(
372
439
  dbLayer,
373
440
  queuesLayer,
374
441
  feedLayer,
375
442
  credentials,
376
- functionInvocationService,
377
443
  operationServiceLayer,
444
+ operationRegistryLayer,
378
445
  aiLayer,
379
- // TODO(dmaretskyi): Forward trace events.
380
- Trace.writerLayerNoop
446
+ OpaqueToolkit.providerLayer(OpaqueToolkit.merge(...this.opts.toolkits ?? [])),
447
+ traceWriterLayer,
448
+ blueprintRegistryLayer,
449
+ // `FunctionInvocationService` is deprecated; new code should yield `Operation.Service`.
450
+ // The cloudflare wrapper provides only the unavailable layer to satisfy the (still-present)
451
+ // type union — handlers that yield it will die at invocation time.
452
+ FunctionInvocationService.layerNotAvailable
381
453
  );
382
454
  }
383
455
  };
384
- var MockedFunctionInvocationService = Layer4.succeed(FunctionInvocationService, {
385
- invokeFunction: () => Effect4.die("Calling functions from functions is not implemented yet."),
386
- resolveFunction: () => Effect4.die("Not implemented.")
456
+ var makeTraceWriterLayer = (traceService) => Layer4.succeed(Trace.TraceService, {
457
+ write: (eventType, payload) => {
458
+ log2("Writing trace event", {
459
+ eventType: eventType.key
460
+ }, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 255, S: void 0 });
461
+ traceService.write([
462
+ {
463
+ key: eventType.key,
464
+ isEphemeral: eventType.isEphemeral,
465
+ data: payload
466
+ }
467
+ ]);
468
+ }
387
469
  });
388
- var MockedOperationServiceLayer = Layer4.succeed(Operation.Service, {
389
- invoke: () => Effect4.die("Calling operations from functions is not implemented yet."),
390
- schedule: () => Effect4.die("Not implemented."),
470
+ var InternalAiServiceLayer = (functionsAiService) => AiModelResolver.AiModelResolver.buildAiService.pipe(Layer4.provide(AnthropicResolver.make().pipe(Layer4.provide(AnthropicClient.layer({
471
+ // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.
472
+ apiUrl: "http://internal/provider/anthropic"
473
+ }).pipe(Layer4.provide(FunctionsAiHttpClient.layer(functionsAiService)))))));
474
+ var makeOperationServiceLayer = (functionsService) => {
475
+ const invokeRemote = async (op, input, options) => {
476
+ invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 279, S: void 0, A: ["op.meta.deployedId", "`Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`"] });
477
+ const result = await functionsService.invoke(op.meta.deployedId, input, {
478
+ spaceId: options?.spaceId,
479
+ // Forward the conversation DXN so the remote runtime can rebuild conversation-scoped
480
+ // services (e.g. `AiContext.Service`) needed by operations like `GetContext`.
481
+ conversation: options?.conversation
482
+ });
483
+ if (result._kind === "success") {
484
+ return {
485
+ data: result.data
486
+ };
487
+ }
488
+ return {
489
+ error: ErrorCodec2.decode(result.error)
490
+ };
491
+ };
492
+ return Layer4.succeed(Operation.Service, {
493
+ invoke: (op, input, options) => Effect4.tryPromise(() => invokeRemote(op, input, options)).pipe(Effect4.orDie, Effect4.flatMap((outcome) => outcome.error ? Effect4.die(outcome.error) : Effect4.succeed(outcome.data))),
494
+ schedule: (op, input) => Effect4.sync(() => {
495
+ invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 298, S: void 0, A: ["op.meta.deployedId", "`Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`"] });
496
+ void functionsService.invoke(op.meta.deployedId, input).catch(() => {
497
+ });
498
+ }),
499
+ invokePromise: (op, input, options) => invokeRemote(op, input, options).catch((error) => ({
500
+ error: error instanceof Error ? error : new Error(String(error))
501
+ }))
502
+ });
503
+ };
504
+ var unavailableOperationServiceLayer = Layer4.succeed(Operation.Service, {
505
+ invoke: () => Effect4.die("Operation.Service is not available: missing functionsService in EDGE context."),
506
+ schedule: () => Effect4.die("Operation.Service is not available: missing functionsService in EDGE context."),
391
507
  invokePromise: async () => ({
392
- error: new Error("Not implemented")
508
+ error: new Error("Operation.Service is not available: missing functionsService in EDGE context.")
393
509
  })
394
510
  });
511
+ var makeOperationRegistryLayer = (functionsService, spaceId) => Layer4.succeed(OperationRegistry.Service, {
512
+ resolve: (key) => Effect4.gen(function* () {
513
+ const records = yield* Effect4.tryPromise(() => functionsService.query({
514
+ spaceId
515
+ })).pipe(Effect4.orDie);
516
+ const match = records.find((record) => Operation.getKey(record) === key);
517
+ return match ? Option.some(Operation.deserialize(match)) : Option.none();
518
+ })
519
+ });
520
+ var emptyOperationRegistryLayer = Layer4.succeed(OperationRegistry.Service, {
521
+ resolve: () => Effect4.succeed(Option.none())
522
+ });
395
523
  var decodeRefsFromSchema = (ast, value2, db) => {
396
524
  if (value2 == null) {
397
525
  return value2;
@@ -457,7 +585,6 @@ var decodeRefsFromSchema = (ast, value2, db) => {
457
585
  };
458
586
  export {
459
587
  ConfiguredCredentialsService,
460
- ContextQueueService,
461
588
  FUNCTIONS_META_KEY,
462
589
  FUNCTIONS_PRESET_META_KEY,
463
590
  FunctionInvocationService,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/services/credentials.ts", "../../../src/services/function-invocation-service.ts", "../../../src/services/queues.ts", "../../../src/services/tracing.ts", "../../../src/types/url.ts", "../../../src/protocol/protocol.ts", "../../../src/protocol/functions-ai-http-client.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest';\nimport type * as Config from 'effect/Config';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Redacted from 'effect/Redacted';\n\nimport { Credential } from '@dxos/compute';\nimport { Query } from '@dxos/echo';\nimport { Database } from '@dxos/echo';\nimport { AccessToken } from '@dxos/types';\n\nexport class ConfiguredCredentialsService implements Context.Tag.Service<Credential.CredentialsService> {\n constructor(private readonly credentials: Credential.ServiceCredential[] = []) {}\n\n addCredentials(credentials: Credential.ServiceCredential[]): ConfiguredCredentialsService {\n this.credentials.push(...credentials);\n return this;\n }\n\n async queryCredentials(query: Credential.CredentialQuery): Promise<Credential.ServiceCredential[]> {\n return this.credentials.filter((credential) => credential.service === query.service);\n }\n\n async getCredential(query: Credential.CredentialQuery): Promise<Credential.ServiceCredential> {\n const credential = this.credentials.find((credential) => credential.service === query.service);\n if (!credential) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credential;\n }\n}\n\n/**\n * Maps the request to include the given token in the Authorization header.\n */\nexport const withAuthorization = (token: string, kind?: 'Bearer' | 'Basic') =>\n HttpClient.mapRequest((request) => {\n const authorization = kind ? `${kind} ${token}` : token;\n return HttpClientRequest.setHeader(request, 'Authorization', authorization);\n });\n\nexport const configuredCredentialsLayer = (credentials: Credential.ServiceCredential[]) =>\n Layer.succeed(Credential.CredentialsService, new ConfiguredCredentialsService(credentials));\n\nexport const credentialsLayerConfig = (\n credentials: {\n service: string;\n apiKey: Config.Config<Redacted.Redacted<string>>;\n }[],\n) =>\n Layer.effect(\n Credential.CredentialsService,\n Effect.gen(function* () {\n const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>\n Effect.gen(function* () {\n return {\n service,\n apiKey: Redacted.value(yield* apiKey),\n };\n }),\n );\n\n return new ConfiguredCredentialsService(serviceCredentials);\n }),\n );\n\nexport const credentialsLayerFromDatabase = ({ caching = false }: { caching?: boolean } = {}) =>\n Layer.effect(\n Credential.CredentialsService,\n Effect.gen(function* () {\n const dbService = yield* Database.Service;\n const cache = new Map<string, Credential.ServiceCredential[]>();\n\n const queryCredentials = async (query: Credential.CredentialQuery): Promise<Credential.ServiceCredential[]> => {\n const cacheKey = JSON.stringify(query);\n if (caching && cache.has(cacheKey)) {\n return cache.get(cacheKey)!;\n }\n\n const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();\n const credentials = accessTokens\n .filter((accessToken) => accessToken.source === query.service)\n .map((accessToken) => ({\n service: accessToken.source,\n apiKey: accessToken.token,\n }));\n\n if (caching) {\n cache.set(cacheKey, credentials);\n }\n\n return credentials;\n };\n\n return {\n getCredential: async (query) => {\n const credentials = await queryCredentials(query);\n if (credentials.length === 0) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credentials[0];\n },\n queryCredentials: async (query) => {\n return queryCredentials(query);\n },\n };\n }),\n );\n", "//\n// Copyright 2025 DXOS.org\n//\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { type FunctionNotFoundError, Operation } from '@dxos/compute';\n\nexport class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<\n FunctionInvocationService,\n {\n invokeFunction<I, O>(functionDef: Operation.Definition<I, O, any>, input: I): Effect.Effect<O>;\n\n resolveFunction(key: string): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError>;\n }\n>() {\n static layerNotAvailable = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('FunctionInvocationService is not avaialble.'),\n resolveFunction: () => Effect.die('FunctionInvocationService is not available.'),\n });\n\n static invokeFunction = <I, O>(\n functionDef: Operation.Definition<I, O, any>,\n input: I,\n ): Effect.Effect<O, never, FunctionInvocationService> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);\n\n static resolveFunction = (\n key: string,\n ): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError, FunctionInvocationService> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.resolveFunction)(key);\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nexport { ContextQueueService, QueueService, feedServiceFromQueueServiceLayer } from '@dxos/echo-db';\n", "//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Goes into {@link Message['properties']}\n */\nexport const MESSAGE_PROPERTY_TOOL_CALL_ID = 'toolCallId' as const;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Obj } from '@dxos/echo';\n\n// TODO: use URL scheme for source?\nexport const FUNCTIONS_META_KEY = 'org.dxos.service.function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'org.dxos.service.function-preset';\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const getUserFunctionIdInMetadata = (meta: Obj.ReadonlyMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n * Must be called inside Obj.update() since it mutates the meta.\n */\nexport const setUserFunctionIdInMetadata = (meta: Obj.Meta, functionId: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionId) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionId });\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { AiModelResolver, AiService } from '@dxos/ai';\nimport { AnthropicResolver } from '@dxos/ai/resolvers';\nimport {\n FunctionError,\n InvalidOperationInputError,\n InvalidOperationOutputError,\n Operation,\n Trace,\n} from '@dxos/compute';\nimport { LifecycleState, Resource } from '@dxos/context';\nimport { Database, Feed, JsonSchema, Ref, type Type } from '@dxos/echo';\nimport { EchoClient, type EchoDatabaseImpl, type QueueFactory, createFeedServiceLayer } from '@dxos/echo-db';\nimport { refFromEncodedReference } from '@dxos/echo/internal';\nimport { runAndForwardErrors } from '@dxos/effect';\nimport { assertState, failedInvariant, invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { type FunctionProtocol } from '@dxos/protocols';\n\nimport { type FunctionServices } from '../sdk';\nimport {\n configuredCredentialsLayer,\n credentialsLayerFromDatabase,\n FunctionInvocationService,\n QueueService,\n} from '../services';\nimport { FunctionsAiHttpClient } from './functions-ai-http-client';\n\n/**\n * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.\n */\nexport const wrapFunctionHandler = (func: Operation.WithHandler<Operation.Definition.Any>): FunctionProtocol.Func => {\n if (!Operation.isOperationWithHandler(func)) {\n throw new TypeError('Expected operation with handler');\n }\n\n const serviceTags = func.services.map((service) => service.key);\n\n return {\n meta: {\n key: func.meta.key,\n name: func.meta.name,\n description: func.meta.description,\n inputSchema: JsonSchema.toJsonSchema(func.input),\n outputSchema: func.output === undefined ? undefined : JsonSchema.toJsonSchema(func.output),\n services: func.services.map((service) => service.key),\n },\n handler: async ({ data, context }) => {\n if (\n (serviceTags.includes(Database.Service.key) ||\n serviceTags.includes(QueueService.key) ||\n serviceTags.includes(Feed.FeedService.key)) &&\n (!context.services.dataService || !context.services.queryService)\n ) {\n throw new FunctionError({\n message: 'Services not provided: dataService, queryService',\n });\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (!SchemaAST.isAnyKeyword(func.input.ast)) {\n try {\n Schema.validateSync(func.input, { onExcessProperty: 'error' })(data);\n } catch (error: any) {\n throw new InvalidOperationInputError({\n message: `Operation input did not match schema (${func.meta.key}): ${error.message}`,\n cause: error,\n });\n }\n }\n\n await using funcContext = await new FunctionContext(context).open();\n\n if (func.types.length > 0) {\n invariant(funcContext.db, 'Database is required for functions with types');\n await funcContext.db.graph.schemaRegistry.register(func.types as Type.AnyEntity[]);\n }\n\n const dataWithDecodedRefs =\n funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast)\n ? decodeRefsFromSchema(func.input.ast, data, funcContext.db)\n : data;\n\n let result: any = await func.handler(dataWithDecodedRefs);\n\n if (Effect.isEffect(result)) {\n result = await runAndForwardErrors(\n (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(\n Effect.orDie,\n Effect.provide(funcContext.createLayer()),\n ),\n );\n }\n\n if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {\n try {\n Schema.validateSync(func.output, { onExcessProperty: 'error' })(result);\n } catch (error: any) {\n throw new InvalidOperationOutputError({\n message: `Operation output did not match schema (${func.meta.key}): ${error.message}`,\n cause: error,\n });\n }\n }\n\n return result;\n } catch (error) {\n // TODO(dmaretskyi): We might do error wrapping here and add extra context.\n throw error;\n }\n },\n };\n};\n\n/**\n * Container for services and context for a function.\n */\nclass FunctionContext extends Resource {\n readonly context: FunctionProtocol.Context;\n readonly client: EchoClient | undefined;\n db: EchoDatabaseImpl | undefined;\n queues: QueueFactory | undefined;\n\n constructor(context: FunctionProtocol.Context) {\n super();\n this.context = context;\n if (context.services.dataService && context.services.queryService) {\n this.client = new EchoClient().connectToService({\n dataService: context.services.dataService,\n queryService: context.services.queryService,\n queueService: context.services.queueService,\n });\n }\n }\n\n override async _open() {\n await this.client?.open();\n this.db =\n this.client && this.context.spaceId\n ? this.client.constructDatabase({\n spaceId: this.context.spaceId ?? failedInvariant(),\n spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),\n reactiveSchemaQuery: false,\n preloadSchemaOnOpen: false,\n })\n : undefined;\n\n await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context'));\n await this.db?.open();\n this.queues =\n this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : undefined;\n }\n\n override async _close() {\n await this.db?.close();\n await this.client?.close();\n }\n\n createLayer(): Layer.Layer<FunctionServices> {\n assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');\n\n const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;\n const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;\n const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;\n const credentials = dbLayer\n ? credentialsLayerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))\n : configuredCredentialsLayer([]);\n const functionInvocationService = MockedFunctionInvocationService;\n const operationServiceLayer = MockedOperationServiceLayer;\n\n const aiLayer = this.context.services.functionsAiService\n ? AiModelResolver.AiModelResolver.buildAiService.pipe(\n Layer.provide(\n AnthropicResolver.make().pipe(\n Layer.provide(\n AnthropicClient.layer({\n // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.\n apiUrl: 'http://internal/provider/anthropic',\n }).pipe(Layer.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))),\n ),\n ),\n ),\n )\n : AiService.notAvailable;\n\n return Layer.mergeAll(\n dbLayer,\n queuesLayer,\n feedLayer,\n credentials,\n functionInvocationService,\n operationServiceLayer,\n aiLayer,\n // TODO(dmaretskyi): Forward trace events.\n Trace.writerLayerNoop,\n );\n }\n}\n\nconst MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),\n resolveFunction: () => Effect.die('Not implemented.'),\n});\n\nconst MockedOperationServiceLayer = Layer.succeed(Operation.Service, {\n invoke: () => Effect.die('Calling operations from functions is not implemented yet.'),\n schedule: () => Effect.die('Not implemented.'),\n invokePromise: async () => ({ error: new Error('Not implemented') }),\n} as any);\n\nconst decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {\n if (value == null) {\n return value;\n }\n\n const encoded = SchemaAST.encodedBoundAST(ast);\n if (Ref.isRefType(encoded)) {\n if (Ref.isRef(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {\n const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });\n return refFromEncodedReference(value as any, resolver);\n }\n\n return value;\n }\n\n switch (encoded._tag) {\n case 'TypeLiteral': {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return value;\n }\n const result: Record<string, unknown> = { ...(value as any) };\n for (const prop of SchemaAST.getPropertySignatures(encoded)) {\n const key = prop.name.toString();\n if (key in result) {\n result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);\n }\n }\n return result;\n }\n\n case 'TupleType': {\n if (!Array.isArray(value)) {\n return value;\n }\n\n // For arrays, effect uses TupleType with empty elements and a single rest element.\n if (encoded.elements.length === 0 && encoded.rest.length === 1) {\n const elementType = encoded.rest[0].type;\n return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));\n }\n\n return value;\n }\n\n case 'Union': {\n // Optional values are represented as union with undefined.\n const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));\n if (nonUndefined.length === 1) {\n return decodeRefsFromSchema(nonUndefined[0], value, db);\n }\n\n // For other unions we can't safely pick a branch without validating.\n return value;\n }\n\n case 'Suspend': {\n return decodeRefsFromSchema(encoded.f(), value, db);\n }\n\n case 'Refinement': {\n return decodeRefsFromSchema(encoded.from, value, db);\n }\n\n default: {\n return value;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Headers from '@effect/platform/Headers';\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientError from '@effect/platform/HttpClientError';\nimport * as HttpClientResponse from '@effect/platform/HttpClientResponse';\nimport * as Effect from 'effect/Effect';\nimport * as FiberRef from 'effect/FiberRef';\nimport * as Layer from 'effect/Layer';\nimport * as Stream from 'effect/Stream';\n\nimport { log } from '@dxos/log';\nimport { type EdgeFunctionEnv, ErrorCodec } from '@dxos/protocols';\n/**\n * Copy pasted from https://github.com/Effect-TS/effect/blob/main/packages/platform/src/internal/fetchHttpClient.ts\n */\nexport const requestInitTagKey = '@effect/platform/FetchHttpClient/FetchOptions';\n\nexport class FunctionsAiHttpClient {\n static make = (service: EdgeFunctionEnv.FunctionsAiService) =>\n HttpClient.make((request, url, signal, fiber) => {\n const context = fiber.getFiberRef(FiberRef.currentContext);\n const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {};\n const headers = options.headers\n ? Headers.merge(Headers.fromInput(options.headers), request.headers)\n : request.headers;\n\n const send = (body: BodyInit | undefined) =>\n Effect.tryPromise({\n try: () =>\n service.fetch(\n new Request(url, {\n ...options,\n method: request.method,\n headers,\n body,\n // Note: Don't pass signal - it can't be serialized through RPC\n }),\n ),\n catch: (cause) => {\n log.error('Failed to fetch', { errorSerialized: ErrorCodec.encode(cause as Error) });\n return new HttpClientError.RequestError({\n request,\n reason: 'Transport',\n cause,\n });\n },\n }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response)));\n\n switch (request.body._tag) {\n case 'Raw':\n case 'Uint8Array':\n return send(request.body.body as any);\n case 'FormData':\n return send(request.body.formData);\n case 'Stream':\n return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect.flatMap(send));\n }\n\n return send(undefined);\n });\n\n static layer = (service: EdgeFunctionEnv.FunctionsAiService) =>\n Layer.succeed(HttpClient.HttpClient, FunctionsAiHttpClient.make(service));\n}\n"],
5
- "mappings": ";AAIA,YAAYA,gBAAgB;AAC5B,YAAYC,uBAAuB;AAGnC,YAAYC,YAAY;AACxB,YAAYC,WAAW;AACvB,YAAYC,cAAc;AAE1B,SAASC,kBAAkB;AAC3B,SAASC,aAAa;AACtB,SAASC,gBAAgB;AACzB,SAASC,mBAAmB;AAErB,IAAMC,+BAA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F,aAAAA;IAEA;SAAgB;AAEhB,aAAA,qBAAA,QAAA,EAAA,GAAAA,QAAA,EAAA;IAEA;SAAmB;AAEnB,aAAA,qBAAA,QAAA,MAAAA,QAAA,EAAA;IAEA;;AAEA,aAAAA;IACF;EACF;;",
6
- "names": ["HttpClient", "HttpClientRequest", "Effect", "Layer", "Redacted", "Credential", "Query", "Database", "AccessToken", "ConfiguredCredentialsService", "credentials", "addCredentials", "push", "queryCredentials", "query", "filter", "credential", "service", "getCredential", "find", "Error", "withAuthorization", "token", "kind", "mapRequest", "request", "authorization", "setHeader", "configuredCredentialsLayer", "succeed", "CredentialsService", "credentialsLayerConfig", "effect", "gen", "serviceCredentials", "forEach", "apiKey", "value", "credentialsLayerFromDatabase", "caching", "dbService", "Service", "cache", "Map", "cacheKey", "JSON", "stringify", "has", "get", "accessTokens", "db", "type", "run", "accessToken", "source", "map", "set", "length", "Context", "Effect", "Layer", "FunctionInvocationService", "Tag", "layerNotAvailable", "succeed", "invokeFunction", "die", "resolveFunction", "functionDef", "input", "serviceFunctionEffect", "service", "key", "ContextQueueService", "QueueService", "feedServiceFromQueueServiceLayer", "MESSAGE_PROPERTY_TOOL_CALL_ID", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "getUserFunctionIdInMetadata", "meta", "keys", "find", "key", "source", "id", "setUserFunctionIdInMetadata", "functionId", "Error", "push", "Effect", "Layer", "Schema", "SchemaAST", "AiModelResolver", "AiService", "AnthropicResolver", "FunctionError", "InvalidOperationInputError", "LifecycleState", "Database", "JsonSchema", "EchoClient", "createFeedServiceLayer", "refFromEncodedReference", "runAndForwardErrors", "assertState", "failedInvariant", "PublicKey", "configuredCredentialsLayer", "Headers", "HttpClient", "HttpClientError", "HttpClientResponse", "Effect", "FiberRef", "Layer", "Stream", "log", "ErrorCodec", "make", "getFiberRef", "options", "unsafeMap", "get", "requestInitTagKey", "headers", "merge", "fromInput", "send", "body", "tryPromise", "service", "Request", "method", "request", "cause", "errorSerialized", "RequestError", "reason", "formData", "toReadableStreamEffect", "undefined", "layer", "__dxlog_file", "Operation", "isOperationWithHandler", "func", "TypeError", "meta", "key", "name", "description", "inputSchema", "JsonSchema", "outputSchema", "output", "undefined", "services", "service", "handler", "serviceTags", "includes", "Database", "FunctionError", "message", "Schema", "onExcessProperty", "data", "error", "InvalidOperationInputError", "cause", "length", "invariant", "funcContext", "db", "graph", "result", "dataWithDecodedRefs", "Effect", "isEffect", "runAndForwardErrors", "InvalidOperationOutputError", "context", "client", "queues", "connectToService", "dataService", "queryService", "queueService", "spaceId", "failedInvariant", "spaceKey", "PublicKey", "fromHex", "reactiveSchemaQuery", "preloadSchemaOnOpen", "open", "close", "createLayer", "assertState", "dbLayer", "layer", "queuesLayer", "QueueService", "feedLayer", "createFeedServiceLayer", "notAvailable", "credentials", "credentialsLayerFromDatabase", "caching", "pipe", "Layer", "functionInvocationService", "MockedFunctionInvocationService", "operationServiceLayer", "MockedOperationServiceLayer", "aiLayer", "mergeAll", "Trace", "writerLayerNoop", "invokeFunction", "resolveFunction", "invoke", "schedule", "die", "invokePromise", "value", "Ref", "encoded", "resolver", "createRefResolver", "space", "toString", "decodeRefsFromSchema", "elementType", "rest", "item", "nonUndefined"]
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest';\nimport type * as Config from 'effect/Config';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Redacted from 'effect/Redacted';\n\nimport { Credential } from '@dxos/compute';\nimport { Database, Query } from '@dxos/echo';\nimport { AccessToken } from '@dxos/types';\n\nexport class ConfiguredCredentialsService implements Context.Tag.Service<Credential.CredentialsService> {\n constructor(private readonly credentials: Credential.ServiceCredential[] = []) {}\n\n addCredentials(credentials: Credential.ServiceCredential[]): ConfiguredCredentialsService {\n this.credentials.push(...credentials);\n return this;\n }\n\n async queryCredentials(query: Credential.CredentialQuery): Promise<Credential.ServiceCredential[]> {\n return this.credentials.filter((credential) => credential.service === query.service);\n }\n\n async getCredential(query: Credential.CredentialQuery): Promise<Credential.ServiceCredential> {\n const credential = this.credentials.find((credential) => credential.service === query.service);\n if (!credential) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credential;\n }\n}\n\n/**\n * Maps the request to include the given token in the Authorization header.\n */\nexport const withAuthorization = (token: string, kind?: 'Bearer' | 'Basic') =>\n HttpClient.mapRequest((request) => {\n const authorization = kind ? `${kind} ${token}` : token;\n return HttpClientRequest.setHeader(request, 'Authorization', authorization);\n });\n\nexport const configuredCredentialsLayer = (credentials: Credential.ServiceCredential[]) =>\n Layer.succeed(Credential.CredentialsService, new ConfiguredCredentialsService(credentials));\n\nexport const credentialsLayerConfig = (\n credentials: {\n service: string;\n apiKey: Config.Config<Redacted.Redacted<string>>;\n }[],\n) =>\n Layer.effect(\n Credential.CredentialsService,\n Effect.gen(function* () {\n const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>\n Effect.gen(function* () {\n return {\n service,\n apiKey: Redacted.value(yield* apiKey),\n };\n }),\n );\n\n return new ConfiguredCredentialsService(serviceCredentials);\n }),\n );\n\nexport const credentialsLayerFromDatabase = ({ caching = false }: { caching?: boolean } = {}) =>\n Layer.effect(\n Credential.CredentialsService,\n Effect.gen(function* () {\n const dbService = yield* Database.Service;\n const cache = new Map<string, Credential.ServiceCredential[]>();\n\n const queryCredentials = async (query: Credential.CredentialQuery): Promise<Credential.ServiceCredential[]> => {\n const cacheKey = JSON.stringify(query);\n if (caching && cache.has(cacheKey)) {\n return cache.get(cacheKey)!;\n }\n\n const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();\n const credentials = accessTokens\n .filter((accessToken) => accessToken.source === query.service)\n .map((accessToken) => ({\n service: accessToken.source,\n apiKey: accessToken.token,\n }));\n\n if (caching) {\n cache.set(cacheKey, credentials);\n }\n\n return credentials;\n };\n\n return {\n getCredential: async (query) => {\n const credentials = await queryCredentials(query);\n if (credentials.length === 0) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credentials[0];\n },\n queryCredentials: async (query) => {\n return queryCredentials(query);\n },\n };\n }),\n );\n", "//\n// Copyright 2025 DXOS.org\n//\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { type FunctionNotFoundError, Operation } from '@dxos/compute';\n\n/**\n * @deprecated\n */\nexport class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<\n FunctionInvocationService,\n {\n invokeFunction<I, O>(functionDef: Operation.Definition<I, O, any>, input: I): Effect.Effect<O>;\n\n resolveFunction(key: string): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError>;\n }\n>() {\n static layerNotAvailable = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('FunctionInvocationService is not avaialble.'),\n resolveFunction: () => Effect.die('FunctionInvocationService is not available.'),\n });\n\n static invokeFunction = <I, O>(\n functionDef: Operation.Definition<I, O, any>,\n input: I,\n ): Effect.Effect<O, never, FunctionInvocationService> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);\n\n static resolveFunction = (\n key: string,\n ): Effect.Effect<Operation.Definition.Any, FunctionNotFoundError, FunctionInvocationService> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.resolveFunction)(key);\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nexport { QueueService, feedServiceFromQueueServiceLayer } from '@dxos/echo-db';\n", "//\n// Copyright 2025 DXOS.org\n//\n\n/**\n * Goes into {@link Message['properties']}\n */\nexport const MESSAGE_PROPERTY_TOOL_CALL_ID = 'toolCallId' as const;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Obj } from '@dxos/echo';\n\n// TODO: use URL scheme for source?\nexport const FUNCTIONS_META_KEY = 'org.dxos.service.function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'org.dxos.service.function-preset';\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const getUserFunctionIdInMetadata = (meta: Obj.ReadonlyMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n * Must be called inside Obj.update() since it mutates the meta.\n */\nexport const setUserFunctionIdInMetadata = (meta: Obj.Meta, functionId: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionId) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionId });\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { AiModelResolver, AiService, OpaqueToolkit } from '@dxos/ai';\nimport { AnthropicResolver } from '@dxos/ai/resolvers';\nimport {\n Blueprint,\n FunctionError,\n InvalidOperationInputError,\n InvalidOperationOutputError,\n Operation,\n OperationRegistry,\n Trace,\n} from '@dxos/compute';\nimport { LifecycleState, Resource } from '@dxos/context';\nimport { Database, Feed, JsonSchema, Ref, type Type } from '@dxos/echo';\nimport { createFeedServiceLayer, EchoClient, type EchoDatabaseImpl, type QueueFactory } from '@dxos/echo-db';\nimport { refFromEncodedReference } from '@dxos/echo/internal';\nimport { runAndForwardErrors } from '@dxos/effect';\nimport { assertState, failedInvariant, invariant } from '@dxos/invariant';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { EdgeFunctionEnv, ErrorCodec, type FunctionProtocol, type TraceProtocol } from '@dxos/protocols';\n\nimport { type FunctionServices } from '../sdk';\nimport {\n configuredCredentialsLayer,\n credentialsLayerFromDatabase,\n FunctionInvocationService,\n QueueService,\n} from '../services';\nimport { FunctionsAiHttpClient } from './functions-ai-http-client';\n\nexport interface FunctionWrappingOptions {\n /**\n * Additional types to register with the database.\n */\n types?: Type.AnyEntity[];\n\n /**\n * Toolkits to make available via the `OpaqueToolkitProvider`.\n */\n toolkits?: OpaqueToolkit.OpaqueToolkit[];\n\n /**\n * Blueprint registry to expose as `Blueprint.RegistryService` inside handler Effects.\n * Required for operations that declare `Blueprint.RegistryService` in their `services` list.\n */\n blueprintRegistry?: Blueprint.Registry;\n}\n\n/**\n * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.\n */\nexport const wrapFunctionHandler = (\n func: Operation.WithHandler<Operation.Definition.Any>,\n opts: FunctionWrappingOptions = {},\n): FunctionProtocol.Func => {\n if (!Operation.isOperationWithHandler(func)) {\n throw new TypeError('Expected operation with handler');\n }\n\n const serviceTags = func.services.map((service) => service.key);\n\n return {\n meta: {\n key: func.meta.key,\n name: func.meta.name,\n description: func.meta.description,\n inputSchema: JsonSchema.toJsonSchema(func.input),\n outputSchema: func.output === undefined ? undefined : JsonSchema.toJsonSchema(func.output),\n services: func.services.map((service) => service.key),\n },\n handler: async ({ data, context }) => {\n if (\n (serviceTags.includes(Database.Service.key) ||\n serviceTags.includes(QueueService.key) ||\n serviceTags.includes(Feed.FeedService.key)) &&\n (!context.services.dataService || !context.services.queryService)\n ) {\n throw new FunctionError({\n message: 'Services not provided: dataService, queryService',\n });\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (!SchemaAST.isAnyKeyword(func.input.ast)) {\n try {\n Schema.validateSync(func.input, { onExcessProperty: 'error' })(data);\n } catch (error: any) {\n throw new InvalidOperationInputError({\n message: `Operation input did not match schema (${func.meta.key}): ${error.message}`,\n cause: error,\n });\n }\n }\n\n await using funcContext = await new FunctionContext(context, opts).open();\n\n const types = [...(opts.types ?? []), ...(func.types ?? [])];\n if (types.length > 0) {\n invariant(funcContext.db, 'Database is required for functions with types');\n await funcContext.db.graph.schemaRegistry.register(types as Type.AnyEntity[]);\n }\n\n const dataWithDecodedRefs =\n funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast)\n ? decodeRefsFromSchema(func.input.ast, data, funcContext.db)\n : data;\n\n let result: any = await func.handler(dataWithDecodedRefs);\n\n if (Effect.isEffect(result)) {\n result = await runAndForwardErrors(\n (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(\n Effect.orDie,\n Effect.provide(funcContext.createLayer()),\n ),\n );\n }\n\n // Flush in-memory ECHO writes before the function scope closes.\n // Writes performed by `db.add` / `db.remove` are buffered in the in-memory\n // `EchoDatabaseImpl` and only pushed across the `DataService` binding when\n // `db.flush({ disk })` is called. `FunctionContext._close` (invoked by the\n // `await using` above) calls `db.close()` but does NOT flush, so mutations\n // performed by handlers that declare `Database.Service` (e.g. `object-create`,\n // `object-update`, `relation-create`) would be silently dropped before reaching\n // the edge `AutomergeReplicator`. Flushing here closes that hole.\n if (serviceTags.includes(Database.Service.key) && funcContext.db) {\n await funcContext.db.flush({ disk: true, indexes: false });\n }\n\n if (func.output && !SchemaAST.isAnyKeyword(func.output.ast)) {\n try {\n Schema.validateSync(func.output, { onExcessProperty: 'error' })(result);\n } catch (error: any) {\n throw new InvalidOperationOutputError({\n message: `Operation output did not match schema (${func.meta.key}): ${error.message}`,\n cause: error,\n });\n }\n }\n\n return result;\n } catch (error) {\n // TODO(dmaretskyi): We might do error wrapping here and add extra context.\n throw error;\n }\n },\n };\n};\n\n/**\n * Container for services and context for a function.\n */\nclass FunctionContext extends Resource {\n readonly context: FunctionProtocol.Context;\n readonly client: EchoClient | undefined;\n db: EchoDatabaseImpl | undefined;\n queues: QueueFactory | undefined;\n readonly opts: FunctionWrappingOptions;\n\n constructor(context: FunctionProtocol.Context, opts: FunctionWrappingOptions) {\n super();\n this.context = context;\n this.opts = opts;\n if (context.services.dataService && context.services.queryService) {\n this.client = new EchoClient().connectToService({\n dataService: context.services.dataService,\n queryService: context.services.queryService,\n queueService: context.services.queueService,\n });\n }\n }\n\n override async _open() {\n await this.client?.open();\n this.db =\n this.client && this.context.spaceId\n ? this.client.constructDatabase({\n spaceId: this.context.spaceId ?? failedInvariant(),\n spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),\n reactiveSchemaQuery: false,\n preloadSchemaOnOpen: false,\n })\n : undefined;\n\n await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context'));\n await this.db?.open();\n this.queues =\n this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : undefined;\n }\n\n override async _close() {\n await this.db?.close();\n await this.client?.close();\n }\n\n createLayer(): Layer.Layer<FunctionServices> {\n assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');\n\n const dbLayer = this.db ? Database.layer(this.db) : Database.notAvailable;\n const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;\n const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;\n const credentials = dbLayer\n ? credentialsLayerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))\n : configuredCredentialsLayer([]);\n\n const aiLayer = this.context.services.functionsAiService\n ? InternalAiServiceLayer(this.context.services.functionsAiService)\n : AiService.notAvailable;\n\n const operationServiceLayer = this.context.services.functionsService\n ? makeOperationServiceLayer(this.context.services.functionsService)\n : unavailableOperationServiceLayer;\n\n const operationRegistryLayer = this.context.services.functionsService\n ? makeOperationRegistryLayer(this.context.services.functionsService, this.context.spaceId as SpaceId | undefined)\n : emptyOperationRegistryLayer;\n\n const traceWriterLayer = this.context.services.traceService\n ? makeTraceWriterLayer(this.context.services.traceService)\n : Trace.writerLayerNoop;\n\n log('Creating function context layer', {\n traceService: !!this.context.services.traceService,\n functionsService: !!this.context.services.functionsService,\n functionsAiService: !!this.context.services.functionsAiService,\n spaceId: this.context.spaceId,\n spaceRootUrl: this.context.spaceRootUrl,\n toolkits: this.opts.toolkits?.length ?? 0,\n types: this.opts.types?.length ?? 0,\n });\n\n const blueprintRegistryLayer = this.opts.blueprintRegistry\n ? Layer.succeed(Blueprint.RegistryService, this.opts.blueprintRegistry)\n : Blueprint.RegistryService.notAvailable;\n\n return Layer.mergeAll(\n dbLayer,\n queuesLayer,\n feedLayer,\n credentials,\n operationServiceLayer,\n operationRegistryLayer,\n aiLayer,\n OpaqueToolkit.providerLayer(OpaqueToolkit.merge(...(this.opts.toolkits ?? []))),\n traceWriterLayer,\n blueprintRegistryLayer,\n\n // `FunctionInvocationService` is deprecated; new code should yield `Operation.Service`.\n // The cloudflare wrapper provides only the unavailable layer to satisfy the (still-present)\n // type union — handlers that yield it will die at invocation time.\n FunctionInvocationService.layerNotAvailable,\n );\n }\n}\n\n/**\n * Backs `Trace.TraceService` with the EDGE-provided `TraceService` so that operation\n * handlers can write trace events that are forwarded to the runtime's trace sink.\n */\nconst makeTraceWriterLayer = (traceService: TraceProtocol.TraceService): Layer.Layer<Trace.TraceService> =>\n Layer.succeed(Trace.TraceService, {\n write: (eventType, payload) => {\n log('Writing trace event', {\n eventType: eventType.key,\n });\n traceService.write([\n {\n key: eventType.key,\n isEphemeral: eventType.isEphemeral,\n data: payload,\n },\n ]);\n },\n });\n\n/**\n * AI service layer that proxies HTTP requests through the EDGE-provided `FunctionsAiService`.\n */\nconst InternalAiServiceLayer = (functionsAiService: EdgeFunctionEnv.FunctionsAiService) =>\n AiModelResolver.AiModelResolver.buildAiService.pipe(\n Layer.provide(\n AnthropicResolver.make().pipe(\n Layer.provide(\n AnthropicClient.layer({\n // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.\n apiUrl: 'http://internal/provider/anthropic',\n }).pipe(Layer.provide(FunctionsAiHttpClient.layer(functionsAiService))),\n ),\n ),\n ),\n );\n\n/**\n * Backs `Operation.Service` with the EDGE-provided `FunctionsService` so that operation\n * handlers can invoke other deployed operations remotely. The `deployedId` on the operation\n * definition is used as the routing key.\n */\nconst makeOperationServiceLayer = (\n functionsService: EdgeFunctionEnv.FunctionsService,\n): Layer.Layer<Operation.Service> => {\n const invokeRemote = async (\n op: Operation.Definition.Any,\n input: unknown,\n options?: Operation.InvokeOptions,\n ): Promise<{ data?: unknown; error?: Error }> => {\n invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`);\n const result = await functionsService.invoke(op.meta.deployedId, input, {\n spaceId: options?.spaceId,\n // Forward the conversation DXN so the remote runtime can rebuild conversation-scoped\n // services (e.g. `AiContext.Service`) needed by operations like `GetContext`.\n conversation: options?.conversation,\n });\n if (result._kind === 'success') {\n return { data: result.data };\n }\n return { error: ErrorCodec.decode(result.error) };\n };\n\n return Layer.succeed(Operation.Service, {\n invoke: ((op: Operation.Definition.Any, input: unknown, options?: Operation.InvokeOptions) =>\n Effect.tryPromise(() => invokeRemote(op, input, options)).pipe(\n Effect.orDie,\n Effect.flatMap((outcome) =>\n outcome.error ? Effect.die(outcome.error) : Effect.succeed(outcome.data as never),\n ),\n )) as Operation.OperationService['invoke'],\n schedule: ((op: Operation.Definition.Any, input: unknown) =>\n Effect.sync(() => {\n invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`);\n // Fire and forget — schedule is intentionally non-awaiting.\n void functionsService.invoke(op.meta.deployedId, input).catch(() => {\n // Swallow errors — schedule is observability-only.\n });\n })) as Operation.OperationService['schedule'],\n invokePromise: ((op: Operation.Definition.Any, input: unknown, options?: Operation.InvokeOptions) =>\n invokeRemote(op, input, options).catch((error: unknown) => ({\n error: error instanceof Error ? error : new Error(String(error)),\n }))) as Operation.OperationService['invokePromise'],\n } satisfies Operation.OperationService);\n};\n\nconst unavailableOperationServiceLayer = Layer.succeed(Operation.Service, {\n invoke: () => Effect.die('Operation.Service is not available: missing functionsService in EDGE context.'),\n schedule: () => Effect.die('Operation.Service is not available: missing functionsService in EDGE context.'),\n invokePromise: async () => ({\n error: new Error('Operation.Service is not available: missing functionsService in EDGE context.'),\n }),\n} as Operation.OperationService);\n\n/**\n * Backs `OperationRegistry.Service` with the EDGE-provided `FunctionsService.query`. Returns\n * the first persistent operation matching the requested key, or `Option.none()` when not found.\n */\nconst makeOperationRegistryLayer = (\n functionsService: EdgeFunctionEnv.FunctionsService,\n spaceId: SpaceId | undefined,\n): Layer.Layer<OperationRegistry.Service> =>\n Layer.succeed(OperationRegistry.Service, {\n resolve: (key: string) =>\n Effect.gen(function* () {\n const records = yield* Effect.tryPromise(() => functionsService.query({ spaceId })).pipe(Effect.orDie);\n const match = (records as Operation.PersistentOperation[]).find((record) => Operation.getKey(record) === key);\n return match ? Option.some(Operation.deserialize(match)) : Option.none();\n }),\n });\n\nconst emptyOperationRegistryLayer = Layer.succeed(OperationRegistry.Service, {\n resolve: () => Effect.succeed(Option.none()),\n});\n\nconst decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {\n if (value == null) {\n return value;\n }\n\n const encoded = SchemaAST.encodedBoundAST(ast);\n if (Ref.isRefType(encoded)) {\n if (Ref.isRef(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {\n const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });\n return refFromEncodedReference(value as any, resolver);\n }\n\n return value;\n }\n\n switch (encoded._tag) {\n case 'TypeLiteral': {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return value;\n }\n const result: Record<string, unknown> = { ...(value as any) };\n for (const prop of SchemaAST.getPropertySignatures(encoded)) {\n const key = prop.name.toString();\n if (key in result) {\n result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);\n }\n }\n return result;\n }\n\n case 'TupleType': {\n if (!Array.isArray(value)) {\n return value;\n }\n\n // For arrays, effect uses TupleType with empty elements and a single rest element.\n if (encoded.elements.length === 0 && encoded.rest.length === 1) {\n const elementType = encoded.rest[0].type;\n return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));\n }\n\n return value;\n }\n\n case 'Union': {\n // Optional values are represented as union with undefined.\n const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));\n if (nonUndefined.length === 1) {\n return decodeRefsFromSchema(nonUndefined[0], value, db);\n }\n\n // For other unions we can't safely pick a branch without validating.\n return value;\n }\n\n case 'Suspend': {\n return decodeRefsFromSchema(encoded.f(), value, db);\n }\n\n case 'Refinement': {\n return decodeRefsFromSchema(encoded.from, value, db);\n }\n\n default: {\n return value;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Headers from '@effect/platform/Headers';\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientError from '@effect/platform/HttpClientError';\nimport * as HttpClientResponse from '@effect/platform/HttpClientResponse';\nimport * as Effect from 'effect/Effect';\nimport * as FiberRef from 'effect/FiberRef';\nimport * as Layer from 'effect/Layer';\nimport * as Stream from 'effect/Stream';\n\nimport { FunctionsAiMemoizationMissError, FunctionsAiUpstreamError } from '@dxos/compute';\nimport { log } from '@dxos/log';\nimport { type EdgeFunctionEnv, ErrorCodec } from '@dxos/protocols';\n\n/**\n * Copy pasted from https://github.com/Effect-TS/effect/blob/main/packages/platform/src/internal/fetchHttpClient.ts\n */\nexport const requestInitTagKey = '@effect/platform/FetchHttpClient/FetchOptions';\n\n/**\n * Shape of the JSON error envelope emitted by the upstream AI gateway (and by the memoization\n * layer that fronts it in test environments).\n *\n * @example\n * ```json\n * {\n * \"type\": \"error\",\n * \"error\": {\n * \"type\": \"memoization_miss\",\n * \"message\": \"No memoized Anthropic conversation found for ...\",\n * \"cacheKey\": \"114dae3db8fe60...\"\n * }\n * }\n * ```\n */\ntype UpstreamErrorEnvelope = {\n type?: string;\n error?: {\n type?: string;\n message?: string;\n cacheKey?: string;\n };\n};\n\nexport class FunctionsAiHttpClient {\n static make = (service: EdgeFunctionEnv.FunctionsAiService) =>\n HttpClient.make((request, url, signal, fiber) => {\n const context = fiber.getFiberRef(FiberRef.currentContext);\n const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {};\n const headers = options.headers\n ? Headers.merge(Headers.fromInput(options.headers), request.headers)\n : request.headers;\n\n const send = (body: BodyInit | undefined) =>\n Effect.tryPromise({\n try: () =>\n service.fetch(\n new Request(url, {\n ...options,\n method: request.method,\n headers,\n body,\n // Note: Don't pass signal - it can't be serialized through RPC\n }),\n ),\n catch: (cause) => {\n log.error('Failed to fetch', { errorSerialized: ErrorCodec.encode(cause as Error) });\n return new HttpClientError.RequestError({\n request,\n reason: 'Transport',\n cause,\n });\n },\n }).pipe(\n Effect.flatMap((response) =>\n // Inspect the body before handing the response to `@effect/ai` so that structured\n // upstream errors surface as typed defects (`FunctionsAiUpstreamError` and friends)\n // rather than as the generic `HttpResponseError` from `@effect/ai/AiError`.\n Effect.flatMap(\n Effect.promise(() => parseUpstreamError(response)),\n (typedError) =>\n typedError ? Effect.die(typedError) : Effect.succeed(HttpClientResponse.fromWeb(request, response)),\n ),\n ),\n );\n\n switch (request.body._tag) {\n case 'Raw':\n case 'Uint8Array':\n return send(request.body.body as any);\n case 'FormData':\n return send(request.body.formData);\n case 'Stream':\n return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect.flatMap(send));\n }\n\n return send(undefined);\n });\n\n static layer = (service: EdgeFunctionEnv.FunctionsAiService) =>\n Layer.succeed(HttpClient.HttpClient, FunctionsAiHttpClient.make(service));\n}\n\n/**\n * Returns a typed error if the response is a non-2xx JSON payload matching\n * {@link UpstreamErrorEnvelope}; otherwise returns `undefined` and the response is forwarded\n * unchanged.\n */\nconst parseUpstreamError = async (response: Response): Promise<Error | undefined> => {\n if (response.ok) {\n return undefined;\n }\n const contentType = response.headers.get('content-type') ?? '';\n if (!contentType.toLowerCase().includes('application/json')) {\n return undefined;\n }\n let body: UpstreamErrorEnvelope;\n try {\n body = (await response.clone().json()) as UpstreamErrorEnvelope;\n } catch {\n return undefined;\n }\n if (!body || body.type !== 'error' || typeof body.error !== 'object' || body.error === null) {\n return undefined;\n }\n const inner = body.error;\n const message = inner.message ?? `Upstream AI service responded with HTTP ${response.status}`;\n if (inner.type === 'memoization_miss' && typeof inner.cacheKey === 'string') {\n return new FunctionsAiMemoizationMissError({\n message,\n context: { cacheKey: inner.cacheKey, status: response.status },\n });\n }\n return new FunctionsAiUpstreamError({\n message,\n context: { type: inner.type, status: response.status, ...(inner.cacheKey ? { cacheKey: inner.cacheKey } : {}) },\n });\n};\n"],
5
+ "mappings": ";AAIA,YAAYA,gBAAgB;AAC5B,YAAYC,uBAAuB;AAGnC,YAAYC,YAAY;AACxB,YAAYC,WAAW;AACvB,YAAYC,cAAc;AAE1B,SAASC,kBAAkB;AAC3B,SAASC,UAAUC,aAAa;AAChC,SAASC,mBAAmB;AAErB,IAAMC,+BAAN,MAAMA;;EACX,YAA6BC,cAA8C,CAAA,GAAI;SAAlDA,cAAAA;EAAmD;EAEhFC,eAAeD,aAA2E;AACxF,SAAKA,YAAYE,KAAI,GAAIF,WAAAA;AACzB,WAAO;EACT;EAEA,MAAMG,iBAAiBC,OAA4E;AACjG,WAAO,KAAKJ,YAAYK,OAAO,CAACC,eAAeA,WAAWC,YAAYH,MAAMG,OAAO;EACrF;EAEA,MAAMC,cAAcJ,OAA0E;AAC5F,UAAME,aAAa,KAAKN,YAAYS,KAAK,CAACH,gBAAeA,YAAWC,YAAYH,MAAMG,OAAO;AAC7F,QAAI,CAACD,YAAY;AACf,YAAM,IAAII,MAAM,qCAAqCN,MAAMG,OAAO,EAAE;IACtE;AAEA,WAAOD;EACT;AACF;AAKO,IAAMK,oBAAoB,CAACC,OAAeC,SACpCC,sBAAW,CAACC,YAAAA;AACrB,QAAMC,gBAAgBH,OAAO,GAAGA,IAAAA,IAAQD,KAAAA,KAAUA;AAClD,SAAyBK,4BAAUF,SAAS,iBAAiBC,aAAAA;AAC/D,CAAA;AAEK,IAAME,6BAA6B,CAAClB,gBACnCmB,cAAQxB,WAAWyB,oBAAoB,IAAIrB,6BAA6BC,WAAAA,CAAAA;AAEzE,IAAMqB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AEhB,OAAOA,WAAAA,YAAAA,WAAAA,QAAAA,MAAAA,QAAAA,MAAAA,GAAAA;AACT,eAAAA;MACA;YAA0C,SAAS;QAAS,GAAAA;MAC5D;iBACQlH,QAAgBwH,gCAAQ,OAAA,GAAA;AAC9B,cAAIxH,MAAO0B,KAAAA,KAAQ,SAAA;YACjBA,OAAO1B,QAAOyH;AAChB,iBAAA,GAAA,IAAA,qBAAA,KAAA,MAAA,OAAA,GAAA,GAAA,EAAA;QACF;MACA;AACF,aAAA;IAEA;SAAkB;UAEd,CAAA,MAAOP,QAAAA,MAAAA,GAAAA;AACT,eAAAA;MAEA;UAEE,QAAMQ,SAAAA,WAAsBC,KAAK,QAAO,KAAA,WAAA,GAAA;AACxC,cAAA,cAAiCC,QAASH,KAAAA,CAAAA,EAAAA;AAC5C,eAAAP,OAAA,IAAA,CAAA,SAAA,qBAAA,aAAA,MAAA,EAAA,CAAA;MAEA;AACF,aAAAA;IAEA;SAAc;AAGZ,YAAIW,eAAa1C,QAAW,MAAG,OAAA,CAAA,MAAA,CAAA,6BAAA,CAAA,CAAA;UAC7B,aAAOsC,WAAAA,GAAAA;AACT,eAAA,qBAAA,aAAA,CAAA,GAAAP,QAAA,EAAA;MAEA;AAEF,aAAAA;IAEA;SAAgB;AAEhB,aAAA,qBAAA,QAAA,EAAA,GAAAA,QAAA,EAAA;IAEA;SAAmB;AAEnB,aAAA,qBAAA,QAAA,MAAAA,QAAA,EAAA;IAEA;;AAEA,aAAAA;IACF;EACF;;",
6
+ "names": ["HttpClient", "HttpClientRequest", "Effect", "Layer", "Redacted", "Credential", "Database", "Query", "AccessToken", "ConfiguredCredentialsService", "credentials", "addCredentials", "push", "queryCredentials", "query", "filter", "credential", "service", "getCredential", "find", "Error", "withAuthorization", "token", "kind", "mapRequest", "request", "authorization", "setHeader", "configuredCredentialsLayer", "succeed", "CredentialsService", "credentialsLayerConfig", "effect", "gen", "serviceCredentials", "forEach", "apiKey", "value", "credentialsLayerFromDatabase", "caching", "dbService", "Service", "cache", "Map", "cacheKey", "JSON", "stringify", "has", "get", "accessTokens", "db", "type", "run", "accessToken", "source", "map", "set", "length", "Context", "Effect", "Layer", "FunctionInvocationService", "Tag", "layerNotAvailable", "succeed", "invokeFunction", "die", "resolveFunction", "functionDef", "input", "serviceFunctionEffect", "service", "key", "QueueService", "feedServiceFromQueueServiceLayer", "MESSAGE_PROPERTY_TOOL_CALL_ID", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "getUserFunctionIdInMetadata", "meta", "keys", "find", "key", "source", "id", "setUserFunctionIdInMetadata", "functionId", "Error", "push", "Effect", "Layer", "Option", "Schema", "SchemaAST", "AiModelResolver", "AiService", "AnthropicResolver", "Blueprint", "LifecycleState", "Database", "JsonSchema", "createFeedServiceLayer", "EchoClient", "refFromEncodedReference", "runAndForwardErrors", "assertState", "failedInvariant", "PublicKey", "log", "ErrorCodec", "configuredCredentialsLayer", "Headers", "HttpClient", "HttpClientError", "HttpClientResponse", "Effect", "FiberRef", "Layer", "Stream", "FunctionsAiMemoizationMissError", "FunctionsAiUpstreamError", "log", "ErrorCodec", "make", "getFiberRef", "options", "unsafeMap", "get", "requestInitTagKey", "headers", "merge", "fromInput", "send", "body", "tryPromise", "service", "Request", "method", "request", "cause", "errorSerialized", "RequestError", "reason", "formData", "toReadableStreamEffect", "undefined", "layer", "contentType", "inner", "message", "context", "status", "cacheKey", "Operation", "isOperationWithHandler", "func", "TypeError", "meta", "key", "name", "description", "inputSchema", "JsonSchema", "outputSchema", "output", "undefined", "services", "service", "handler", "serviceTags", "includes", "Database", "FunctionError", "message", "Schema", "onExcessProperty", "data", "error", "InvalidOperationInputError", "cause", "types", "invariant", "funcContext", "graph", "result", "dataWithDecodedRefs", "Effect", "isEffect", "runAndForwardErrors", "flush", "disk", "indexes", "InvalidOperationOutputError", "context", "client", "db", "queues", "opts", "connectToService", "dataService", "queryService", "queueService", "spaceId", "failedInvariant", "spaceKey", "PublicKey", "fromHex", "reactiveSchemaQuery", "preloadSchemaOnOpen", "open", "close", "createLayer", "assertState", "dbLayer", "layer", "queuesLayer", "QueueService", "feedLayer", "createFeedServiceLayer", "notAvailable", "credentials", "credentialsLayerFromDatabase", "caching", "pipe", "Layer", "aiLayer", "InternalAiServiceLayer", "operationServiceLayer", "functionsService", "makeOperationServiceLayer", "operationRegistryLayer", "makeOperationRegistryLayer", "traceWriterLayer", "traceService", "makeTraceWriterLayer", "Trace", "writerLayerNoop", "log", "functionsAiService", "spaceRootUrl", "toolkits", "length", "blueprintRegistryLayer", "blueprintRegistry", "OpaqueToolkit", "providerLayer", "write", "payload", "eventType", "__dxlog_file", "isEphemeral", "invokeRemote", "input", "options", "deployedId", "op", "ErrorCodec", "schedule", "invokePromise", "Error", "String", "invoke", "die", "resolve", "records", "tryPromise", "match", "find", "some", "deserialize", "Option", "none", "value", "Ref", "encoded", "resolver", "createRefResolver", "space", "toString", "decodeRefsFromSchema", "elementType", "rest", "item", "nonUndefined"]
7
7
  }