@dxos/functions 0.8.3 → 0.8.4-main.28f8d3d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/lib/browser/bundler/index.mjs +22 -10
  2. package/dist/lib/browser/bundler/index.mjs.map +3 -3
  3. package/dist/lib/browser/chunk-M2OIFLGE.mjs +486 -0
  4. package/dist/lib/browser/chunk-M2OIFLGE.mjs.map +7 -0
  5. package/dist/lib/browser/edge/index.mjs +2 -2
  6. package/dist/lib/browser/edge/index.mjs.map +1 -1
  7. package/dist/lib/browser/index.mjs +51 -37
  8. package/dist/lib/browser/index.mjs.map +3 -3
  9. package/dist/lib/browser/meta.json +1 -1
  10. package/dist/lib/browser/testing/index.mjs +39 -8
  11. package/dist/lib/browser/testing/index.mjs.map +4 -4
  12. package/dist/lib/node-esm/bundler/index.mjs +22 -10
  13. package/dist/lib/node-esm/bundler/index.mjs.map +3 -3
  14. package/dist/lib/node-esm/chunk-K7REX6H4.mjs +488 -0
  15. package/dist/lib/node-esm/chunk-K7REX6H4.mjs.map +7 -0
  16. package/dist/lib/node-esm/edge/index.mjs +2 -2
  17. package/dist/lib/node-esm/edge/index.mjs.map +1 -1
  18. package/dist/lib/node-esm/index.mjs +51 -37
  19. package/dist/lib/node-esm/index.mjs.map +3 -3
  20. package/dist/lib/node-esm/meta.json +1 -1
  21. package/dist/lib/node-esm/testing/index.mjs +39 -8
  22. package/dist/lib/node-esm/testing/index.mjs.map +4 -4
  23. package/dist/types/src/bundler/bundler.d.ts +1 -2
  24. package/dist/types/src/bundler/bundler.d.ts.map +1 -1
  25. package/dist/types/src/edge/functions.d.ts +1 -1
  26. package/dist/types/src/edge/functions.d.ts.map +1 -1
  27. package/dist/types/src/errors.d.ts +70 -0
  28. package/dist/types/src/errors.d.ts.map +1 -0
  29. package/dist/types/src/executor/executor.d.ts +3 -0
  30. package/dist/types/src/executor/executor.d.ts.map +1 -1
  31. package/dist/types/src/handler.d.ts +16 -15
  32. package/dist/types/src/handler.d.ts.map +1 -1
  33. package/dist/types/src/index.d.ts +1 -0
  34. package/dist/types/src/index.d.ts.map +1 -1
  35. package/dist/types/src/schema.d.ts +5 -5
  36. package/dist/types/src/services/credentials.d.ts +7 -3
  37. package/dist/types/src/services/credentials.d.ts.map +1 -1
  38. package/dist/types/src/services/database.d.ts +71 -3
  39. package/dist/types/src/services/database.d.ts.map +1 -1
  40. package/dist/types/src/services/event-logger.d.ts +65 -30
  41. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  42. package/dist/types/src/services/index.d.ts +2 -2
  43. package/dist/types/src/services/index.d.ts.map +1 -1
  44. package/dist/types/src/services/local-function-execution.d.ts +12 -0
  45. package/dist/types/src/services/local-function-execution.d.ts.map +1 -0
  46. package/dist/types/src/services/queues.d.ts +32 -6
  47. package/dist/types/src/services/queues.d.ts.map +1 -1
  48. package/dist/types/src/services/remote-function-execution-service.d.ts +15 -0
  49. package/dist/types/src/services/remote-function-execution-service.d.ts.map +1 -0
  50. package/dist/types/src/services/service-container.d.ts +29 -17
  51. package/dist/types/src/services/service-container.d.ts.map +1 -1
  52. package/dist/types/src/services/service-registry.d.ts +29 -0
  53. package/dist/types/src/services/service-registry.d.ts.map +1 -0
  54. package/dist/types/src/services/service-registry.test.d.ts +2 -0
  55. package/dist/types/src/services/service-registry.test.d.ts.map +1 -0
  56. package/dist/types/src/services/tracing.d.ts +13 -2
  57. package/dist/types/src/services/tracing.d.ts.map +1 -1
  58. package/dist/types/src/testing/index.d.ts +1 -0
  59. package/dist/types/src/testing/index.d.ts.map +1 -1
  60. package/dist/types/src/testing/layer.d.ts +10 -0
  61. package/dist/types/src/testing/layer.d.ts.map +1 -0
  62. package/dist/types/src/testing/logger.d.ts +3 -3
  63. package/dist/types/src/testing/logger.d.ts.map +1 -1
  64. package/dist/types/src/testing/services.d.ts +55 -9
  65. package/dist/types/src/testing/services.d.ts.map +1 -1
  66. package/dist/types/src/trace.d.ts +3 -5
  67. package/dist/types/src/trace.d.ts.map +1 -1
  68. package/dist/types/src/translations.d.ts +9 -9
  69. package/dist/types/src/translations.d.ts.map +1 -1
  70. package/dist/types/src/types.d.ts +7 -7
  71. package/dist/types/src/types.d.ts.map +1 -1
  72. package/dist/types/tsconfig.tsbuildinfo +1 -1
  73. package/package.json +36 -26
  74. package/src/bundler/bundler.test.ts +1 -1
  75. package/src/bundler/bundler.ts +26 -4
  76. package/src/edge/functions.ts +1 -1
  77. package/src/errors.ts +13 -0
  78. package/src/executor/executor.ts +20 -13
  79. package/src/handler.ts +34 -25
  80. package/src/index.ts +1 -0
  81. package/src/services/credentials.ts +47 -4
  82. package/src/services/database.ts +91 -3
  83. package/src/services/event-logger.ts +68 -37
  84. package/src/services/index.ts +2 -2
  85. package/src/services/local-function-execution.ts +74 -0
  86. package/src/services/queues.ts +51 -11
  87. package/src/services/{function-call-service.ts → remote-function-execution-service.ts} +7 -5
  88. package/src/services/service-container.ts +47 -42
  89. package/src/services/service-registry.test.ts +42 -0
  90. package/src/services/service-registry.ts +59 -0
  91. package/src/services/tracing.ts +19 -2
  92. package/src/testing/index.ts +1 -0
  93. package/src/testing/layer.ts +31 -0
  94. package/src/testing/logger.ts +4 -4
  95. package/src/testing/services.ts +97 -14
  96. package/src/trace.ts +3 -5
  97. package/src/translations.ts +4 -4
  98. package/src/types.ts +1 -1
  99. package/dist/lib/browser/chunk-WEFZUEL2.mjs +0 -300
  100. package/dist/lib/browser/chunk-WEFZUEL2.mjs.map +0 -7
  101. package/dist/lib/node/bundler/index.cjs +0 -260
  102. package/dist/lib/node/bundler/index.cjs.map +0 -7
  103. package/dist/lib/node/chunk-IJAE7FZK.cjs +0 -320
  104. package/dist/lib/node/chunk-IJAE7FZK.cjs.map +0 -7
  105. package/dist/lib/node/edge/index.cjs +0 -94
  106. package/dist/lib/node/edge/index.cjs.map +0 -7
  107. package/dist/lib/node/index.cjs +0 -522
  108. package/dist/lib/node/index.cjs.map +0 -7
  109. package/dist/lib/node/meta.json +0 -1
  110. package/dist/lib/node/testing/index.cjs +0 -43
  111. package/dist/lib/node/testing/index.cjs.map +0 -7
  112. package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs +0 -302
  113. package/dist/lib/node-esm/chunk-LIYPMWNQ.mjs.map +0 -7
  114. package/dist/types/src/services/ai.d.ts +0 -12
  115. package/dist/types/src/services/ai.d.ts.map +0 -1
  116. package/dist/types/src/services/function-call-service.d.ts +0 -16
  117. package/dist/types/src/services/function-call-service.d.ts.map +0 -1
  118. package/src/services/ai.ts +0 -32
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/services/database.ts", "../../../src/services/queues.ts", "../../../src/services/credentials.ts", "../../../src/services/tracing.ts", "../../../src/services/event-logger.ts", "../../../src/services/remote-function-execution-service.ts", "../../../src/services/service-container.ts", "../../../src/errors.ts", "../../../src/services/local-function-execution.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Effect, Layer, type Schema } from 'effect';\n\nimport { type Filter, type Live, Obj, type Query, type Ref, type Relation, type Type } from '@dxos/echo';\nimport type { EchoDatabase, FlushOptions, OneShotQueryResult, QueryResult } from '@dxos/echo-db';\nimport { BaseError } from '@dxos/errors';\nimport { invariant } from '@dxos/invariant';\nimport type { DXN } from '@dxos/keys';\n\nexport class DatabaseService extends Context.Tag('@dxos/functions/DatabaseService')<\n DatabaseService,\n {\n readonly db: EchoDatabase;\n }\n>() {\n static notAvailable = Layer.succeed(DatabaseService, {\n get db(): EchoDatabase {\n throw new Error('Database not available');\n },\n });\n\n static make = (db: EchoDatabase): Context.Tag.Service<DatabaseService> => {\n return {\n get db() {\n return db;\n },\n };\n };\n\n static layer = (db: EchoDatabase): Layer.Layer<DatabaseService> => {\n return Layer.succeed(DatabaseService, DatabaseService.make(db));\n };\n\n /**\n * Resolves an object by its DXN.\n */\n static resolve: {\n // No type check.\n (dxn: DXN): Effect.Effect<Obj.Any | Relation.Any, never, DatabaseService>;\n // Check matches schema.\n <S extends Type.Obj.Any | Type.Relation.Any>(\n dxn: DXN,\n schema: S,\n ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService>;\n } = (<S extends Type.Obj.Any | Type.Relation.Any>(\n dxn: DXN,\n schema?: S,\n ): Effect.Effect<Schema.Schema.Type<S>, ObjectNotFoundError, DatabaseService> =>\n Effect.gen(function* () {\n const { db } = yield* DatabaseService;\n const object = yield* Effect.promise(() =>\n db.graph\n .createRefResolver({\n context: {\n space: db.spaceId,\n },\n })\n .resolve(dxn),\n );\n\n if (!object) {\n return yield* Effect.fail(new ObjectNotFoundError({ dxn }));\n }\n invariant(!schema || Obj.instanceOf(schema, object), 'Object type mismatch.');\n return object as any;\n })) as any;\n\n /**\n * Loads an object reference.\n */\n static load: <T>(ref: Ref.Ref<T>) => Effect.Effect<T, never, never> = Effect.fn(function* (ref) {\n return yield* Effect.promise(() => ref.load());\n });\n\n /**\n * Creates a `QueryResult` object that can be subscribed to.\n */\n static query: {\n <Q extends Query.Any>(query: Q): Effect.Effect<QueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;\n <F extends Filter.Any>(filter: F): Effect.Effect<QueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;\n } = (queryOrFilter: Query.Any | Filter.Any) =>\n DatabaseService.pipe(\n Effect.map(({ db }) => db.query(queryOrFilter as any)),\n Effect.withSpan('DatabaseService.query'),\n );\n\n /**\n * Executes the query once and returns the results.\n */\n static runQuery: {\n <Q extends Query.Any>(query: Q): Effect.Effect<OneShotQueryResult<Live<Query.Type<Q>>>, never, DatabaseService>;\n <F extends Filter.Any>(filter: F): Effect.Effect<OneShotQueryResult<Live<Filter.Type<F>>>, never, DatabaseService>;\n } = (queryOrFilter: Query.Any | Filter.Any) =>\n DatabaseService.query(queryOrFilter as any).pipe(\n Effect.flatMap((queryResult) => Effect.promise(() => queryResult.run())),\n );\n\n /**\n * Adds an object to the database.\n */\n static add = <T extends Obj.Any | Relation.Any>(obj: T): Effect.Effect<T, never, DatabaseService> =>\n DatabaseService.pipe(Effect.map(({ db }) => db.add(obj)));\n\n static flush = (opts?: FlushOptions) =>\n DatabaseService.pipe(Effect.flatMap(({ db }) => Effect.promise(() => db.flush(opts))));\n}\n\n// TODO(burdon): Move to echo/errors.\nclass ObjectNotFoundError extends BaseError.extend('OBJECT_NOT_FOUND') {\n constructor(context?: Record<string, unknown>) {\n super('Object not found', { context });\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Effect, Layer } from 'effect';\n\nimport type { Obj, Relation } from '@dxos/echo';\nimport type { Queue, QueueAPI, QueueFactory } from '@dxos/echo-db';\nimport type { DXN, QueueSubspaceTag } from '@dxos/keys';\n\n/**\n * Gives access to all queues.\n */\nexport class QueueService extends Context.Tag('@dxos/functions/QueueService')<\n QueueService,\n {\n /**\n * API to access the queues.\n */\n readonly queues: QueueAPI;\n\n /**\n * The queue that is used to store the context of the current research.\n * @deprecated Use `ContextQueueService` instead.\n */\n readonly queue: Queue | undefined;\n }\n>() {\n static notAvailable = Layer.succeed(QueueService, {\n queues: {\n get(_dxn) {\n throw new Error('Queues not available');\n },\n create() {\n throw new Error('Queues not available');\n },\n },\n queue: undefined,\n });\n\n static make = (queues: QueueFactory, queue?: Queue): Context.Tag.Service<QueueService> => {\n return {\n queues,\n queue,\n };\n };\n\n static layer = (queues: QueueFactory, queue?: Queue): Layer.Layer<QueueService> =>\n Layer.succeed(QueueService, QueueService.make(queues, queue));\n\n /**\n * Gets a queue by its DXN.\n */\n static getQueue = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(\n dxn: DXN,\n ): Effect.Effect<Queue<T>, never, QueueService> => QueueService.pipe(Effect.map(({ queues }) => queues.get<T>(dxn)));\n\n /**\n * Creates a new queue.\n */\n static createQueue = <T extends Obj.Any | Relation.Any = Obj.Any | Relation.Any>(options?: {\n subspaceTag?: QueueSubspaceTag;\n }): Effect.Effect<Queue<T>, never, QueueService> =>\n QueueService.pipe(Effect.map(({ queues }) => queues.create<T>(options)));\n}\n\n/**\n * Gives access to a specific queue passed as a context.\n */\nexport class ContextQueueService extends Context.Tag('@dxos/functions/ContextQueueService')<\n ContextQueueService,\n {\n readonly queue: Queue;\n }\n>() {\n static layer = (queue: Queue) => Layer.succeed(ContextQueueService, { queue });\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Effect, Layer } from 'effect';\n\nimport { Query } from '@dxos/echo';\nimport { DataType } from '@dxos/schema';\n\nimport { DatabaseService } from './database';\n\ntype CredentialQuery = {\n service?: string;\n};\n\n// TODO(dmaretskyi): Unify with other apis.\n// packages/sdk/schema/src/common/access-token.ts\nexport type ServiceCredential = {\n service: string;\n\n // TODO(dmaretskyi): Build out.\n apiKey?: string;\n};\n\nexport class CredentialsService extends Context.Tag('@dxos/functions/CredentialsService')<\n CredentialsService,\n {\n /**\n * Query all.\n */\n queryCredentials: (query: CredentialQuery) => Promise<ServiceCredential[]>;\n\n /**\n * Get a single credential.\n * @throws {Error} If no credential is found.\n */\n getCredential: (query: CredentialQuery) => Promise<ServiceCredential>;\n }\n>() {\n static getCredential = (query: CredentialQuery): Effect.Effect<ServiceCredential, never, CredentialsService> =>\n Effect.gen(function* () {\n const credentials = yield* CredentialsService;\n return yield* Effect.promise(() => credentials.getCredential(query));\n });\n\n static configuredLayer = (credentials: ServiceCredential[]) =>\n Layer.succeed(CredentialsService, new ConfiguredCredentialsService(credentials));\n\n static layerFromDatabase = () =>\n Layer.effect(\n CredentialsService,\n Effect.gen(function* () {\n const dbService = yield* DatabaseService;\n const queryCredentials = async (query: CredentialQuery): Promise<ServiceCredential[]> => {\n const { objects: accessTokens } = await dbService.db.query(Query.type(DataType.AccessToken)).run();\n return accessTokens\n .filter((accessToken) => accessToken.source === query.service)\n .map((accessToken) => ({\n service: accessToken.source,\n apiKey: accessToken.token,\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 return credentials[0];\n },\n queryCredentials: async (query) => {\n return queryCredentials(query);\n },\n };\n }),\n );\n}\n\nexport class ConfiguredCredentialsService implements Context.Tag.Service<CredentialsService> {\n constructor(private readonly credentials: ServiceCredential[] = []) {}\n\n addCredentials(credentials: ServiceCredential[]): ConfiguredCredentialsService {\n this.credentials.push(...credentials);\n return this;\n }\n\n async queryCredentials(query: CredentialQuery): Promise<ServiceCredential[]> {\n return this.credentials.filter((credential) => credential.service === query.service);\n }\n\n async getCredential(query: CredentialQuery): Promise<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 return credential;\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Effect, Layer } from 'effect';\n\nimport { AgentStatus } from '@dxos/ai';\nimport { Obj } from '@dxos/echo';\nimport type { AnyEchoObject } from '@dxos/echo-schema';\n\n/**\n * Provides a way for compute primitives (functions, workflows, tools)\n * to emit an execution trace as a series of structured ECHO objects.\n */\nexport class TracingService extends Context.Tag('@dxos/functions/TracingService')<\n TracingService,\n {\n /**\n * Write an event to the tracing queue.\n * @param event - The event to write. Must be an a typed object.\n */\n write(event: AnyEchoObject): void;\n }\n>() {\n static noop: Context.Tag.Service<TracingService> = { write: () => {} };\n\n static layerNoop = Layer.succeed(TracingService, TracingService.noop);\n\n static console: Context.Tag.Service<TracingService> = {\n write: (event) => {\n // eslint-disable-next-line no-console\n console.log(event);\n },\n };\n\n /**\n * Emit the current human-readable execution status.\n */\n static emitStatus: (data: Obj.MakeProps<typeof AgentStatus>) => Effect.Effect<void, never, TracingService> =\n Effect.fnUntraced(function* (data) {\n const tracing = yield* TracingService;\n tracing.write(Obj.make(AgentStatus, data));\n });\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Effect, Layer, Schema } from 'effect';\n\nimport { Obj, Type } from '@dxos/echo';\nimport { invariant } from '@dxos/invariant';\nimport { LogLevel, log } from '@dxos/log';\n\nimport { TracingService } from './tracing';\n\nexport const ComputeEventPayload = Schema.Union(\n Schema.Struct({\n type: Schema.Literal('begin-compute'),\n nodeId: Schema.String,\n inputs: Schema.Record({ key: Schema.String, value: Schema.Any }),\n }),\n Schema.Struct({\n type: Schema.Literal('end-compute'),\n nodeId: Schema.String,\n outputs: Schema.Record({ key: Schema.String, value: Schema.Any }),\n }),\n Schema.Struct({\n type: Schema.Literal('compute-input'),\n nodeId: Schema.String,\n property: Schema.String,\n value: Schema.Any,\n }),\n Schema.Struct({\n type: Schema.Literal('compute-output'),\n nodeId: Schema.String,\n property: Schema.String,\n value: Schema.Any,\n }),\n Schema.Struct({\n type: Schema.Literal('custom'),\n nodeId: Schema.String,\n event: Schema.Any,\n }),\n);\nexport type ComputeEventPayload = Schema.Schema.Type<typeof ComputeEventPayload>;\n\nexport const ComputeEvent = Schema.Struct({\n payload: ComputeEventPayload,\n}).pipe(Type.Obj({ typename: 'dxos.org/type/ComputeEvent', version: '0.1.0' }));\n\n/**\n * Logs event for the compute workflows.\n */\nexport class ComputeEventLogger extends Context.Tag('@dxos/functions/ComputeEventLogger')<\n ComputeEventLogger,\n { readonly log: (event: ComputeEventPayload) => void; readonly nodeId: string | undefined }\n>() {\n static noop: Context.Tag.Service<ComputeEventLogger> = {\n log: () => {},\n nodeId: undefined,\n };\n\n /**\n * Implements ComputeEventLogger using TracingService.\n */\n static layerFromTracing = Layer.effect(\n ComputeEventLogger,\n Effect.gen(function* () {\n const tracing = yield* TracingService;\n return {\n log: (event: ComputeEventPayload) => {\n tracing.write(Obj.make(ComputeEvent, { payload: event }));\n },\n nodeId: undefined,\n };\n }),\n );\n}\n\nexport const logCustomEvent = (data: any) =>\n Effect.gen(function* () {\n const logger = yield* ComputeEventLogger;\n if (!logger.nodeId) {\n throw new Error('logCustomEvent must be called within a node compute function');\n }\n logger.log({\n type: 'custom',\n nodeId: logger.nodeId,\n event: data,\n });\n });\n\nexport const createDefectLogger = <A, E, R>(): ((self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>) =>\n Effect.catchAll((error) =>\n Effect.gen(function* () {\n log.error('unhandled effect error', { error });\n throw error;\n }),\n );\n\nexport const createEventLogger = (\n level: LogLevel,\n message: string = 'event',\n): Context.Tag.Service<ComputeEventLogger> => {\n const logFunction = (\n {\n [LogLevel.WARN]: log.warn,\n [LogLevel.VERBOSE]: log.verbose,\n [LogLevel.DEBUG]: log.debug,\n [LogLevel.INFO]: log.info,\n [LogLevel.ERROR]: log.error,\n } as any\n )[level];\n invariant(logFunction);\n return {\n log: (event: ComputeEventPayload) => {\n logFunction(message, event);\n },\n nodeId: undefined,\n };\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Layer } from 'effect';\n\nimport type { SpaceId } from '@dxos/keys';\n\n/**\n * Allows calling into other functions.\n */\nexport class RemoteFunctionExecutionService extends Context.Tag('@dxos/functions/RemoteFunctionExecutionService')<\n RemoteFunctionExecutionService,\n {\n callFunction(deployedFunctionId: string, input: any, spaceId?: SpaceId): Promise<any>;\n }\n>() {\n static fromClient(baseUrl: string, spaceId: SpaceId): Context.Tag.Service<RemoteFunctionExecutionService> {\n return {\n callFunction: async (deployedFunctionId: string, input: any) => {\n const url = getInvocationUrl(deployedFunctionId, baseUrl, { spaceId });\n const result = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n });\n if (result.status >= 300 || result.status < 200) {\n throw new Error('Failed to invoke function', { cause: new Error(`HTTP error: ${await result.text()}`) });\n }\n return await result.json();\n },\n };\n }\n\n static mock = (): Context.Tag.Service<RemoteFunctionExecutionService> => {\n return {\n callFunction: async (deployedFunctionId: string, input: any) => {\n return input;\n },\n };\n };\n\n static mockLayer = Layer.succeed(RemoteFunctionExecutionService, RemoteFunctionExecutionService.mock());\n}\n\n// TODO(dmaretskyi): Reconcile with `getInvocationUrl` in `@dxos/functions/edge`.\nconst getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = isSecure(url.protocol) ? 'https' : 'http';\n return url.toString();\n};\n\nconst isSecure = (protocol: string) => {\n return protocol === 'https:' || protocol === 'wss:';\n};\n\ntype InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Context, Layer } from 'effect';\n\nimport { AiService } from '@dxos/ai';\nimport { entries } from '@dxos/util';\n\nimport { ConfiguredCredentialsService, CredentialsService } from './credentials';\nimport { DatabaseService } from './database';\nimport { ComputeEventLogger } from './event-logger';\nimport { QueueService } from './queues';\nimport { RemoteFunctionExecutionService } from './remote-function-execution-service';\nimport { TracingService } from './tracing';\n\n// TODO(dmaretskyi): Refactor this module to only rely on tags and not the human-assigned names.\n\n/**\n * List of all services.\n */\nconst SERVICES = {\n ai: AiService.AiService,\n credentials: CredentialsService,\n database: DatabaseService,\n eventLogger: ComputeEventLogger,\n functionCallService: RemoteFunctionExecutionService,\n queues: QueueService,\n tracing: TracingService,\n} as const satisfies Record<string, Context.TagClass<any, string, any>>;\n\n/**\n * Mapping of service names to their tags.\n */\nexport type ServiceTagRecord = {\n [K in keyof typeof SERVICES]: (typeof SERVICES)[K] extends { new (_: never): infer T } ? T : never;\n};\n\n/**\n * Mapping of service names to their runtime types.\n */\nexport type ServiceRecord = {\n [K in keyof ServiceTagRecord]: Context.Tag.Service<ServiceTagRecord[K]>;\n};\n\n/**\n * Union of all services tags.\n */\nexport type Services = ServiceTagRecord[keyof ServiceTagRecord];\n\nconst SERVICE_MAPPING: Record<string, keyof ServiceRecord> = Object.fromEntries(\n entries(SERVICES).map(([name, tag]) => [tag.key, name]),\n);\n\nexport const SERVICE_TAGS: Context.Tag<any, any>[] = Object.values(SERVICES);\n\nconst DEFAULT_SERVICES: Partial<ServiceRecord> = {\n tracing: TracingService.noop,\n};\n\n/**\n * @deprecated\n */\nexport class ServiceContainer {\n private _services: Partial<ServiceRecord> = { ...DEFAULT_SERVICES };\n\n /**\n * Set services.\n * @param services - Services to set.\n * @returns The container instance.\n */\n setServices(services: Partial<ServiceRecord>): this {\n this._services = { ...this._services, ...services };\n return this;\n }\n\n getService<Id, T>(tag: Context.Tag<Id, T>): T {\n const serviceKey = SERVICE_MAPPING[tag.key];\n const service = serviceKey != null ? this._services[serviceKey] : undefined;\n if (!service) {\n throw new Error(`Service not available: ${tag.key}`);\n }\n\n return service as T;\n }\n\n clone(): ServiceContainer {\n return new ServiceContainer().setServices({ ...this._services });\n }\n\n // TODO(dmaretskyi): `getService` is designed to error at runtime if the service is not available, but Layer forces us to provide all services and makes stubs for the ones that are not available.\n createLayer(): Layer.Layer<Services> {\n const ai =\n this._services.ai != null ? Layer.succeed(AiService.AiService, this._services.ai) : AiService.notAvailable;\n const credentials = Layer.succeed(\n CredentialsService,\n this._services.credentials ?? new ConfiguredCredentialsService(),\n );\n const database =\n this._services.database != null\n ? Layer.succeed(DatabaseService, this._services.database)\n : DatabaseService.notAvailable;\n const queues =\n this._services.queues != null ? Layer.succeed(QueueService, this._services.queues) : QueueService.notAvailable;\n const tracing = Layer.succeed(TracingService, this._services.tracing ?? TracingService.noop);\n const eventLogger = Layer.succeed(ComputeEventLogger, this._services.eventLogger ?? ComputeEventLogger.noop);\n const functionCallService = Layer.succeed(\n RemoteFunctionExecutionService,\n this._services.functionCallService ?? RemoteFunctionExecutionService.mock(),\n );\n\n return Layer.mergeAll(ai, credentials, database, queues, tracing, eventLogger, functionCallService);\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\nexport class ServiceNotAvailableError extends BaseError.extend('SERVICE_NOT_AVAILABLE') {\n constructor(serviceName: string) {\n super(`Service not available: ${serviceName}`);\n }\n}\n\nexport class FunctionError extends BaseError.extend('FUNCTION_ERROR') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Context, Effect, Layer, Schema } from 'effect';\n\nimport { todo } from '@dxos/debug';\n\nimport { FunctionError } from '../errors';\nimport type { FunctionContext, FunctionDefinition } from '../handler';\n\nimport type { Services } from './service-container';\n\nexport class LocalFunctionExecutionService extends Context.Tag('@dxos/functions/LocalFunctionExecutionService')<\n LocalFunctionExecutionService,\n {\n // TODO(dmaretskyi): This should take function id instead of the definition object.\n // TODO(dmaretskyi): Services should be satisfied from environment rather then bubbled up.\n invokeFunction(fnDef: FunctionDefinition<any, any>, input: unknown): Effect.Effect<unknown, never, Services>;\n }\n>() {\n static layer = Layer.succeed(LocalFunctionExecutionService, {\n invokeFunction: (fnDef, input) => invokeFunction(fnDef, input),\n });\n\n static invokeFunction: <F extends FunctionDefinition.Any>(\n fnDef: F,\n input: FunctionDefinition.Input<F>,\n ) => Effect.Effect<FunctionDefinition.Output<F>, never, Services | LocalFunctionExecutionService> =\n Effect.serviceFunctionEffect(LocalFunctionExecutionService, (_) => _.invokeFunction as any);\n}\n\nconst invokeFunction = (fnDef: FunctionDefinition<any, any>, input: any): Effect.Effect<unknown, never, Services> =>\n Effect.gen(function* () {\n // Assert input matches schema\n const assertInput = fnDef.inputSchema.pipe(Schema.asserts);\n (assertInput as any)(input);\n\n const context: FunctionContext = {\n space: undefined,\n getService: () => todo(),\n getSpace: async (_spaceId: any) => {\n throw new Error('Not available. Use the database service instead.');\n },\n };\n\n // TODO(dmaretskyi): This should be delegated to a function invoker service.\n const data = yield* Effect.gen(function* () {\n const result = fnDef.handler({ context, data: input });\n if (Effect.isEffect(result)) {\n return yield* (result as Effect.Effect<unknown, unknown, Services>).pipe(Effect.orDie);\n } else if (\n typeof result === 'object' &&\n result !== null &&\n 'then' in result &&\n typeof result.then === 'function'\n ) {\n return yield* Effect.promise(() => result);\n } else {\n return result;\n }\n }).pipe(\n Effect.orDie,\n Effect.catchAllDefect((defect) =>\n Effect.die(new FunctionError('Error running function', { context: { name: fnDef.name }, cause: defect })),\n ),\n );\n\n // Assert output matches schema\n const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);\n (assertOutput as any)(data);\n\n return data;\n }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: fnDef.name } }));\n"],
5
+ "mappings": ";AAIA,SAASA,SAASC,QAAQC,aAA0B;AAEpD,SAAiCC,WAA2D;AAE5F,SAASC,iBAAiB;AAC1B,SAASC,iBAAiB;;AAGnB,IAAMC,kBAAN,MAAMA,yBAAwBN,QAAQO,IAAI,iCAAA,EAAA,EAAA;EAM/C,OAAOC,eAAeN,MAAMO,QAAQH,kBAAiB;IACnD,IAAII,KAAmB;AACrB,YAAM,IAAIC,MAAM,wBAAA;IAClB;EACF,CAAA;EAEA,OAAOC,OAAO,CAACF,OAAAA;AACb,WAAO;MACL,IAAIA,KAAK;AACP,eAAOA;MACT;IACF;EACF;EAEA,OAAOG,QAAQ,CAACH,OAAAA;AACd,WAAOR,MAAMO,QAAQH,kBAAiBA,iBAAgBM,KAAKF,EAAAA,CAAAA;EAC7D;;;;EAKA,OAAOI,UAQF,CACHC,KACAC,WAEAf,OAAOgB,IAAI,aAAA;AACT,UAAM,EAAEP,GAAE,IAAK,OAAOJ;AACtB,UAAMY,SAAS,OAAOjB,OAAOkB,QAAQ,MACnCT,GAAGU,MACAC,kBAAkB;MACjBC,SAAS;QACPC,OAAOb,GAAGc;MACZ;IACF,CAAA,EACCV,QAAQC,GAAAA,CAAAA;AAGb,QAAI,CAACG,QAAQ;AACX,aAAO,OAAOjB,OAAOwB,KAAK,IAAIC,oBAAoB;QAAEX;MAAI,CAAA,CAAA;IAC1D;AACAV,cAAU,CAACW,UAAUb,IAAIwB,WAAWX,QAAQE,MAAAA,GAAS,yBAAA;;;;;;;;;AACrD,WAAOA;EACT,CAAA;;;;E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error", "make", "layer", "resolve", "dxn", "schema", "gen", "object", "promise", "graph", "createRefResolver", "context", "space", "spaceId", "fail", "ObjectNotFoundError", "instanceOf", "load", "fn", "ref", "query", "queryOrFilter", "pipe", "map", "withSpan", "runQuery", "flatMap", "queryResult", "run", "add", "obj", "flush", "opts", "extend", "Context", "Effect", "Layer", "QueueService", "Context", "Tag", "notAvailable", "Layer", "succeed", "queues", "get", "_dxn", "Error", "create", "queue", "undefined", "make", "layer", "getQueue", "dxn", "pipe", "Effect", "map", "createQueue", "options", "ContextQueueService", "Context", "Effect", "Layer", "Query", "DataType", "CredentialsService", "Context", "Tag", "getCredential", "query", "Effect", "gen", "credentials", "promise", "configuredLayer", "Layer", "succeed", "ConfiguredCredentialsService", "layerFromDatabase", "effect", "dbService", "DatabaseService", "queryCredentials", "objects", "accessTokens", "db", "Query", "type", "DataType", "AccessToken", "run", "filter", "accessToken", "source", "service", "map", "apiKey", "token", "length", "Error", "addCredentials", "push", "credential", "find", "Context", "Effect", "Layer", "AgentStatus", "Obj", "TracingService", "Context", "Tag", "noop", "write", "layerNoop", "Layer", "succeed", "console", "event", "log", "emitStatus", "Effect", "fnUntraced", "data", "tracing", "Obj", "make", "AgentStatus", "Context", "Effect", "Layer", "Schema", "Obj", "Type", "invariant", "LogLevel", "log", "ComputeEventPayload", "Schema", "Union", "Struct", "type", "Literal", "nodeId", "String", "inputs", "Record", "key", "value", "Any", "outputs", "property", "event", "ComputeEvent", "payload", "pipe", "Type", "Obj", "typename", "version", "ComputeEventLogger", "Context", "Tag", "noop", "log", "undefined", "layerFromTracing", "Layer", "effect", "Effect", "gen", "tracing", "TracingService", "write", "make", "logCustomEvent", "data", "logger", "Error", "createDefectLogger", "catchAll", "error", "createEventLogger", "level", "message", "logFunction", "LogLevel", "WARN", "warn", "VERBOSE", "verbose", "DEBUG", "debug", "INFO", "info", "ERROR", "invariant", "Context", "Layer", "RemoteFunctionExecutionService", "Context", "Tag", "fromClient", "baseUrl", "spaceId", "callFunction", "deployedFunctionId", "input", "url", "getInvocationUrl", "result", "fetch", "method", "headers", "body", "JSON", "stringify", "status", "Error", "cause", "text", "json", "mock", "mockLayer", "Layer", "succeed", "functionUrl", "edgeUrl", "options", "URL", "relativeUrl", "replace", "toString", "searchParams", "set", "subjectId", "protocol", "isSecure", "Layer", "AiService", "entries", "SERVICES", "ai", "AiService", "credentials", "CredentialsService", "database", "DatabaseService", "eventLogger", "ComputeEventLogger", "functionCallService", "RemoteFunctionExecutionService", "queues", "QueueService", "tracing", "TracingService", "SERVICE_MAPPING", "Object", "fromEntries", "entries", "map", "name", "tag", "key", "SERVICE_TAGS", "values", "DEFAULT_SERVICES", "noop", "ServiceContainer", "_services", "setServices", "services", "getService", "serviceKey", "service", "undefined", "Error", "clone", "createLayer", "Layer", "succeed", "notAvailable", "ConfiguredCredentialsService", "mock", "mergeAll", "BaseError", "ServiceNotAvailableError", "BaseError", "extend", "serviceName", "FunctionError", "Context", "Effect", "Layer", "Schema", "todo", "LocalFunctionExecutionService", "Context", "Tag", "layer", "Layer", "succeed", "invokeFunction", "fnDef", "input", "Effect", "serviceFunctionEffect", "_", "gen", "assertInput", "inputSchema", "pipe", "Schema", "asserts", "context", "space", "undefined", "getService", "todo", "getSpace", "_spaceId", "Error", "data", "result", "handler", "isEffect", "orDie", "then", "promise", "catchAllDefect", "defect", "die", "FunctionError", "name", "cause", "assertOutput", "outputSchema", "withSpan", "attributes"]
7
+ }
@@ -1,9 +1,9 @@
1
- // packages/core/functions/src/edge/functions.ts
1
+ // src/edge/functions.ts
2
2
  import { createEdgeIdentity } from "@dxos/client/edge";
3
3
  import { EdgeHttpClient } from "@dxos/edge-client";
4
4
  import { invariant } from "@dxos/invariant";
5
5
  import { log } from "@dxos/log";
6
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/edge/functions.ts";
6
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/edge/functions.ts";
7
7
  var uploadWorkerFunction = async ({ client, version, source, name, functionId, ownerPublicKey }) => {
8
8
  const edgeUrl = client.config.values.runtime?.services?.edge?.url;
9
9
  invariant(edgeUrl, "Edge is not configured.", {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/edge/functions.ts"],
4
- "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { type Client } from '@dxos/client';\nimport { createEdgeIdentity } from '@dxos/client/edge';\nimport { EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport type { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type UploadFunctionResponseBody } from '@dxos/protocols';\n\nexport type UploadWorkerArgs = {\n client: Client;\n source: string;\n version: string;\n name?: string;\n functionId?: string;\n ownerPublicKey: PublicKey;\n};\n\nexport const uploadWorkerFunction = async ({\n client,\n version,\n source,\n name,\n functionId,\n ownerPublicKey,\n}: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {\n const edgeUrl = client.config.values.runtime?.services?.edge?.url;\n invariant(edgeUrl, 'Edge is not configured.');\n const edgeClient = new EdgeHttpClient(edgeUrl);\n const edgeIdentity = createEdgeIdentity(client);\n edgeClient.setIdentity(edgeIdentity);\n const response = await edgeClient.uploadFunction(\n { functionId },\n { name, version, script: source, ownerPublicKey: ownerPublicKey.toHex() },\n );\n\n // TODO(burdon): Edge service log.\n log.info('Uploaded', {\n identityKey: edgeIdentity.identityKey,\n functionId,\n name,\n source: source.length,\n response,\n });\n\n return response;\n};\n\nexport const incrementSemverPatch = (version: string): string => {\n const [major, minor, patch] = version.split('.');\n const patchNum = Number(patch);\n invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);\n return [major, minor, String(patchNum + 1)].join('.');\n};\n\n// TODO(burdon): Factor out.\nexport const publicKeyToDid = (key: PublicKey): DID => {\n return `did:key:${key.toHex()}`;\n};\n"],
4
+ "sourcesContent": ["//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DID } from 'iso-did/types';\n\nimport { type Client } from '@dxos/client';\nimport { createEdgeIdentity } from '@dxos/client/edge';\nimport { EdgeHttpClient } from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type UploadFunctionResponseBody } from '@dxos/protocols';\n\nexport type UploadWorkerArgs = {\n client: Client;\n source: string;\n version: string;\n name?: string;\n functionId?: string;\n ownerPublicKey: PublicKey;\n};\n\nexport const uploadWorkerFunction = async ({\n client,\n version,\n source,\n name,\n functionId,\n ownerPublicKey,\n}: UploadWorkerArgs): Promise<UploadFunctionResponseBody> => {\n const edgeUrl = client.config.values.runtime?.services?.edge?.url;\n invariant(edgeUrl, 'Edge is not configured.');\n const edgeClient = new EdgeHttpClient(edgeUrl);\n const edgeIdentity = createEdgeIdentity(client);\n edgeClient.setIdentity(edgeIdentity);\n const response = await edgeClient.uploadFunction(\n { functionId },\n { name, version, script: source, ownerPublicKey: ownerPublicKey.toHex() },\n );\n\n // TODO(burdon): Edge service log.\n log.info('Uploaded', {\n identityKey: edgeIdentity.identityKey,\n functionId,\n name,\n source: source.length,\n response,\n });\n\n return response;\n};\n\nexport const incrementSemverPatch = (version: string): string => {\n const [major, minor, patch] = version.split('.');\n const patchNum = Number(patch);\n invariant(!Number.isNaN(patchNum), `Unexpected function version format: ${version}`);\n return [major, minor, String(patchNum + 1)].join('.');\n};\n\n// TODO(burdon): Factor out.\nexport const publicKeyToDid = (key: PublicKey): DID => {\n return `did:key:${key.toHex()}`;\n};\n"],
5
5
  "mappings": ";AAOA,SAASA,0BAA0B;AACnC,SAASC,sBAAsB;AAC/B,SAASC,iBAAiB;AAE1B,SAASC,WAAW;;AAYb,IAAMC,uBAAuB,OAAO,EACzCC,QACAC,SACAC,QACAC,MACAC,YACAC,eAAc,MACG;AACjB,QAAMC,UAAUN,OAAOO,OAAOC,OAAOC,SAASC,UAAUC,MAAMC;AAC9Df,YAAUS,SAAS,2BAAA;;;;;;;;;AACnB,QAAMO,aAAa,IAAIjB,eAAeU,OAAAA;AACtC,QAAMQ,eAAenB,mBAAmBK,MAAAA;AACxCa,aAAWE,YAAYD,YAAAA;AACvB,QAAME,WAAW,MAAMH,WAAWI,eAChC;IAAEb;EAAW,GACb;IAAED;IAAMF;IAASiB,QAAQhB;IAAQG,gBAAgBA,eAAec,MAAK;EAAG,CAAA;AAI1ErB,MAAIsB,KAAK,YAAY;IACnBC,aAAaP,aAAaO;IAC1BjB;IACAD;IACAD,QAAQA,OAAOoB;IACfN;EACF,GAAA;;;;;;AAEA,SAAOA;AACT;AAEO,IAAMO,uBAAuB,CAACtB,YAAAA;AACnC,QAAM,CAACuB,OAAOC,OAAOC,KAAAA,IAASzB,QAAQ0B,MAAM,GAAA;AAC5C,QAAMC,WAAWC,OAAOH,KAAAA;AACxB7B,YAAU,CAACgC,OAAOC,MAAMF,QAAAA,GAAW,uCAAuC3B,OAAAA,IAAS;;;;;;;;;AACnF,SAAO;IAACuB;IAAOC;IAAOM,OAAOH,WAAW,CAAA;IAAII,KAAK,GAAA;AACnD;AAGO,IAAMC,iBAAiB,CAACC,QAAAA;AAC7B,SAAO,WAAWA,IAAIf,MAAK,CAAA;AAC7B;",
6
6
  "names": ["createEdgeIdentity", "EdgeHttpClient", "invariant", "log", "uploadWorkerFunction", "client", "version", "source", "name", "functionId", "ownerPublicKey", "edgeUrl", "config", "values", "runtime", "services", "edge", "url", "edgeClient", "edgeIdentity", "setIdentity", "response", "uploadFunction", "script", "toHex", "info", "identityKey", "length", "incrementSemverPatch", "major", "minor", "patch", "split", "patchNum", "Number", "isNaN", "String", "join", "publicKeyToDid", "key"]
7
7
  }
@@ -1,37 +1,43 @@
1
1
  import {
2
- AiService,
2
+ ComputeEvent,
3
+ ComputeEventLogger,
4
+ ComputeEventPayload,
3
5
  ConfiguredCredentialsService,
6
+ ContextQueueService,
4
7
  CredentialsService,
5
8
  DatabaseService,
6
- EventLogger,
7
- FunctionCallService,
9
+ FunctionError,
10
+ LocalFunctionExecutionService,
8
11
  QueueService,
12
+ RemoteFunctionExecutionService,
9
13
  SERVICE_TAGS,
10
14
  ServiceContainer,
15
+ ServiceNotAvailableError,
11
16
  TracingService,
12
17
  createDefectLogger,
13
18
  createEventLogger,
14
19
  logCustomEvent
15
- } from "./chunk-WEFZUEL2.mjs";
20
+ } from "./chunk-M2OIFLGE.mjs";
16
21
 
17
- // packages/core/functions/src/handler.ts
22
+ // src/handler.ts
18
23
  import { Schema } from "effect";
19
- var defineFunction = (params) => {
20
- if (!Schema.isSchema(params.inputSchema)) {
24
+ var defineFunction = ({ name, description, inputSchema, outputSchema = Schema.Any, handler }) => {
25
+ if (!Schema.isSchema(inputSchema)) {
21
26
  throw new Error("Input schema must be a valid schema");
22
27
  }
23
- if (typeof params.handler !== "function") {
28
+ if (typeof handler !== "function") {
24
29
  throw new Error("Handler must be a function");
25
30
  }
26
31
  return {
27
- description: params.description,
28
- inputSchema: params.inputSchema,
29
- outputSchema: params.outputSchema ?? Schema.Any,
30
- handler: params.handler
32
+ name,
33
+ description,
34
+ inputSchema,
35
+ outputSchema,
36
+ handler
31
37
  };
32
38
  };
33
39
 
34
- // packages/core/functions/src/schema.ts
40
+ // src/schema.ts
35
41
  import { Schema as Schema2 } from "effect";
36
42
  import { Type } from "@dxos/echo";
37
43
  import { JsonSchemaType, LabelAnnotation, Ref } from "@dxos/echo-schema";
@@ -68,16 +74,16 @@ var FunctionType = Schema2.Struct({
68
74
  "name"
69
75
  ]));
70
76
 
71
- // packages/core/functions/src/trace.ts
77
+ // src/trace.ts
72
78
  import { Schema as Schema4 } from "effect";
73
79
  import { Type as Type2 } from "@dxos/echo";
74
80
  import { Queue } from "@dxos/echo-db";
75
81
  import { ObjectId } from "@dxos/echo-schema";
76
82
  import { log } from "@dxos/log";
77
83
 
78
- // packages/core/functions/src/types.ts
84
+ // src/types.ts
79
85
  import { Schema as Schema3, SchemaAST } from "effect";
80
- import { Expando, OptionsAnnotationId, TypedObject, Ref as Ref2, RawObject } from "@dxos/echo-schema";
86
+ import { Expando, OptionsAnnotationId, RawObject, Ref as Ref2, TypedObject } from "@dxos/echo-schema";
81
87
  import { DXN } from "@dxos/keys";
82
88
  var TriggerKind = /* @__PURE__ */ function(TriggerKind2) {
83
89
  TriggerKind2["Timer"] = "timer";
@@ -228,8 +234,8 @@ var FUNCTION_TYPES = [
228
234
  FunctionTrigger
229
235
  ];
230
236
 
231
- // packages/core/functions/src/trace.ts
232
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/functions/src/trace.ts";
237
+ // src/trace.ts
238
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/functions/src/trace.ts";
233
239
  var InvocationOutcome = /* @__PURE__ */ function(InvocationOutcome2) {
234
240
  InvocationOutcome2["SUCCESS"] = "success";
235
241
  InvocationOutcome2["FAILURE"] = "failure";
@@ -314,10 +320,8 @@ var TraceEvent = Schema4.Struct({
314
320
  // TODO(burdon): Need enum/numeric result (not string).
315
321
  outcome: Schema4.String,
316
322
  truncated: Schema4.Boolean,
317
- /**
318
- * Time when the event was persisted.
319
- */
320
- ingestionTimestampMs: Schema4.Number,
323
+ /** Time when the event was persisted. */
324
+ ingestionTimestamp: Schema4.Number,
321
325
  logs: Schema4.Array(TraceEventLog),
322
326
  exceptions: Schema4.Array(TraceEventException)
323
327
  }).pipe(Type2.Obj({
@@ -353,7 +357,7 @@ var createInvocationSpans = (items) => {
353
357
  invocationId
354
358
  }, {
355
359
  F: __dxlog_file,
356
- L: 160,
360
+ L: 158,
357
361
  S: void 0,
358
362
  C: (f, a) => f(...a)
359
363
  });
@@ -375,7 +379,7 @@ var createInvocationSpans = (items) => {
375
379
  return result;
376
380
  };
377
381
 
378
- // packages/core/functions/src/url.ts
382
+ // src/url.ts
379
383
  var FUNCTIONS_META_KEY = "dxos.org/service/function";
380
384
  var FUNCTIONS_PRESET_META_KEY = "dxos.org/service/function-preset";
381
385
  var isSecure = (protocol) => {
@@ -408,48 +412,55 @@ var getInvocationUrl = (functionUrl, edgeUrl, options = {}) => {
408
412
  return url.toString();
409
413
  };
410
414
 
411
- // packages/core/functions/src/executor/executor.ts
415
+ // src/executor/executor.ts
412
416
  import { Effect, Schema as Schema5 } from "effect";
417
+ import { runAndForwardErrors } from "@dxos/effect";
413
418
  var FunctionExecutor = class {
419
+ _services;
414
420
  constructor(_services) {
415
421
  this._services = _services;
416
422
  }
423
+ /**
424
+ *
425
+ */
417
426
  // TODO(dmaretskyi): Invocation context: queue, space, etc...
418
427
  async invoke(fnDef, input) {
419
428
  const assertInput = fnDef.inputSchema.pipe(Schema5.asserts);
420
429
  assertInput(input);
421
430
  const context = {
431
+ space: void 0,
422
432
  getService: this._services.getService.bind(this._services),
423
433
  getSpace: async (_spaceId) => {
424
434
  throw new Error("Not available. Use the database service instead.");
425
- },
426
- space: void 0,
427
- get ai() {
428
- throw new Error("Not available. Use the ai service instead.");
429
435
  }
430
436
  };
431
- const result = await fnDef.handler({
437
+ const result = fnDef.handler({
432
438
  context,
433
439
  data: input
434
440
  });
435
- const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
436
- assertOutput(result);
441
+ let data;
437
442
  if (Effect.isEffect(result)) {
438
- return Effect.runPromise(result);
443
+ data = await result.pipe(Effect.provide(this._services.createLayer()), runAndForwardErrors);
444
+ } else {
445
+ data = await result;
439
446
  }
440
- return result;
447
+ const assertOutput = fnDef.outputSchema?.pipe(Schema5.asserts);
448
+ assertOutput(data);
449
+ return data;
441
450
  }
442
451
  };
443
452
  export {
444
- AiService,
453
+ ComputeEvent,
454
+ ComputeEventLogger,
455
+ ComputeEventPayload,
445
456
  ConfiguredCredentialsService,
457
+ ContextQueueService,
446
458
  CredentialsService,
447
459
  DatabaseService,
448
460
  EmailTriggerOutput,
449
- EventLogger,
450
461
  FUNCTIONS_PRESET_META_KEY,
451
462
  FUNCTION_TYPES,
452
- FunctionCallService,
463
+ FunctionError,
453
464
  FunctionExecutor,
454
465
  FunctionManifestSchema,
455
466
  FunctionTrigger,
@@ -459,11 +470,14 @@ export {
459
470
  InvocationTraceEndEvent,
460
471
  InvocationTraceEventType,
461
472
  InvocationTraceStartEvent,
473
+ LocalFunctionExecutionService,
462
474
  QueueService,
463
475
  QueueTriggerOutput,
476
+ RemoteFunctionExecutionService,
464
477
  SERVICE_TAGS,
465
478
  ScriptType,
466
479
  ServiceContainer,
480
+ ServiceNotAvailableError,
467
481
  SubscriptionTriggerOutput,
468
482
  TimerTriggerOutput,
469
483
  TraceEvent,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/handler.ts", "../../../src/schema.ts", "../../../src/trace.ts", "../../../src/types.ts", "../../../src/url.ts", "../../../src/executor/executor.ts"],
4
- "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema, type Context, type Effect } from 'effect';\n\nimport { type AiServiceClient } from '@dxos/ai';\n// import { type Space } from '@dxos/client/echo';\nimport type { CoreDatabase, EchoDatabase } from '@dxos/echo-db';\nimport { type HasId } from '@dxos/echo-schema';\nimport { type SpaceId, type DXN } from '@dxos/keys';\nimport { type QueryResult } from '@dxos/protocols';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TOutput = any> = (params: {\n /**\n * Services and context available to the function.\n */\n context: FunctionContext;\n\n /**\n * Data passed as the input to the function.\n * Must match the function's input schema.\n * This will be the payload from the trigger or other data passed into the function in a workflow.\n */\n data: TData;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n /**\n * Resolves a service available to the function.\n * @throws if the service is not available.\n */\n getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;\n\n getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;\n\n /**\n * Space from which the function was invoked.\n */\n space: SpaceAPI | undefined;\n\n ai: AiServiceClient;\n}\n\nexport interface FunctionContextAi {\n // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.\n run(model: string, inputs: any, options?: any): Promise<any>;\n}\n\n//\n// API.\n//\n\n// TODO(dmaretskyi): Temporary API to get the queues working.\n// TODO(dmaretskyi): To be replaced with integrating queues into echo.\nexport interface QueuesAPI {\n queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;\n}\n\n/**\n * Space interface available to functions.\n */\nexport interface SpaceAPI {\n get id(): SpaceId;\n /**\n * @deprecated\n */\n get crud(): CoreDatabase;\n get db(): EchoDatabase;\n // TODO(dmaretskyi): Align with echo api --- queues.get(id).append(items);\n get queues(): QueuesAPI;\n}\n\n// TODO(wittjosiah): Queues are incompatible.\nconst __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {\n // const _: SpaceAPI = {} as Space;\n};\n\nexport type FunctionDefinition<T = {}, O = any> = {\n description?: string;\n inputSchema: Schema.Schema<T, any>;\n outputSchema?: Schema.Schema<O, any>;\n handler: FunctionHandler<T, O>;\n};\n\n// TODO(dmaretskyi): Bind input type to function handler.\nexport const defineFunction = <T, O>(params: FunctionDefinition<T, O>): FunctionDefinition<T, O> => {\n if (!Schema.isSchema(params.inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof params.handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n return {\n description: params.description,\n inputSchema: params.inputSchema,\n outputSchema: params.outputSchema ?? Schema.Any,\n handler: params.handler,\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Type } from '@dxos/echo';\nimport { JsonSchemaType, LabelAnnotation, Ref } from '@dxos/echo-schema';\nimport { DataType } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const ScriptType = Schema.Struct({\n name: Schema.optional(Schema.String),\n description: Schema.optional(Schema.String),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: Schema.optional(Schema.Boolean),\n source: Ref(DataType.Text),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/Script',\n version: '0.1.0',\n }),\n LabelAnnotation.set(['name']),\n);\n\nexport interface ScriptType extends Schema.Schema.Type<typeof ScriptType> {}\n\n/**\n * Function deployment.\n */\nexport const FunctionType = Schema.Struct({\n // TODO(burdon): Rename to id/uri?\n name: Schema.NonEmptyString,\n version: Schema.String,\n\n description: Schema.optional(Schema.String),\n\n // Reference to a source script if it exists within ECHO.\n // TODO(burdon): Don't ref ScriptType directly (core).\n source: Schema.optional(Ref(ScriptType)),\n\n inputSchema: Schema.optional(JsonSchemaType),\n outputSchema: Schema.optional(JsonSchemaType),\n\n // Local binding to a function name.\n binding: Schema.optional(Schema.String),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/Function',\n version: '0.1.0',\n }),\n LabelAnnotation.set(['name']),\n);\nexport interface FunctionType extends Schema.Schema.Type<typeof FunctionType> {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Type, type Ref } from '@dxos/echo';\nimport { Queue } from '@dxos/echo-db';\nimport { ObjectId } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\n\nimport { FunctionTrigger, type FunctionTriggerType } from './types';\n\nexport enum InvocationOutcome {\n SUCCESS = 'success',\n FAILURE = 'failure',\n PENDING = 'pending',\n}\n\n// TODO(burdon): Convert to extensible discriminated union of EDGE events.\nexport enum InvocationTraceEventType {\n START = 'start',\n END = 'end',\n}\n\nexport const TraceEventException = Schema.Struct({\n timestampMs: Schema.Number,\n message: Schema.String,\n name: Schema.String,\n stack: Schema.optional(Schema.String),\n});\nexport type TraceEventException = Schema.Schema.Type<typeof TraceEventException>;\n\nexport const InvocationTraceStartEvent = Schema.Struct({\n /**\n * Queue message id.\n */\n id: ObjectId,\n type: Schema.Literal(InvocationTraceEventType.START),\n /**\n * Invocation id, the same for invocation start and end events.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n timestampMs: Schema.Number,\n /**\n * Data passed to function / workflow as an argument.\n */\n // TODO(burdon): Input schema?\n input: Schema.Object,\n /**\n * Queue for function/workflow invocation events.\n */\n invocationTraceQueue: Type.Ref(Queue),\n /**\n * DXN of the invoked function/workflow.\n */\n invocationTarget: Type.Ref(Type.Expando),\n /**\n * Present for automatic invocations.\n */\n trigger: Schema.optional(Type.Ref(FunctionTrigger)),\n}).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));\n\nexport type InvocationTraceStartEvent = Schema.Schema.Type<typeof InvocationTraceStartEvent>;\n\nexport const InvocationTraceEndEvent = Schema.Struct({\n /**\n * Trace event id.\n */\n id: ObjectId,\n type: Schema.Literal(InvocationTraceEventType.END),\n /**\n * Invocation id, will be the same for invocation start and end.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n // TODO(burdon): Remove ms suffix.\n timestampMs: Schema.Number,\n outcome: Schema.Enums(InvocationOutcome),\n exception: Schema.optional(TraceEventException),\n}).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));\n\nexport type InvocationTraceEndEvent = Schema.Schema.Type<typeof InvocationTraceEndEvent>;\n\nexport type InvocationTraceEvent = InvocationTraceStartEvent | InvocationTraceEndEvent;\n\nexport const TraceEventLog = Schema.Struct({\n timestampMs: Schema.Number,\n level: Schema.String,\n message: Schema.String,\n context: Schema.optional(Schema.Object),\n});\n\nexport const TraceEvent = Schema.Struct({\n id: ObjectId,\n // TODO(burdon): Need enum/numeric result (not string).\n outcome: Schema.String,\n truncated: Schema.Boolean,\n /**\n * Time when the event was persisted.\n */\n ingestionTimestampMs: Schema.Number,\n logs: Schema.Array(TraceEventLog),\n exceptions: Schema.Array(TraceEventException),\n}).pipe(Type.Obj({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));\n\nexport type TraceEvent = Schema.Schema.Type<typeof TraceEvent>;\n\n/**\n * InvocationTrace event format.\n * This is the combined format of InvocationTraceStartEvent and InvocationTraceEndEvents for UI consumption.\n */\nexport type InvocationSpan = {\n id: string;\n timestampMs: number;\n outcome: InvocationOutcome;\n input: object;\n durationMs: number;\n invocationTraceQueue: Ref.Ref<Queue>;\n invocationTarget: Ref.Ref<Type.Expando>;\n trigger?: Ref.Ref<FunctionTriggerType>;\n exception?: TraceEventException;\n};\n\nexport const createInvocationSpans = (items?: InvocationTraceEvent[]): InvocationSpan[] => {\n if (!items) {\n return [];\n }\n\n const eventsByInvocationId = new Map<string, { start?: InvocationTraceStartEvent; end?: InvocationTraceEndEvent }>();\n for (const event of items) {\n if (!('invocationId' in event)) {\n // Skip legacy format entries.\n continue;\n }\n\n const invocationId = event.invocationId;\n const entry = eventsByInvocationId.get(invocationId) || { start: undefined, end: undefined };\n if (event.type === InvocationTraceEventType.START) {\n entry.start = event as InvocationTraceStartEvent;\n } else if (event.type === InvocationTraceEventType.END) {\n entry.end = event as InvocationTraceEndEvent;\n }\n\n eventsByInvocationId.set(invocationId, entry);\n }\n\n const now = Date.now();\n const result: InvocationSpan[] = [];\n\n // Create spans for each invocation\n for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {\n if (!start) {\n // No start event, can't create a meaningful span\n log.warn('found end event without matching start', { invocationId });\n continue;\n }\n\n const isInProgress = end === undefined;\n\n result.push({\n id: invocationId,\n timestampMs: start.timestampMs,\n durationMs: isInProgress ? now - start.timestampMs : end!.timestampMs - start.timestampMs,\n outcome: end?.outcome ?? InvocationOutcome.PENDING,\n exception: end?.exception,\n input: start.input,\n invocationTraceQueue: start.invocationTraceQueue,\n invocationTarget: start.invocationTarget,\n trigger: start.trigger,\n });\n }\n\n return result;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema, SchemaAST } from 'effect';\n\nimport { Expando, OptionsAnnotationId, TypedObject, Ref, RawObject } from '@dxos/echo-schema';\nimport { DXN } from '@dxos/keys';\n\nimport { FunctionType } from './schema';\n\n/**\n * Type discriminator for TriggerType.\n * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport enum TriggerKind {\n Timer = 'timer',\n Webhook = 'webhook',\n Subscription = 'subscription',\n Email = 'email',\n Queue = 'queue',\n}\n\nconst kindLiteralAnnotations = { title: 'Kind' };\n\n/**\n * Cron timer.\n */\nconst TimerTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Timer).annotations(kindLiteralAnnotations),\n cron: Schema.String.annotations({\n title: 'Cron',\n [SchemaAST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n}).pipe(Schema.mutable);\nexport type TimerTrigger = Schema.Schema.Type<typeof TimerTriggerSchema>;\n\nconst EmailTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Email).annotations(kindLiteralAnnotations),\n}).pipe(Schema.mutable);\nexport type EmailTrigger = Schema.Schema.Type<typeof EmailTriggerSchema>;\n\nconst QueueTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Queue).annotations(kindLiteralAnnotations),\n queue: DXN.Schema,\n}).pipe(Schema.mutable);\nexport type QueueTrigger = Schema.Schema.Type<typeof QueueTriggerSchema>;\n\n/**\n * Webhook.\n */\nconst WebhookTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Webhook).annotations(kindLiteralAnnotations),\n method: Schema.optional(\n Schema.String.annotations({\n title: 'Method',\n [OptionsAnnotationId]: ['GET', 'POST'],\n }),\n ),\n port: Schema.optional(\n Schema.Number.annotations({\n title: 'Port',\n }),\n ),\n}).pipe(Schema.mutable);\nexport type WebhookTrigger = Schema.Schema.Type<typeof WebhookTriggerSchema>;\n\n// TODO(burdon): Use ECHO definition (from https://github.com/dxos/dxos/pull/8233).\nconst QuerySchema = Schema.Struct({\n type: Schema.optional(Schema.String.annotations({ title: 'Type' })),\n props: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Any })),\n}).annotations({ title: 'Query' });\n\n/**\n * Subscription.\n */\nconst SubscriptionTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Subscription).annotations(kindLiteralAnnotations),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: QuerySchema,\n options: Schema.optional(\n Schema.Struct({\n // Watch changes to object (not just creation).\n deep: Schema.optional(Schema.Boolean.annotations({ title: 'Nested' })),\n // Debounce changes (delay in ms).\n delay: Schema.optional(Schema.Number.annotations({ title: 'Delay' })),\n }).annotations({ title: 'Options' }),\n ),\n}).pipe(Schema.mutable);\nexport type SubscriptionTrigger = Schema.Schema.Type<typeof SubscriptionTriggerSchema>;\n\n/**\n * Trigger schema (discriminated union).\n */\nexport const TriggerSchema = Schema.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n SubscriptionTriggerSchema,\n EmailTriggerSchema,\n QueueTriggerSchema,\n).annotations({\n title: 'Trigger',\n});\nexport type TriggerType = Schema.Schema.Type<typeof TriggerSchema>;\n\nexport type EventType =\n | EmailTriggerOutput\n | WebhookTriggerOutput\n | QueueTriggerOutput\n | SubscriptionTriggerOutput\n | TimerTriggerOutput;\n\n// TODO(burdon): Reuse trigger schema from @dxos/functions (TriggerType).\nexport const EmailTriggerOutput = Schema.mutable(\n Schema.Struct({\n from: Schema.String,\n to: Schema.String,\n subject: Schema.String,\n created: Schema.String,\n body: Schema.String,\n }),\n);\nexport type EmailTriggerOutput = Schema.Schema.Type<typeof EmailTriggerOutput>;\n\nexport const WebhookTriggerOutput = Schema.mutable(\n Schema.Struct({\n url: Schema.String,\n method: Schema.Literal('GET', 'POST'),\n headers: Schema.Record({ key: Schema.String, value: Schema.String }),\n bodyText: Schema.String,\n }),\n);\nexport type WebhookTriggerOutput = Schema.Schema.Type<typeof WebhookTriggerOutput>;\n\nexport const QueueTriggerOutput = Schema.mutable(\n Schema.Struct({\n queue: DXN.Schema,\n item: Schema.Any,\n cursor: Schema.String,\n }),\n);\nexport type QueueTriggerOutput = Schema.Schema.Type<typeof QueueTriggerOutput>;\n\nexport const SubscriptionTriggerOutput = Schema.mutable(\n Schema.Struct({ type: Schema.String, changedObjectId: Schema.String }),\n);\nexport type SubscriptionTriggerOutput = Schema.Schema.Type<typeof SubscriptionTriggerOutput>;\n\nexport const TimerTriggerOutput = Schema.mutable(Schema.Struct({ tick: Schema.Number }));\nexport type TimerTriggerOutput = Schema.Schema.Type<typeof TimerTriggerOutput>;\n\n/**\n * Function trigger.\n * Function is invoked with the `payload` passed as input data.\n * The event that triggers the function is available in the function context.\n */\nexport const FunctionTriggerSchema = Schema.Struct({\n /**\n * Function or workflow to invoke.\n */\n // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).\n function: Schema.optional(Ref(Expando).annotations({ title: 'Function' })),\n\n /**\n * Only used for workflowSchema.\n * Specifies the input node in the circuit.\n * @deprecated Remove and enforce a single input node in all compute graphSchema.\n */\n inputNodeId: Schema.optional(Schema.String.annotations({ title: 'Input Node ID' })),\n\n enabled: Schema.optional(Schema.Boolean.annotations({ title: 'Enabled' })),\n\n spec: Schema.optional(TriggerSchema),\n\n /**\n * Passed as the input data to the function.\n * Must match the function's input schema.\n *\n * @example\n * {\n * item: '{{$.trigger.event}}',\n * instructions: 'Summarize and perform entity-extraction'\n * mailbox: { '/': 'dxn:echo:AAA:ZZZ' }\n * }\n */\n input: Schema.optional(Schema.mutable(Schema.Record({ key: Schema.String, value: Schema.Any }))),\n});\n\nexport type FunctionTriggerType = Schema.Schema.Type<typeof FunctionTriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.2.0',\n})(FunctionTriggerSchema.fields) {}\n\n// TODO(wittjosiah): Remove?\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = Schema.Struct({\n functions: Schema.optional(Schema.mutable(Schema.Array(RawObject(FunctionType)))),\n triggers: Schema.optional(Schema.mutable(Schema.Array(RawObject(FunctionTrigger)))),\n});\nexport type FunctionManifest = Schema.Schema.Type<typeof FunctionManifestSchema>;\n\nexport const FUNCTION_TYPES = [FunctionType, FunctionTrigger];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ObjectMeta } from '@dxos/echo-schema';\nimport { type SpaceId } from '@dxos/keys';\n\n// TODO: use URL scheme for source?\nconst FUNCTIONS_META_KEY = 'dxos.org/service/function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'dxos.org/service/function-preset';\n\nconst isSecure = (protocol: string) => {\n return protocol === 'https:' || protocol === 'wss:';\n};\n\nexport const getUserFunctionUrlInMetadata = (meta: ObjectMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\nexport const setUserFunctionUrlInMetadata = (meta: ObjectMeta, functionUrl: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionUrl) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionUrl });\n }\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const makeFunctionUrl = (fn: { functionId: string }) => `/${fn.functionId}`;\n\nexport const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = isSecure(url.protocol) ? 'https' : 'http';\n return url.toString();\n};\n\nexport type InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Schema } from 'effect';\n\nimport type { SpaceId } from '@dxos/client/echo';\n\nimport type { FunctionContext, FunctionDefinition } from '../handler';\nimport type { ServiceContainer } from '../services';\n\nexport class FunctionExecutor {\n constructor(private readonly _services: ServiceContainer) {}\n\n // TODO(dmaretskyi): Invocation context: queue, space, etc...\n async invoke<F extends FunctionDefinition<any, any>>(\n fnDef: F,\n input: F extends FunctionDefinition<infer I, infer _O> ? I : never,\n ): Promise<F extends FunctionDefinition<infer _I, infer O> ? O : never> {\n // Assert input matches schema\n const assertInput = fnDef.inputSchema.pipe(Schema.asserts);\n (assertInput as any)(input);\n\n const context: FunctionContext = {\n getService: this._services.getService.bind(this._services),\n getSpace: async (_spaceId: SpaceId) => {\n throw new Error('Not available. Use the database service instead.');\n },\n space: undefined,\n get ai(): never {\n throw new Error('Not available. Use the ai service instead.');\n },\n };\n\n const result = await fnDef.handler({ context, data: input });\n\n // Assert output matches schema\n const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);\n (assertOutput as any)(result);\n\n if (Effect.isEffect(result)) {\n return Effect.runPromise(result as any);\n }\n\n return result as any;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;AAIA,SAASA,cAAyC;AA8F3C,IAAMC,iBAAiB,CAAOC,WAAAA;AACnC,MAAI,CAACC,OAAOC,SAASF,OAAOG,WAAW,GAAG;AACxC,UAAM,IAAIC,MAAM,qCAAA;EAClB;AACA,MAAI,OAAOJ,OAAOK,YAAY,YAAY;AACxC,UAAM,IAAID,MAAM,4BAAA;EAClB;AAEA,SAAO;IACLE,aAAaN,OAAOM;IACpBH,aAAaH,OAAOG;IACpBI,cAAcP,OAAOO,gBAAgBN,OAAOO;IAC5CH,SAASL,OAAOK;EAClB;AACF;;;AC5GA,SAASI,UAAAA,eAAc;AAEvB,SAASC,YAAY;AACrB,SAASC,gBAAgBC,iBAAiBC,WAAW;AACrD,SAASC,gBAAgB;AAKlB,IAAMC,aAAaC,QAAOC,OAAO;EACtCC,MAAM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OAAOE,WAAWP,MAAAA;IAC3B;AAEA,WAAOA;EACT;AACF;",
6
- "names": ["Schema", "defineFunction", "params", "Schema", "isSchema", "inputSchema", "Error", "handler", "description", "outputSchema", "Any", "Schema", "Type", "JsonSchemaType", "LabelAnnotation", "Ref", "DataType", "ScriptType", "Schema", "Struct", "name", "optional", "String", "description", "changed", "Boolean", "source", "Ref", "DataType", "Text", "pipe", "Type", "Obj", "typename", "version", "LabelAnnotation", "set", "FunctionType", "NonEmptyString", "inputSchema", "JsonSchemaType", "outputSchema", "binding", "Schema", "Type", "Queue", "ObjectId", "log", "Schema", "SchemaAST", "Expando", "OptionsAnnotationId", "TypedObject", "Ref", "RawObject", "DXN", "TriggerKind", "kindLiteralAnnotations", "title", "TimerTriggerSchema", "Schema", "Struct", "kind", "Literal", "annotations", "cron", "String", "SchemaAST", "ExamplesAnnotationId", "pipe", "mutable", "EmailTriggerSchema", "QueueTriggerSchema", "queue", "DXN", "WebhookTriggerSchema", "method", "optional", "OptionsAnnotationId", "port", "Number", "QuerySchema", "type", "props", "Record", "key", "value", "Any", "SubscriptionTriggerSchema", "filter", "options", "deep", "Boolean", "delay", "TriggerSchema", "Union", "EmailTriggerOutput", "from", "to", "subject", "created", "body", "WebhookTriggerOutput", "url", "headers", "bodyText", "QueueTriggerOutput", "item", "cursor", "SubscriptionTriggerOutput", "changedObjectId", "TimerTriggerOutput", "tick", "FunctionTriggerSchema", "function", "Ref", "Expando", "inputNodeId", "enabled", "spec", "input", "FunctionTrigger", "TypedObject", "typename", "version", "fields", "FunctionManifestSchema", "functions", "Array", "RawObject", "FunctionType", "triggers", "FUNCTION_TYPES", "InvocationOutcome", "InvocationTraceEventType", "TraceEventException", "Schema", "Struct", "timestampMs", "Number", "message", "String", "name", "stack", "optional", "InvocationTraceStartEvent", "id", "ObjectId", "type", "Literal", "invocationId", "input", "Object", "invocationTraceQueue", "Type", "Ref", "Queue", "invocationTarget", "Expando", "trigger", "FunctionTrigger", "pipe", "Obj", "typename", "version", "InvocationTraceEndEvent", "outcome", "Enums", "exception", "TraceEventLog", "level", "context", "TraceEvent", "truncated", "Boolean", "ingestionTimestampMs", "logs", "Array", "exceptions", "createInvocationSpans", "items", "eventsByInvocationId", "Map", "event", "entry", "get", "start", "undefined", "end", "set", "now", "Date", "result", "entries", "log", "warn", "isInProgress", "push", "durationMs", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "isSecure", "protocol", "getUserFunctionUrlInMetadata", "meta", "keys", "find", "key", "source", "id", "setUserFunctionUrlInMetadata", "functionUrl", "Error", "push", "makeFunctionUrl", "fn", "functionId", "getInvocationUrl", "edgeUrl", "options", "baseUrl", "URL", "relativeUrl", "replace", "url", "toString", "spaceId", "searchParams", "set", "subjectId", "Effect", "Schema", "FunctionExecutor", "_services", "invoke", "fnDef", "input", "assertInput", "inputSchema", "pipe", "Schema", "asserts", "context", "getService", "bind", "getSpace", "_spaceId", "Error", "space", "undefined", "ai", "result", "handler", "data", "assertOutput", "outputSchema", "Effect", "isEffect", "runPromise"]
4
+ "sourcesContent": ["//\n// Copyright 2023 DXOS.org\n//\n\nimport { type Context, type Effect, Schema } from 'effect';\n\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { type HasId } from '@dxos/echo-schema';\nimport { type DXN, type SpaceId } from '@dxos/keys';\nimport { type QueryResult } from '@dxos/protocols';\n\nimport type { Services } from './services';\n\n// TODO(burdon): Model after http request. Ref Lambda/OpenFaaS.\n// https://docs.aws.amazon.com/lambda/latest/dg/typescript-handler.html\n// https://www.serverless.com/framework/docs/providers/aws/guide/serverless.yml/#functions\n// https://www.npmjs.com/package/aws-lambda\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TOutput = any> = (params: {\n /**\n * Services and context available to the function.\n */\n context: FunctionContext;\n\n /**\n * Data passed as the input to the function.\n * Must match the function's input schema.\n * This will be the payload from the trigger or other data passed into the function in a workflow.\n */\n data: TData;\n}) => TOutput | Promise<TOutput> | Effect.Effect<TOutput, any, Services>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n /**\n * Space from which the function was invoked.\n */\n space: SpaceAPI | undefined;\n\n /**\n * Resolves a service available to the function.\n * @throws if the service is not available.\n */\n getService: <T extends Context.Tag<any, any>>(tag: T) => Context.Tag.Service<T>;\n\n getSpace: (spaceId: SpaceId) => Promise<SpaceAPI>;\n}\n\nexport interface FunctionContextAi {\n // TODO(dmaretskyi): Refer to cloudflare AI docs for more comprehensive typedefs.\n run(model: string, inputs: any, options?: any): Promise<any>;\n}\n\n//\n// API.\n//\n\n// TODO(dmaretskyi): Temporary API to get the queues working.\n// TODO(dmaretskyi): To be replaced with integrating queues into echo.\nexport interface QueuesAPI {\n queryQueue(queue: DXN, options?: {}): Promise<QueryResult>;\n insertIntoQueue(queue: DXN, objects: HasId[]): Promise<void>;\n}\n\n/**\n * Space interface available to functions.\n */\nexport interface SpaceAPI {\n get id(): SpaceId;\n get db(): EchoDatabase;\n\n // TODO(dmaretskyi): Align with echo api: queues.get(id).append(items);\n get queues(): QueuesAPI;\n}\n\n// TODO(wittjosiah): Queues are incompatible.\nconst __assertFunctionSpaceIsCompatibleWithTheClientSpace = () => {\n // const _: SpaceAPI = {} as Space;\n};\n\nexport type FunctionDefinition<T = {}, O = any> = {\n name: string;\n description?: string;\n inputSchema: Schema.Schema<T, any>;\n outputSchema?: Schema.Schema<O, any>;\n handler: FunctionHandler<T, O>;\n};\n\n// TODO(dmaretskyi): Bind input type to function handler.\nexport const defineFunction = <T, O>({\n name,\n description,\n inputSchema,\n outputSchema = Schema.Any,\n handler,\n}: FunctionDefinition<T, O>): FunctionDefinition<T, O> => {\n if (!Schema.isSchema(inputSchema)) {\n throw new Error('Input schema must be a valid schema');\n }\n if (typeof handler !== 'function') {\n throw new Error('Handler must be a function');\n }\n\n return {\n name,\n description,\n inputSchema,\n outputSchema,\n handler,\n };\n};\n\nexport namespace FunctionDefinition {\n export type Any = FunctionDefinition<any, any>;\n export type Input<T extends FunctionDefinition> = T extends FunctionDefinition<infer I, any> ? I : never;\n export type Output<T extends FunctionDefinition> = T extends FunctionDefinition<any, infer O> ? O : never;\n}\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { Type } from '@dxos/echo';\nimport { JsonSchemaType, LabelAnnotation, Ref } from '@dxos/echo-schema';\nimport { DataType } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const ScriptType = Schema.Struct({\n name: Schema.optional(Schema.String),\n description: Schema.optional(Schema.String),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: Schema.optional(Schema.Boolean),\n source: Ref(DataType.Text),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/Script',\n version: '0.1.0',\n }),\n LabelAnnotation.set(['name']),\n);\n\nexport interface ScriptType extends Schema.Schema.Type<typeof ScriptType> {}\n\n/**\n * Function deployment.\n */\nexport const FunctionType = Schema.Struct({\n // TODO(burdon): Rename to id/uri?\n name: Schema.NonEmptyString,\n version: Schema.String,\n\n description: Schema.optional(Schema.String),\n\n // Reference to a source script if it exists within ECHO.\n // TODO(burdon): Don't ref ScriptType directly (core).\n source: Schema.optional(Ref(ScriptType)),\n\n inputSchema: Schema.optional(JsonSchemaType),\n outputSchema: Schema.optional(JsonSchemaType),\n\n // Local binding to a function name.\n binding: Schema.optional(Schema.String),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/Function',\n version: '0.1.0',\n }),\n LabelAnnotation.set(['name']),\n);\nexport interface FunctionType extends Schema.Schema.Type<typeof FunctionType> {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Schema } from 'effect';\n\nimport { type Ref, Type } from '@dxos/echo';\nimport { Queue } from '@dxos/echo-db';\nimport { ObjectId } from '@dxos/echo-schema';\nimport { log } from '@dxos/log';\n\nimport { FunctionTrigger, type FunctionTriggerType } from './types';\n\nexport enum InvocationOutcome {\n SUCCESS = 'success',\n FAILURE = 'failure',\n PENDING = 'pending',\n}\n\n// TODO(burdon): Convert to extensible discriminated union of EDGE events.\nexport enum InvocationTraceEventType {\n START = 'start',\n END = 'end',\n}\n\nexport const TraceEventException = Schema.Struct({\n timestampMs: Schema.Number,\n message: Schema.String,\n name: Schema.String,\n stack: Schema.optional(Schema.String),\n});\nexport type TraceEventException = Schema.Schema.Type<typeof TraceEventException>;\n\nexport const InvocationTraceStartEvent = Schema.Struct({\n /**\n * Queue message id.\n */\n id: ObjectId,\n type: Schema.Literal(InvocationTraceEventType.START),\n /**\n * Invocation id, the same for invocation start and end events.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n timestampMs: Schema.Number,\n /**\n * Data passed to function / workflow as an argument.\n */\n // TODO(burdon): Input schema?\n input: Schema.Object,\n /**\n * Queue for function/workflow invocation events.\n */\n invocationTraceQueue: Type.Ref(Queue),\n /**\n * DXN of the invoked function/workflow.\n */\n invocationTarget: Type.Ref(Type.Expando),\n /**\n * Present for automatic invocations.\n */\n trigger: Schema.optional(Type.Ref(FunctionTrigger)),\n}).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceStart', version: '0.1.0' }));\n\nexport type InvocationTraceStartEvent = Schema.Schema.Type<typeof InvocationTraceStartEvent>;\n\nexport const InvocationTraceEndEvent = Schema.Struct({\n /**\n * Trace event id.\n */\n id: ObjectId,\n type: Schema.Literal(InvocationTraceEventType.END),\n /**\n * Invocation id, will be the same for invocation start and end.\n */\n invocationId: ObjectId,\n /**\n * Event generation time.\n */\n // TODO(burdon): Remove ms suffix.\n timestampMs: Schema.Number,\n outcome: Schema.Enums(InvocationOutcome),\n exception: Schema.optional(TraceEventException),\n}).pipe(Type.Obj({ typename: 'dxos.org/type/InvocationTraceEnd', version: '0.1.0' }));\n\nexport type InvocationTraceEndEvent = Schema.Schema.Type<typeof InvocationTraceEndEvent>;\n\nexport type InvocationTraceEvent = InvocationTraceStartEvent | InvocationTraceEndEvent;\n\nexport const TraceEventLog = Schema.Struct({\n timestampMs: Schema.Number,\n level: Schema.String,\n message: Schema.String,\n context: Schema.optional(Schema.Object),\n});\n\nexport const TraceEvent = Schema.Struct({\n id: ObjectId,\n // TODO(burdon): Need enum/numeric result (not string).\n outcome: Schema.String,\n truncated: Schema.Boolean,\n /** Time when the event was persisted. */\n ingestionTimestamp: Schema.Number,\n logs: Schema.Array(TraceEventLog),\n exceptions: Schema.Array(TraceEventException),\n}).pipe(Type.Obj({ typename: 'dxos.org/type/TraceEvent', version: '0.1.0' }));\n\nexport type TraceEvent = Schema.Schema.Type<typeof TraceEvent>;\n\n/**\n * InvocationTrace event format.\n * This is the combined format of InvocationTraceStartEvent and InvocationTraceEndEvents for UI consumption.\n */\nexport type InvocationSpan = {\n id: string;\n timestampMs: number;\n outcome: InvocationOutcome;\n input: object;\n durationMs: number;\n invocationTraceQueue: Ref.Ref<Queue>;\n invocationTarget: Ref.Ref<Type.Expando>;\n trigger?: Ref.Ref<FunctionTriggerType>;\n exception?: TraceEventException;\n};\n\nexport const createInvocationSpans = (items?: InvocationTraceEvent[]): InvocationSpan[] => {\n if (!items) {\n return [];\n }\n\n const eventsByInvocationId = new Map<string, { start?: InvocationTraceStartEvent; end?: InvocationTraceEndEvent }>();\n for (const event of items) {\n if (!('invocationId' in event)) {\n // Skip legacy format entries.\n continue;\n }\n\n const invocationId = event.invocationId;\n const entry = eventsByInvocationId.get(invocationId) || { start: undefined, end: undefined };\n if (event.type === InvocationTraceEventType.START) {\n entry.start = event as InvocationTraceStartEvent;\n } else if (event.type === InvocationTraceEventType.END) {\n entry.end = event as InvocationTraceEndEvent;\n }\n\n eventsByInvocationId.set(invocationId, entry);\n }\n\n const now = Date.now();\n const result: InvocationSpan[] = [];\n\n // Create spans for each invocation\n for (const [invocationId, { start, end }] of eventsByInvocationId.entries()) {\n if (!start) {\n // No start event, can't create a meaningful span\n log.warn('found end event without matching start', { invocationId });\n continue;\n }\n\n const isInProgress = end === undefined;\n\n result.push({\n id: invocationId,\n timestampMs: start.timestampMs,\n durationMs: isInProgress ? now - start.timestampMs : end!.timestampMs - start.timestampMs,\n outcome: end?.outcome ?? InvocationOutcome.PENDING,\n exception: end?.exception,\n input: start.input,\n invocationTraceQueue: start.invocationTraceQueue,\n invocationTarget: start.invocationTarget,\n trigger: start.trigger,\n });\n }\n\n return result;\n};\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { Schema, SchemaAST } from 'effect';\n\nimport { Expando, OptionsAnnotationId, RawObject, Ref, TypedObject } from '@dxos/echo-schema';\nimport { DXN } from '@dxos/keys';\n\nimport { FunctionType } from './schema';\n\n/**\n * Type discriminator for TriggerType.\n * Every spec has a type field of type TriggerKind that we can use to understand which type we're working with.\n * https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions\n */\nexport enum TriggerKind {\n Timer = 'timer',\n Webhook = 'webhook',\n Subscription = 'subscription',\n Email = 'email',\n Queue = 'queue',\n}\n\nconst kindLiteralAnnotations = { title: 'Kind' };\n\n/**\n * Cron timer.\n */\nconst TimerTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Timer).annotations(kindLiteralAnnotations),\n cron: Schema.String.annotations({\n title: 'Cron',\n [SchemaAST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n}).pipe(Schema.mutable);\nexport type TimerTrigger = Schema.Schema.Type<typeof TimerTriggerSchema>;\n\nconst EmailTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Email).annotations(kindLiteralAnnotations),\n}).pipe(Schema.mutable);\nexport type EmailTrigger = Schema.Schema.Type<typeof EmailTriggerSchema>;\n\nconst QueueTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Queue).annotations(kindLiteralAnnotations),\n queue: DXN.Schema,\n}).pipe(Schema.mutable);\nexport type QueueTrigger = Schema.Schema.Type<typeof QueueTriggerSchema>;\n\n/**\n * Webhook.\n */\nconst WebhookTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Webhook).annotations(kindLiteralAnnotations),\n method: Schema.optional(\n Schema.String.annotations({\n title: 'Method',\n [OptionsAnnotationId]: ['GET', 'POST'],\n }),\n ),\n port: Schema.optional(\n Schema.Number.annotations({\n title: 'Port',\n }),\n ),\n}).pipe(Schema.mutable);\nexport type WebhookTrigger = Schema.Schema.Type<typeof WebhookTriggerSchema>;\n\n// TODO(burdon): Use ECHO definition (from https://github.com/dxos/dxos/pull/8233).\nconst QuerySchema = Schema.Struct({\n type: Schema.optional(Schema.String.annotations({ title: 'Type' })),\n props: Schema.optional(Schema.Record({ key: Schema.String, value: Schema.Any })),\n}).annotations({ title: 'Query' });\n\n/**\n * Subscription.\n */\nconst SubscriptionTriggerSchema = Schema.Struct({\n kind: Schema.Literal(TriggerKind.Subscription).annotations(kindLiteralAnnotations),\n // TODO(burdon): Define query DSL (from ECHO). Reconcile with Table.Query.\n filter: QuerySchema,\n options: Schema.optional(\n Schema.Struct({\n // Watch changes to object (not just creation).\n deep: Schema.optional(Schema.Boolean.annotations({ title: 'Nested' })),\n // Debounce changes (delay in ms).\n delay: Schema.optional(Schema.Number.annotations({ title: 'Delay' })),\n }).annotations({ title: 'Options' }),\n ),\n}).pipe(Schema.mutable);\nexport type SubscriptionTrigger = Schema.Schema.Type<typeof SubscriptionTriggerSchema>;\n\n/**\n * Trigger schema (discriminated union).\n */\nexport const TriggerSchema = Schema.Union(\n TimerTriggerSchema,\n WebhookTriggerSchema,\n SubscriptionTriggerSchema,\n EmailTriggerSchema,\n QueueTriggerSchema,\n).annotations({\n title: 'Trigger',\n});\nexport type TriggerType = Schema.Schema.Type<typeof TriggerSchema>;\n\nexport type EventType =\n | EmailTriggerOutput\n | WebhookTriggerOutput\n | QueueTriggerOutput\n | SubscriptionTriggerOutput\n | TimerTriggerOutput;\n\n// TODO(burdon): Reuse trigger schema from @dxos/functions (TriggerType).\nexport const EmailTriggerOutput = Schema.mutable(\n Schema.Struct({\n from: Schema.String,\n to: Schema.String,\n subject: Schema.String,\n created: Schema.String,\n body: Schema.String,\n }),\n);\nexport type EmailTriggerOutput = Schema.Schema.Type<typeof EmailTriggerOutput>;\n\nexport const WebhookTriggerOutput = Schema.mutable(\n Schema.Struct({\n url: Schema.String,\n method: Schema.Literal('GET', 'POST'),\n headers: Schema.Record({ key: Schema.String, value: Schema.String }),\n bodyText: Schema.String,\n }),\n);\nexport type WebhookTriggerOutput = Schema.Schema.Type<typeof WebhookTriggerOutput>;\n\nexport const QueueTriggerOutput = Schema.mutable(\n Schema.Struct({\n queue: DXN.Schema,\n item: Schema.Any,\n cursor: Schema.String,\n }),\n);\nexport type QueueTriggerOutput = Schema.Schema.Type<typeof QueueTriggerOutput>;\n\nexport const SubscriptionTriggerOutput = Schema.mutable(\n Schema.Struct({ type: Schema.String, changedObjectId: Schema.String }),\n);\nexport type SubscriptionTriggerOutput = Schema.Schema.Type<typeof SubscriptionTriggerOutput>;\n\nexport const TimerTriggerOutput = Schema.mutable(Schema.Struct({ tick: Schema.Number }));\nexport type TimerTriggerOutput = Schema.Schema.Type<typeof TimerTriggerOutput>;\n\n/**\n * Function trigger.\n * Function is invoked with the `payload` passed as input data.\n * The event that triggers the function is available in the function context.\n */\nexport const FunctionTriggerSchema = Schema.Struct({\n /**\n * Function or workflow to invoke.\n */\n // TODO(dmaretskyi): Can be a Ref(FunctionType) or Ref(ComputeGraphType).\n function: Schema.optional(Ref(Expando).annotations({ title: 'Function' })),\n\n /**\n * Only used for workflowSchema.\n * Specifies the input node in the circuit.\n * @deprecated Remove and enforce a single input node in all compute graphSchema.\n */\n inputNodeId: Schema.optional(Schema.String.annotations({ title: 'Input Node ID' })),\n\n enabled: Schema.optional(Schema.Boolean.annotations({ title: 'Enabled' })),\n\n spec: Schema.optional(TriggerSchema),\n\n /**\n * Passed as the input data to the function.\n * Must match the function's input schema.\n *\n * @example\n * {\n * item: '{{$.trigger.event}}',\n * instructions: 'Summarize and perform entity-extraction'\n * mailbox: { '/': 'dxn:echo:AAA:ZZZ' }\n * }\n */\n input: Schema.optional(Schema.mutable(Schema.Record({ key: Schema.String, value: Schema.Any }))),\n});\n\nexport type FunctionTriggerType = Schema.Schema.Type<typeof FunctionTriggerSchema>;\n\n/**\n * Function trigger.\n */\nexport class FunctionTrigger extends TypedObject({\n typename: 'dxos.org/type/FunctionTrigger',\n version: '0.2.0',\n})(FunctionTriggerSchema.fields) {}\n\n// TODO(wittjosiah): Remove?\n\n/**\n * Function manifest file.\n */\nexport const FunctionManifestSchema = Schema.Struct({\n functions: Schema.optional(Schema.mutable(Schema.Array(RawObject(FunctionType)))),\n triggers: Schema.optional(Schema.mutable(Schema.Array(RawObject(FunctionTrigger)))),\n});\nexport type FunctionManifest = Schema.Schema.Type<typeof FunctionManifestSchema>;\n\nexport const FUNCTION_TYPES = [FunctionType, FunctionTrigger];\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type ObjectMeta } from '@dxos/echo-schema';\nimport { type SpaceId } from '@dxos/keys';\n\n// TODO: use URL scheme for source?\nconst FUNCTIONS_META_KEY = 'dxos.org/service/function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'dxos.org/service/function-preset';\n\nconst isSecure = (protocol: string) => {\n return protocol === 'https:' || protocol === 'wss:';\n};\n\nexport const getUserFunctionUrlInMetadata = (meta: ObjectMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\nexport const setUserFunctionUrlInMetadata = (meta: ObjectMeta, functionUrl: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionUrl) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionUrl });\n }\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const makeFunctionUrl = (fn: { functionId: string }) => `/${fn.functionId}`;\n\nexport const getInvocationUrl = (functionUrl: string, edgeUrl: string, options: InvocationOptions = {}) => {\n const baseUrl = new URL('functions/', edgeUrl);\n\n // Leading slashes cause the URL to be treated as an absolute path.\n const relativeUrl = functionUrl.replace(/^\\//, '');\n const url = new URL(`./${relativeUrl}`, baseUrl.toString());\n options.spaceId && url.searchParams.set('spaceId', options.spaceId);\n options.subjectId && url.searchParams.set('subjectId', options.subjectId);\n url.protocol = isSecure(url.protocol) ? 'https' : 'http';\n return url.toString();\n};\n\nexport type InvocationOptions = {\n spaceId?: SpaceId;\n subjectId?: string;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { Effect, Schema } from 'effect';\n\nimport { type SpaceId } from '@dxos/client/echo';\nimport { runAndForwardErrors } from '@dxos/effect';\n\nimport type { FunctionContext, FunctionDefinition } from '../handler';\nimport type { ServiceContainer, Services } from '../services';\n\nexport class FunctionExecutor {\n constructor(private readonly _services: ServiceContainer) {}\n\n /**\n *\n */\n // TODO(dmaretskyi): Invocation context: queue, space, etc...\n async invoke<F extends FunctionDefinition<any, any>>(\n fnDef: F,\n input: F extends FunctionDefinition<infer I, infer _O> ? I : never,\n ): Promise<F extends FunctionDefinition<infer _I, infer O> ? O : never> {\n // Assert input matches schema\n const assertInput = fnDef.inputSchema.pipe(Schema.asserts);\n (assertInput as any)(input);\n\n const context: FunctionContext = {\n space: undefined,\n getService: this._services.getService.bind(this._services),\n getSpace: async (_spaceId: SpaceId) => {\n throw new Error('Not available. Use the database service instead.');\n },\n };\n\n const result = fnDef.handler({ context, data: input });\n\n let data: unknown;\n if (Effect.isEffect(result)) {\n data = await (result as Effect.Effect<unknown, unknown, Services>).pipe(\n Effect.provide(this._services.createLayer()),\n runAndForwardErrors,\n );\n } else {\n data = await result;\n }\n\n // Assert output matches schema\n const assertOutput = fnDef.outputSchema?.pipe(Schema.asserts);\n (assertOutput as any)(data);\n\n return data as any;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;AAIA,SAAoCA,cAAc;AA0F3C,IAAMC,iBAAiB,CAAO,EACnCC,MACAC,aACAC,aACAC,eAAeC,OAAOC,KACtBC,QAAO,MACkB;AACzB,MAAI,CAACF,OAAOG,SAASL,WAAAA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S;MACzDc,UAAU,OAAOC,aAAAA;AACf,cAAM,IAAIC,MAAM,kDAAA;MAClB;IACF;AAEA,UAAMC,SAASf,MAAMgB,QAAQ;MAAET;MAASU,MAAMhB;IAAM,CAAA;AAEpD,QAAIgB;AACJ,QAAIC,OAAOC,SAASJ,MAAAA,GAAS;AAC3BE,aAAO,MAAOF,OAAqDX,KACjEc,OAAOE,QAAQ,KAAKtB,UAAUuB,YAAW,CAAA,GACzCC,mBAAAA;IAEJ,OAAO;AACLL,aAAO,MAAMF;IACf;AAGA,UAAMQ,eAAevB,MAAMwB,cAAcpB,KAAKC,QAAOC,OAAO;AAC3DiB,iBAAqBN,IAAAA;AAEtB,WAAOA;EACT;AACF;",
6
+ "names": ["Schema", "defineFunction", "name", "description", "inputSchema", "outputSchema", "Schema", "Any", "handler", "isSchema", "Error", "Schema", "Type", "JsonSchemaType", "LabelAnnotation", "Ref", "DataType", "ScriptType", "Schema", "Struct", "name", "optional", "String", "description", "changed", "Boolean", "source", "Ref", "DataType", "Text", "pipe", "Type", "Obj", "typename", "version", "LabelAnnotation", "set", "FunctionType", "NonEmptyString", "inputSchema", "JsonSchemaType", "outputSchema", "binding", "Schema", "Type", "Queue", "ObjectId", "log", "Schema", "SchemaAST", "Expando", "OptionsAnnotationId", "RawObject", "Ref", "TypedObject", "DXN", "TriggerKind", "kindLiteralAnnotations", "title", "TimerTriggerSchema", "Schema", "Struct", "kind", "Literal", "annotations", "cron", "String", "SchemaAST", "ExamplesAnnotationId", "pipe", "mutable", "EmailTriggerSchema", "QueueTriggerSchema", "queue", "DXN", "WebhookTriggerSchema", "method", "optional", "OptionsAnnotationId", "port", "Number", "QuerySchema", "type", "props", "Record", "key", "value", "Any", "SubscriptionTriggerSchema", "filter", "options", "deep", "Boolean", "delay", "TriggerSchema", "Union", "EmailTriggerOutput", "from", "to", "subject", "created", "body", "WebhookTriggerOutput", "url", "headers", "bodyText", "QueueTriggerOutput", "item", "cursor", "SubscriptionTriggerOutput", "changedObjectId", "TimerTriggerOutput", "tick", "FunctionTriggerSchema", "function", "Ref", "Expando", "inputNodeId", "enabled", "spec", "input", "FunctionTrigger", "TypedObject", "typename", "version", "fields", "FunctionManifestSchema", "functions", "Array", "RawObject", "FunctionType", "triggers", "FUNCTION_TYPES", "InvocationOutcome", "InvocationTraceEventType", "TraceEventException", "Schema", "Struct", "timestampMs", "Number", "message", "String", "name", "stack", "optional", "InvocationTraceStartEvent", "id", "ObjectId", "type", "Literal", "invocationId", "input", "Object", "invocationTraceQueue", "Type", "Ref", "Queue", "invocationTarget", "Expando", "trigger", "FunctionTrigger", "pipe", "Obj", "typename", "version", "InvocationTraceEndEvent", "outcome", "Enums", "exception", "TraceEventLog", "level", "context", "TraceEvent", "truncated", "Boolean", "ingestionTimestamp", "logs", "Array", "exceptions", "createInvocationSpans", "items", "eventsByInvocationId", "Map", "event", "entry", "get", "start", "undefined", "end", "set", "now", "Date", "result", "entries", "log", "warn", "isInProgress", "push", "durationMs", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "isSecure", "protocol", "getUserFunctionUrlInMetadata", "meta", "keys", "find", "key", "source", "id", "setUserFunctionUrlInMetadata", "functionUrl", "Error", "push", "makeFunctionUrl", "fn", "functionId", "getInvocationUrl", "edgeUrl", "options", "baseUrl", "URL", "relativeUrl", "replace", "url", "toString", "spaceId", "searchParams", "set", "subjectId", "Effect", "Schema", "runAndForwardErrors", "FunctionExecutor", "_services", "invoke", "fnDef", "input", "assertInput", "inputSchema", "pipe", "Schema", "asserts", "context", "space", "undefined", "getService", "bind", "getSpace", "_spaceId", "Error", "result", "handler", "data", "Effect", "isEffect", "provide", "createLayer", "runAndForwardErrors", "assertOutput", "outputSchema"]
7
7
  }