@dxos/functions 0.8.4-main.d05539e30a → 0.8.4-main.d9fc60f731
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/dist/lib/neutral/index.mjs +12 -19
- package/dist/lib/neutral/index.mjs.map +4 -4
- package/dist/lib/neutral/meta.json +1 -1
- package/dist/types/src/protocol/protocol.d.ts +1 -6
- package/dist/types/src/protocol/protocol.d.ts.map +1 -1
- package/dist/types/src/sdk.d.ts +2 -2
- package/dist/types/src/sdk.d.ts.map +1 -1
- package/dist/types/src/services/index.d.ts +0 -1
- package/dist/types/src/services/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +19 -19
- package/src/protocol/protocol.test.ts +3 -2
- package/src/protocol/protocol.ts +16 -26
- package/src/sdk.ts +1 -3
- package/src/services/index.ts +0 -1
- package/dist/types/src/services/queues.d.ts +0 -2
- package/dist/types/src/services/queues.d.ts.map +0 -1
- package/src/services/queues.ts +0 -5
|
@@ -86,9 +86,6 @@ var FunctionInvocationService = class _FunctionInvocationService extends Context
|
|
|
86
86
|
static resolveFunction = (key) => Effect2.serviceFunctionEffect(_FunctionInvocationService, (service) => service.resolveFunction)(key);
|
|
87
87
|
};
|
|
88
88
|
|
|
89
|
-
// src/services/queues.ts
|
|
90
|
-
import { QueueService, feedServiceFromQueueServiceLayer } from "@dxos/echo-db";
|
|
91
|
-
|
|
92
89
|
// src/services/tracing.ts
|
|
93
90
|
var MESSAGE_PROPERTY_TOOL_CALL_ID = "toolCallId";
|
|
94
91
|
|
|
@@ -121,10 +118,10 @@ import * as Schema from "effect/Schema";
|
|
|
121
118
|
import * as SchemaAST from "effect/SchemaAST";
|
|
122
119
|
import { AiModelResolver, AiService, OpaqueToolkit } from "@dxos/ai";
|
|
123
120
|
import { AnthropicResolver } from "@dxos/ai/resolvers";
|
|
124
|
-
import {
|
|
121
|
+
import { FunctionError, InvalidOperationInputError, InvalidOperationOutputError, Operation, OperationRegistry, Trace } from "@dxos/compute";
|
|
125
122
|
import { LifecycleState, Resource } from "@dxos/context";
|
|
126
|
-
import { Database as Database2, Feed, JsonSchema, Ref } from "@dxos/echo";
|
|
127
|
-
import { createFeedServiceLayer, EchoClient } from "@dxos/echo-db";
|
|
123
|
+
import { Database as Database2, Feed, JsonSchema, Ref, Registry } from "@dxos/echo";
|
|
124
|
+
import { createFeedServiceLayer, EchoClient, makeRegistry } from "@dxos/echo-db";
|
|
128
125
|
import { refFromEncodedReference } from "@dxos/echo/internal";
|
|
129
126
|
import { runAndForwardErrors } from "@dxos/effect";
|
|
130
127
|
import { assertState, failedInvariant, invariant } from "@dxos/invariant";
|
|
@@ -309,7 +306,7 @@ var wrapFunctionHandler = (func, opts = {}) => {
|
|
|
309
306
|
services: func.services.map((service) => service.key)
|
|
310
307
|
},
|
|
311
308
|
handler: async ({ data, context }) => {
|
|
312
|
-
if ((serviceTags.includes(Database2.Service.key) || serviceTags.includes(
|
|
309
|
+
if ((serviceTags.includes(Database2.Service.key) || serviceTags.includes(Feed.FeedService.key)) && (!context.services.dataService || !context.services.queryService)) {
|
|
313
310
|
throw new FunctionError({
|
|
314
311
|
message: "Services not provided: dataService, queryService"
|
|
315
312
|
});
|
|
@@ -340,7 +337,7 @@ var wrapFunctionHandler = (func, opts = {}) => {
|
|
|
340
337
|
];
|
|
341
338
|
if (types.length > 0) {
|
|
342
339
|
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
|
-
|
|
340
|
+
funcContext.db.graph.registry.add(types);
|
|
344
341
|
}
|
|
345
342
|
const dataWithDecodedRefs = funcContext.db && !SchemaAST.isAnyKeyword(func.input.ast) ? decodeRefsFromSchema(func.input.ast, data, funcContext.db) : data;
|
|
346
343
|
let result = await func.handler(dataWithDecodedRefs);
|
|
@@ -416,7 +413,6 @@ var FunctionContext = class extends Resource {
|
|
|
416
413
|
createLayer() {
|
|
417
414
|
assertState(this._lifecycleState === LifecycleState.OPEN, "FunctionContext is not open");
|
|
418
415
|
const dbLayer = this.db ? Database2.layer(this.db) : Database2.notAvailable;
|
|
419
|
-
const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;
|
|
420
416
|
const feedLayer = this.queues ? createFeedServiceLayer(this.queues) : Feed.notAvailable;
|
|
421
417
|
const credentials = dbLayer ? credentialsLayerFromDatabase({
|
|
422
418
|
caching: true
|
|
@@ -433,11 +429,10 @@ var FunctionContext = class extends Resource {
|
|
|
433
429
|
spaceRootUrl: this.context.spaceRootUrl,
|
|
434
430
|
toolkits: this.opts.toolkits?.length ?? 0,
|
|
435
431
|
types: this.opts.types?.length ?? 0
|
|
436
|
-
}, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L:
|
|
437
|
-
const
|
|
432
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 233, S: this });
|
|
433
|
+
const registryLayer = this.db ? Layer4.succeed(Registry.Service, this.db.graph.registry) : Layer4.succeed(Registry.Service, makeRegistry());
|
|
438
434
|
return Layer4.mergeAll(
|
|
439
435
|
dbLayer,
|
|
440
|
-
queuesLayer,
|
|
441
436
|
feedLayer,
|
|
442
437
|
credentials,
|
|
443
438
|
operationServiceLayer,
|
|
@@ -445,7 +440,7 @@ var FunctionContext = class extends Resource {
|
|
|
445
440
|
aiLayer,
|
|
446
441
|
OpaqueToolkit.providerLayer(OpaqueToolkit.merge(...this.opts.toolkits ?? [])),
|
|
447
442
|
traceWriterLayer,
|
|
448
|
-
|
|
443
|
+
registryLayer,
|
|
449
444
|
// `FunctionInvocationService` is deprecated; new code should yield `Operation.Service`.
|
|
450
445
|
// The cloudflare wrapper provides only the unavailable layer to satisfy the (still-present)
|
|
451
446
|
// type union — handlers that yield it will die at invocation time.
|
|
@@ -457,7 +452,7 @@ var makeTraceWriterLayer = (traceService) => Layer4.succeed(Trace.TraceService,
|
|
|
457
452
|
write: (eventType, payload) => {
|
|
458
453
|
log2("Writing trace event", {
|
|
459
454
|
eventType: eventType.key
|
|
460
|
-
}, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L:
|
|
455
|
+
}, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 254, S: void 0 });
|
|
461
456
|
traceService.write([
|
|
462
457
|
{
|
|
463
458
|
key: eventType.key,
|
|
@@ -473,7 +468,7 @@ var InternalAiServiceLayer = (functionsAiService) => AiModelResolver.AiModelReso
|
|
|
473
468
|
}).pipe(Layer4.provide(FunctionsAiHttpClient.layer(functionsAiService)))))));
|
|
474
469
|
var makeOperationServiceLayer = (functionsService) => {
|
|
475
470
|
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:
|
|
471
|
+
invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 278, S: void 0, A: ["op.meta.deployedId", "`Operation '${op.meta.key}' has no deployedId; cannot invoke remotely.`"] });
|
|
477
472
|
const result = await functionsService.invoke(op.meta.deployedId, input, {
|
|
478
473
|
spaceId: options?.spaceId,
|
|
479
474
|
// Forward the conversation DXN so the remote runtime can rebuild conversation-scoped
|
|
@@ -491,8 +486,8 @@ var makeOperationServiceLayer = (functionsService) => {
|
|
|
491
486
|
};
|
|
492
487
|
return Layer4.succeed(Operation.Service, {
|
|
493
488
|
invoke: (op, input, options) => Effect4.tryPromise(() => invokeRemote(op, input, options)).pipe(Effect4.orDie, Effect4.flatMap((outcome) => outcome.error ? Effect4.die(outcome.error) : Effect4.succeed(outcome.data))),
|
|
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:
|
|
489
|
+
schedule: (op, input, _options) => Effect4.sync(() => {
|
|
490
|
+
invariant(op.meta.deployedId, `Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`, { "~LogMeta": "~LogMeta", F: __dxlog_file2, L: 297, S: void 0, A: ["op.meta.deployedId", "`Operation '${op.meta.key}' has no deployedId; cannot schedule remotely.`"] });
|
|
496
491
|
void functionsService.invoke(op.meta.deployedId, input).catch(() => {
|
|
497
492
|
});
|
|
498
493
|
}),
|
|
@@ -589,11 +584,9 @@ export {
|
|
|
589
584
|
FUNCTIONS_PRESET_META_KEY,
|
|
590
585
|
FunctionInvocationService,
|
|
591
586
|
MESSAGE_PROPERTY_TOOL_CALL_ID,
|
|
592
|
-
QueueService,
|
|
593
587
|
configuredCredentialsLayer,
|
|
594
588
|
credentialsLayerConfig,
|
|
595
589
|
credentialsLayerFromDatabase,
|
|
596
|
-
feedServiceFromQueueServiceLayer,
|
|
597
590
|
getUserFunctionIdInMetadata,
|
|
598
591
|
setUserFunctionIdInMetadata,
|
|
599
592
|
withAuthorization,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../src/services/credentials.ts", "../../../src/services/function-invocation-service.ts", "../../../src/services/
|
|
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,oBAA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A;IAEA;AACF,WAAAA;EAEA;UACE,QAAK,MAAA;SAAe;UAEhB,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", "
|
|
3
|
+
"sources": ["../../../src/services/credentials.ts", "../../../src/services/function-invocation-service.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 { 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\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 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, Registry, type Type } from '@dxos/echo';\nimport {\n createFeedServiceLayer,\n EchoClient,\n type EchoDatabaseImpl,\n makeRegistry,\n type QueueFactory,\n} 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 { configuredCredentialsLayer, credentialsLayerFromDatabase, FunctionInvocationService } 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/**\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) || 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 funcContext.db.graph.registry.add(types);\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 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 registryLayer = this.db\n ? Layer.succeed(Registry.Service, this.db.graph.registry)\n : Layer.succeed(Registry.Service, makeRegistry());\n\n return Layer.mergeAll(\n dbLayer,\n feedLayer,\n credentials,\n operationServiceLayer,\n operationRegistryLayer,\n aiLayer,\n OpaqueToolkit.providerLayer(OpaqueToolkit.merge(...(this.opts.toolkits ?? []))),\n traceWriterLayer,\n registryLayer,\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, _options?: Operation.InvokeOptions) =>\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,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gB;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", "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", "FunctionError", "InvalidOperationInputError", "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", "registry", "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", "feedLayer", "createFeedServiceLayer", "credentials", "credentialsLayerFromDatabase", "caching", "pipe", "Layer", "aiLayer", "InternalAiServiceLayer", "operationServiceLayer", "functionsService", "makeOperationServiceLayer", "operationRegistryLayer", "makeOperationRegistryLayer", "traceWriterLayer", "traceService", "makeTraceWriterLayer", "Trace", "writerLayerNoop", "log", "functionsAiService", "spaceRootUrl", "toolkits", "length", "registryLayer", "succeed", "Registry", "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
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/sdk.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/sdk.ts":{"bytes":2099,"imports":[],"format":"esm"},"src/services/credentials.ts":{"bytes":12961,"imports":[{"path":"@effect/platform/HttpClient","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClientRequest","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Redacted","kind":"import-statement","external":true},{"path":"@dxos/compute","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/types","kind":"import-statement","external":true}],"format":"esm"},"src/services/function-invocation-service.ts":{"bytes":3812,"imports":[{"path":"effect/Context","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true}],"format":"esm"},"src/services/tracing.ts":{"bytes":662,"imports":[],"format":"esm"},"src/services/index.ts":{"bytes":741,"imports":[{"path":"src/services/credentials.ts","kind":"import-statement","original":"./credentials"},{"path":"src/services/function-invocation-service.ts","kind":"import-statement","original":"./function-invocation-service"},{"path":"src/services/tracing.ts","kind":"import-statement","original":"./tracing"}],"format":"esm"},"src/types/url.ts":{"bytes":3289,"imports":[],"format":"esm"},"src/types/index.ts":{"bytes":363,"imports":[{"path":"src/types/url.ts","kind":"import-statement","original":"./url"}],"format":"esm"},"src/protocol/functions-ai-http-client.ts":{"bytes":15950,"imports":[{"path":"@effect/platform/Headers","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClient","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClientError","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClientResponse","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/FiberRef","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Stream","kind":"import-statement","external":true},{"path":"@dxos/compute","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true}],"format":"esm"},"src/protocol/protocol.ts":{"bytes":60690,"imports":[{"path":"@effect/ai-anthropic/AnthropicClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Option","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"effect/SchemaAST","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/ai/resolvers","kind":"import-statement","external":true},{"path":"@dxos/compute","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo/internal","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"src/services/index.ts","kind":"import-statement","original":"../services"},{"path":"src/protocol/functions-ai-http-client.ts","kind":"import-statement","original":"./functions-ai-http-client"}],"format":"esm"},"src/protocol/index.ts":{"bytes":376,"imports":[{"path":"src/protocol/protocol.ts","kind":"import-statement","original":"./protocol"}],"format":"esm"},"src/index.ts":{"bytes":620,"imports":[{"path":"src/sdk.ts","kind":"import-statement","original":"./sdk"},{"path":"src/services/index.ts","kind":"import-statement","original":"./services"},{"path":"src/types/index.ts","kind":"import-statement","original":"./types"},{"path":"src/protocol/index.ts","kind":"import-statement","original":"./protocol"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":45283},"dist/lib/neutral/index.mjs":{"imports":[{"path":"@effect/platform/HttpClient","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClientRequest","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Redacted","kind":"import-statement","external":true},{"path":"@dxos/compute","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/types","kind":"import-statement","external":true},{"path":"effect/Context","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"@effect/ai-anthropic/AnthropicClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Option","kind":"import-statement","external":true},{"path":"effect/Schema","kind":"import-statement","external":true},{"path":"effect/SchemaAST","kind":"import-statement","external":true},{"path":"@dxos/ai","kind":"import-statement","external":true},{"path":"@dxos/ai/resolvers","kind":"import-statement","external":true},{"path":"@dxos/compute","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/echo","kind":"import-statement","external":true},{"path":"@dxos/echo-db","kind":"import-statement","external":true},{"path":"@dxos/echo/internal","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/keys","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@effect/platform/Headers","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClient","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClientError","kind":"import-statement","external":true},{"path":"@effect/platform/HttpClientResponse","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/FiberRef","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/Stream","kind":"import-statement","external":true},{"path":"@dxos/compute","kind":"import-statement","external":true},{"path":"@dxos/log","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true}],"exports":["ConfiguredCredentialsService","FUNCTIONS_META_KEY","FUNCTIONS_PRESET_META_KEY","FunctionInvocationService","MESSAGE_PROPERTY_TOOL_CALL_ID","configuredCredentialsLayer","credentialsLayerConfig","credentialsLayerFromDatabase","getUserFunctionIdInMetadata","setUserFunctionIdInMetadata","withAuthorization","wrapFunctionHandler"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0},"src/services/credentials.ts":{"bytesInOutput":2907},"src/services/index.ts":{"bytesInOutput":0},"src/services/function-invocation-service.ts":{"bytesInOutput":818},"src/services/tracing.ts":{"bytesInOutput":50},"src/types/url.ts":{"bytesInOutput":576},"src/protocol/protocol.ts":{"bytesInOutput":15806},"src/protocol/functions-ai-http-client.ts":{"bytesInOutput":3695}},"bytes":24468}}}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OpaqueToolkit } from '@dxos/ai';
|
|
2
|
-
import {
|
|
2
|
+
import { Operation } from '@dxos/compute';
|
|
3
3
|
import { type Type } from '@dxos/echo';
|
|
4
4
|
import { type FunctionProtocol } from '@dxos/protocols';
|
|
5
5
|
export interface FunctionWrappingOptions {
|
|
@@ -11,11 +11,6 @@ export interface FunctionWrappingOptions {
|
|
|
11
11
|
* Toolkits to make available via the `OpaqueToolkitProvider`.
|
|
12
12
|
*/
|
|
13
13
|
toolkits?: OpaqueToolkit.OpaqueToolkit[];
|
|
14
|
-
/**
|
|
15
|
-
* Blueprint registry to expose as `Blueprint.RegistryService` inside handler Effects.
|
|
16
|
-
* Required for operations that declare `Blueprint.RegistryService` in their `services` list.
|
|
17
|
-
*/
|
|
18
|
-
blueprintRegistry?: Blueprint.Registry;
|
|
19
14
|
}
|
|
20
15
|
/**
|
|
21
16
|
* Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../../src/protocol/protocol.ts"],"names":[],"mappings":"AAWA,OAAO,EAA8B,aAAa,EAAE,MAAM,UAAU,CAAC;AAErE,OAAO,
|
|
1
|
+
{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../../src/protocol/protocol.ts"],"names":[],"mappings":"AAWA,OAAO,EAA8B,aAAa,EAAE,MAAM,UAAU,CAAC;AAErE,OAAO,EAIL,SAAS,EAGV,MAAM,eAAe,CAAC;AAEvB,OAAO,EAA6C,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAalF,OAAO,EAA+B,KAAK,gBAAgB,EAAsB,MAAM,iBAAiB,CAAC;AAMzG,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,KAAK,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;IAEzB;;OAEG;IACH,QAAQ,CAAC,EAAE,aAAa,CAAC,aAAa,EAAE,CAAC;CAC1C;AAED;;GAEG;AACH,eAAO,MAAM,mBAAmB,SACxB,SAAS,CAAC,WAAW,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,SAC/C,uBAAuB,KAC5B,gBAAgB,CAAC,IA6FnB,CAAC"}
|
package/dist/types/src/sdk.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { type AiService } from '@dxos/ai';
|
|
2
2
|
import { type Credential, type Operation, type Trace } from '@dxos/compute';
|
|
3
3
|
import { type Database, type Feed } from '@dxos/echo';
|
|
4
|
-
import { type FunctionInvocationService
|
|
4
|
+
import { type FunctionInvocationService } from './services';
|
|
5
5
|
/**
|
|
6
6
|
* Services that are available to invoked functions.
|
|
7
7
|
* @deprecated
|
|
8
8
|
*/
|
|
9
|
-
export type FunctionServices = AiService.AiService | Credential.CredentialsService | Database.Service |
|
|
9
|
+
export type FunctionServices = AiService.AiService | Credential.CredentialsService | Database.Service | Feed.FeedService | Trace.TraceService | FunctionInvocationService | Operation.Service;
|
|
10
10
|
//# sourceMappingURL=sdk.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../../src/sdk.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,SAAS,EAAE,KAAK,KAAK,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAAE,KAAK,QAAQ,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EAAE,KAAK,yBAAyB,EAAE,
|
|
1
|
+
{"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../../src/sdk.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,UAAU,CAAC;AAC1C,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,SAAS,EAAE,KAAK,KAAK,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAAE,KAAK,QAAQ,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EAAE,KAAK,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAO5D;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GACxB,SAAS,CAAC,SAAS,GACnB,UAAU,CAAC,kBAAkB,GAC7B,QAAQ,CAAC,OAAO,GAChB,IAAI,CAAC,WAAW,GAChB,KAAK,CAAC,YAAY,GAGlB,yBAAyB,GACzB,SAAS,CAAC,OAAO,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/services/index.ts"],"names":[],"mappings":"AAIA,cAAc,eAAe,CAAC;AAC9B,cAAc,+BAA+B,CAAC;AAC9C,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/services/index.ts"],"names":[],"mappings":"AAIA,cAAc,eAAe,CAAC;AAC9B,cAAc,+BAA+B,CAAC;AAC9C,OAAO,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC"}
|