@dxos/functions 0.8.4-main.ae835ea → 0.8.4-main.bc674ce

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 (184) hide show
  1. package/dist/lib/browser/index.mjs +767 -884
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/lib/node-esm/index.mjs +767 -884
  5. package/dist/lib/node-esm/index.mjs.map +4 -4
  6. package/dist/lib/node-esm/meta.json +1 -1
  7. package/dist/types/src/errors.d.ts +44 -60
  8. package/dist/types/src/errors.d.ts.map +1 -1
  9. package/dist/types/src/example/fib.d.ts +1 -1
  10. package/dist/types/src/example/index.d.ts +3 -3
  11. package/dist/types/src/example/index.d.ts.map +1 -1
  12. package/dist/types/src/example/reply.d.ts +1 -1
  13. package/dist/types/src/example/sleep.d.ts +1 -1
  14. package/dist/types/src/index.d.ts +2 -5
  15. package/dist/types/src/index.d.ts.map +1 -1
  16. package/dist/types/src/operation-compatibility.test.d.ts +2 -0
  17. package/dist/types/src/operation-compatibility.test.d.ts.map +1 -0
  18. package/dist/types/src/protocol/functions-ai-http-client.d.ts +12 -0
  19. package/dist/types/src/protocol/functions-ai-http-client.d.ts.map +1 -0
  20. package/dist/types/src/protocol/index.d.ts +2 -0
  21. package/dist/types/src/protocol/index.d.ts.map +1 -0
  22. package/dist/types/src/protocol/protocol.d.ts +7 -0
  23. package/dist/types/src/protocol/protocol.d.ts.map +1 -0
  24. package/dist/types/src/protocol/protocol.test.d.ts +2 -0
  25. package/dist/types/src/protocol/protocol.test.d.ts.map +1 -0
  26. package/dist/types/src/sdk.d.ts +114 -0
  27. package/dist/types/src/sdk.d.ts.map +1 -0
  28. package/dist/types/src/services/credentials.d.ts +6 -4
  29. package/dist/types/src/services/credentials.d.ts.map +1 -1
  30. package/dist/types/src/services/event-logger.d.ts +33 -27
  31. package/dist/types/src/services/event-logger.d.ts.map +1 -1
  32. package/dist/types/src/services/function-invocation-service.d.ts +7 -19
  33. package/dist/types/src/services/function-invocation-service.d.ts.map +1 -1
  34. package/dist/types/src/services/index.d.ts +2 -4
  35. package/dist/types/src/services/index.d.ts.map +1 -1
  36. package/dist/types/src/services/queues.d.ts +4 -4
  37. package/dist/types/src/services/queues.d.ts.map +1 -1
  38. package/dist/types/src/services/tracing.d.ts +41 -12
  39. package/dist/types/src/services/tracing.d.ts.map +1 -1
  40. package/dist/types/src/types/Function.d.ts +40 -35
  41. package/dist/types/src/types/Function.d.ts.map +1 -1
  42. package/dist/types/src/types/Script.d.ts +9 -16
  43. package/dist/types/src/types/Script.d.ts.map +1 -1
  44. package/dist/types/src/types/Trigger.d.ts +58 -76
  45. package/dist/types/src/types/Trigger.d.ts.map +1 -1
  46. package/dist/types/src/types/TriggerEvent.d.ts +43 -13
  47. package/dist/types/src/types/TriggerEvent.d.ts.map +1 -1
  48. package/dist/types/src/types/index.d.ts +1 -0
  49. package/dist/types/src/types/index.d.ts.map +1 -1
  50. package/dist/types/src/types/url.d.ts +13 -0
  51. package/dist/types/src/types/url.d.ts.map +1 -0
  52. package/dist/types/tsconfig.tsbuildinfo +1 -1
  53. package/package.json +23 -58
  54. package/src/errors.ts +4 -4
  55. package/src/example/fib.ts +1 -1
  56. package/src/example/reply.ts +1 -1
  57. package/src/example/sleep.ts +1 -1
  58. package/src/index.ts +2 -5
  59. package/src/operation-compatibility.test.ts +185 -0
  60. package/src/protocol/functions-ai-http-client.ts +67 -0
  61. package/src/{executor → protocol}/index.ts +1 -1
  62. package/src/protocol/protocol.test.ts +59 -0
  63. package/src/protocol/protocol.ts +262 -0
  64. package/src/{handler.ts → sdk.ts} +129 -66
  65. package/src/services/credentials.ts +32 -17
  66. package/src/services/event-logger.ts +10 -4
  67. package/src/services/function-invocation-service.ts +23 -70
  68. package/src/services/index.ts +2 -4
  69. package/src/services/queues.ts +5 -7
  70. package/src/services/tracing.ts +68 -44
  71. package/src/types/Function.ts +39 -8
  72. package/src/types/Script.ts +10 -9
  73. package/src/types/Trigger.ts +18 -14
  74. package/src/types/TriggerEvent.ts +29 -29
  75. package/src/types/index.ts +1 -0
  76. package/src/types/url.ts +32 -0
  77. package/dist/lib/browser/bundler/index.mjs +0 -256
  78. package/dist/lib/browser/bundler/index.mjs.map +0 -7
  79. package/dist/lib/browser/chunk-J5LGTIGS.mjs +0 -10
  80. package/dist/lib/browser/chunk-J5LGTIGS.mjs.map +0 -7
  81. package/dist/lib/browser/chunk-M6EXIREF.mjs +0 -610
  82. package/dist/lib/browser/chunk-M6EXIREF.mjs.map +0 -7
  83. package/dist/lib/browser/edge/index.mjs +0 -83
  84. package/dist/lib/browser/edge/index.mjs.map +0 -7
  85. package/dist/lib/browser/testing/index.mjs +0 -131
  86. package/dist/lib/browser/testing/index.mjs.map +0 -7
  87. package/dist/lib/node-esm/bundler/index.mjs +0 -257
  88. package/dist/lib/node-esm/bundler/index.mjs.map +0 -7
  89. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
  90. package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
  91. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs +0 -612
  92. package/dist/lib/node-esm/chunk-P3IATZMZ.mjs.map +0 -7
  93. package/dist/lib/node-esm/edge/index.mjs +0 -84
  94. package/dist/lib/node-esm/edge/index.mjs.map +0 -7
  95. package/dist/lib/node-esm/testing/index.mjs +0 -132
  96. package/dist/lib/node-esm/testing/index.mjs.map +0 -7
  97. package/dist/types/src/bundler/bundler.d.ts +0 -49
  98. package/dist/types/src/bundler/bundler.d.ts.map +0 -1
  99. package/dist/types/src/bundler/bundler.test.d.ts +0 -2
  100. package/dist/types/src/bundler/bundler.test.d.ts.map +0 -1
  101. package/dist/types/src/bundler/index.d.ts +0 -2
  102. package/dist/types/src/bundler/index.d.ts.map +0 -1
  103. package/dist/types/src/e2e/deploy.test.d.ts +0 -2
  104. package/dist/types/src/e2e/deploy.test.d.ts.map +0 -1
  105. package/dist/types/src/edge/functions.d.ts +0 -17
  106. package/dist/types/src/edge/functions.d.ts.map +0 -1
  107. package/dist/types/src/edge/index.d.ts +0 -2
  108. package/dist/types/src/edge/index.d.ts.map +0 -1
  109. package/dist/types/src/executor/executor.d.ts +0 -14
  110. package/dist/types/src/executor/executor.d.ts.map +0 -1
  111. package/dist/types/src/executor/index.d.ts +0 -2
  112. package/dist/types/src/executor/index.d.ts.map +0 -1
  113. package/dist/types/src/handler.d.ts +0 -102
  114. package/dist/types/src/handler.d.ts.map +0 -1
  115. package/dist/types/src/services/database.d.ts +0 -67
  116. package/dist/types/src/services/database.d.ts.map +0 -1
  117. package/dist/types/src/services/function-invocation-service.test.d.ts +0 -2
  118. package/dist/types/src/services/function-invocation-service.test.d.ts.map +0 -1
  119. package/dist/types/src/services/local-function-execution.d.ts +0 -34
  120. package/dist/types/src/services/local-function-execution.d.ts.map +0 -1
  121. package/dist/types/src/services/remote-function-execution-service.d.ts +0 -22
  122. package/dist/types/src/services/remote-function-execution-service.d.ts.map +0 -1
  123. package/dist/types/src/services/service-container.d.ts +0 -57
  124. package/dist/types/src/services/service-container.d.ts.map +0 -1
  125. package/dist/types/src/services/service-registry.d.ts +0 -31
  126. package/dist/types/src/services/service-registry.d.ts.map +0 -1
  127. package/dist/types/src/services/service-registry.test.d.ts +0 -2
  128. package/dist/types/src/services/service-registry.test.d.ts.map +0 -1
  129. package/dist/types/src/testing/index.d.ts +0 -3
  130. package/dist/types/src/testing/index.d.ts.map +0 -1
  131. package/dist/types/src/testing/layer.d.ts +0 -18
  132. package/dist/types/src/testing/layer.d.ts.map +0 -1
  133. package/dist/types/src/testing/logger.d.ts +0 -5
  134. package/dist/types/src/testing/logger.d.ts.map +0 -1
  135. package/dist/types/src/testing/persist-database.test.d.ts +0 -2
  136. package/dist/types/src/testing/persist-database.test.d.ts.map +0 -1
  137. package/dist/types/src/testing/services.d.ts +0 -59
  138. package/dist/types/src/testing/services.d.ts.map +0 -1
  139. package/dist/types/src/trace.d.ts +0 -122
  140. package/dist/types/src/trace.d.ts.map +0 -1
  141. package/dist/types/src/translations.d.ts +0 -12
  142. package/dist/types/src/translations.d.ts.map +0 -1
  143. package/dist/types/src/triggers/index.d.ts +0 -4
  144. package/dist/types/src/triggers/index.d.ts.map +0 -1
  145. package/dist/types/src/triggers/input-builder.d.ts +0 -3
  146. package/dist/types/src/triggers/input-builder.d.ts.map +0 -1
  147. package/dist/types/src/triggers/invocation-tracer.d.ts +0 -37
  148. package/dist/types/src/triggers/invocation-tracer.d.ts.map +0 -1
  149. package/dist/types/src/triggers/trigger-dispatcher.d.ts +0 -78
  150. package/dist/types/src/triggers/trigger-dispatcher.d.ts.map +0 -1
  151. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts +0 -2
  152. package/dist/types/src/triggers/trigger-dispatcher.test.d.ts.map +0 -1
  153. package/dist/types/src/triggers/trigger-state-store.d.ts +0 -28
  154. package/dist/types/src/triggers/trigger-state-store.d.ts.map +0 -1
  155. package/dist/types/src/url.d.ts +0 -21
  156. package/dist/types/src/url.d.ts.map +0 -1
  157. package/src/bundler/bundler.test.ts +0 -58
  158. package/src/bundler/bundler.ts +0 -295
  159. package/src/bundler/index.ts +0 -5
  160. package/src/e2e/deploy.test.ts +0 -69
  161. package/src/edge/functions.ts +0 -67
  162. package/src/edge/index.ts +0 -9
  163. package/src/executor/executor.ts +0 -58
  164. package/src/services/database.ts +0 -175
  165. package/src/services/function-invocation-service.test.ts +0 -81
  166. package/src/services/local-function-execution.ts +0 -153
  167. package/src/services/remote-function-execution-service.ts +0 -63
  168. package/src/services/service-container.ts +0 -115
  169. package/src/services/service-registry.test.ts +0 -45
  170. package/src/services/service-registry.ts +0 -63
  171. package/src/testing/index.ts +0 -6
  172. package/src/testing/layer.ts +0 -114
  173. package/src/testing/logger.ts +0 -17
  174. package/src/testing/persist-database.test.ts +0 -87
  175. package/src/testing/services.ts +0 -115
  176. package/src/trace.ts +0 -178
  177. package/src/translations.ts +0 -20
  178. package/src/triggers/index.ts +0 -7
  179. package/src/triggers/input-builder.ts +0 -35
  180. package/src/triggers/invocation-tracer.ts +0 -101
  181. package/src/triggers/trigger-dispatcher.test.ts +0 -664
  182. package/src/triggers/trigger-dispatcher.ts +0 -521
  183. package/src/triggers/trigger-state-store.ts +0 -61
  184. package/src/url.ts +0 -55
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../src/example/fib.ts", "../../../src/handler.ts", "../../../src/types/Function.ts", "../../../src/types/Script.ts", "../../../src/types/Trigger.ts", "../../../src/types/TriggerEvent.ts", "../../../src/example/reply.ts", "../../../src/example/sleep.ts", "../../../src/example/index.ts", "../../../src/executor/executor.ts", "../../../src/services/function-invocation-service.ts", "../../../src/services/local-function-execution.ts", "../../../src/trace.ts", "../../../src/triggers/invocation-tracer.ts", "../../../src/triggers/trigger-dispatcher.ts", "../../../src/triggers/input-builder.ts", "../../../src/triggers/trigger-state-store.ts"],
4
- "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../handler';\n\nexport default defineFunction({\n key: 'example.org/function/fib',\n name: 'Fibonacci',\n description: 'Function that calculates a Fibonacci number',\n inputSchema: Schema.Struct({\n iterations: Schema.optional(Schema.Number).annotations({\n description: 'Number of iterations',\n default: 100_000,\n }),\n }),\n outputSchema: Schema.Struct({\n result: Schema.String,\n }),\n handler: Effect.fn(function* ({ data: { iterations = 100_000 } }) {\n let a = 0n;\n let b = 1n;\n for (let i = 0; i < iterations; i++) {\n a += b;\n b = a - b;\n }\n return { result: a.toString() };\n }),\n});\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { Obj, Type } from '@dxos/echo';\nimport { type HasId } from '@dxos/echo/internal';\nimport { type EchoDatabase } from '@dxos/echo-db';\nimport { assertArgument } from '@dxos/invariant';\nimport { type DXN, type SpaceId } from '@dxos/keys';\nimport { type QueryResult } from '@dxos/protocols';\n\nimport { type Services } from './services';\nimport { Function } from './types';\nimport { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './url';\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\nconst typeId = Symbol.for('@dxos/functions/FunctionDefinition');\n\nexport type FunctionDefinition<T = any, O = any> = {\n [typeId]: true;\n key: string;\n name: string;\n description?: string;\n inputSchema: Schema.Schema<T, any>;\n outputSchema?: Schema.Schema<O, any>;\n handler: FunctionHandler<T, O>;\n meta?: {\n /**\n * Tools that are projected from functions have this annotation.\n *\n * deployedFunctionId:\n * - Backend deployment ID assigned by the EDGE function service (typically a UUID).\n * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.\n * - Persisted on the corresponding ECHO `Function.Function` object's metadata under the\n * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.\n */\n deployedFunctionId?: string;\n };\n};\n\nexport type FunctionProps<T, O> = {\n key: string;\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): Output type doesn't get typechecked.\nexport const defineFunction: {\n <I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O>;\n} = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler }) => {\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 // Captures the function definition location.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 2;\n const traceError = new Error();\n Error.stackTraceLimit = limit;\n let cache: false | string = false;\n const captureStackTrace = () => {\n if (cache !== false) {\n return cache;\n }\n if (traceError.stack !== undefined) {\n const stack = traceError.stack.split('\\n');\n if (stack[2] !== undefined) {\n cache = stack[2].trim();\n return cache;\n }\n }\n };\n\n const handlerWithSpan = (...args: any[]) => {\n const result = (handler as any)(...args);\n if (Effect.isEffect(result)) {\n return Effect.withSpan(result, `${key ?? name}`, {\n captureStackTrace,\n });\n }\n return result;\n };\n\n return {\n [typeId]: true,\n key,\n name,\n description,\n inputSchema,\n outputSchema,\n handler: handlerWithSpan,\n } satisfies FunctionDefinition.Any;\n};\n\nexport const FunctionDefinition = {\n make: defineFunction,\n isFunction: (value: unknown): value is FunctionDefinition.Any => {\n return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;\n },\n serialize: (functionDef: FunctionDefinition.Any): Function.Function => {\n assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');\n return serializeFunction(functionDef);\n },\n deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {\n assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');\n return deserializeFunction(functionObj);\n },\n};\nexport declare 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\nexport const serializeFunction = (functionDef: FunctionDefinition<any, any>): Function.Function => {\n const fn = Function.make({\n key: functionDef.key,\n name: functionDef.name,\n version: '0.1.0',\n description: functionDef.description,\n inputSchema: Type.toJsonSchema(functionDef.inputSchema),\n outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),\n });\n if (functionDef.meta?.deployedFunctionId) {\n setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta.deployedFunctionId);\n }\n return fn;\n};\n\nexport const deserializeFunction = (functionObj: Function.Function): FunctionDefinition<unknown, unknown> => {\n return {\n [typeId]: true,\n // TODO(dmaretskyi): Fix key.\n key: functionObj.key ?? functionObj.name,\n name: functionObj.name,\n description: functionObj.description,\n inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),\n outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),\n // TODO(dmaretskyi): This should throw error.\n handler: () => {},\n meta: {\n deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),\n },\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Obj, Type } from '@dxos/echo';\nimport { JsonSchemaType, LabelAnnotation, Ref } from '@dxos/echo/internal';\n\nimport { Script } from './Script';\n\n/**\n * Function deployment.\n */\nexport const Function = Schema.Struct({\n /**\n * Global registry ID.\n * NOTE: The `key` property refers to the original registry entry.\n */\n // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.\n // TODO(dmaretskyi): Consider making it part of ECHO meta.\n // TODO(dmaretskyi): Make required.\n key: Schema.optional(Schema.String).annotations({\n description: 'Unique registration key for the blueprint',\n }),\n\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(Script)),\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 Function extends Schema.Schema.Type<typeof Function> {}\n\nexport const make = (props: Obj.MakeProps<typeof Function>) => Obj.make(Function, props);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Obj, Ref, Type } from '@dxos/echo';\nimport { FormAnnotation, LabelAnnotation } from '@dxos/echo/internal';\nimport { DataType } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const Script = Schema.Struct({\n name: Schema.String.pipe(Schema.optional),\n description: Schema.String.pipe(Schema.optional),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: Schema.Boolean.pipe(FormAnnotation.set(false), Schema.optional),\n source: Type.Ref(DataType.Text).pipe(FormAnnotation.set(false)),\n}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/Script',\n version: '0.1.0',\n }),\n LabelAnnotation.set(['name']),\n);\nexport interface Script extends Schema.Schema.Type<typeof Script> {}\n\ntype Props = Omit<Obj.MakeProps<typeof Script>, 'source'> & { source?: string };\n\nexport const make = ({ source = '', ...props }: Props = {}) =>\n Obj.make(Script, { ...props, source: Ref.make(DataType.makeText(source)) });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { Obj, QueryAST, Type } from '@dxos/echo';\nimport { Expando, OptionsAnnotationId, Ref } from '@dxos/echo/internal';\nimport { DXN } from '@dxos/keys';\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 const Kinds = ['email', 'queue', 'subscription', 'timer', 'webhook'] as const;\nexport type Kind = (typeof Kinds)[number];\n\nconst kindLiteralAnnotations = { title: 'Kind' };\n\nexport const EmailSpec = Schema.Struct({\n kind: Schema.Literal('email').annotations(kindLiteralAnnotations),\n}).pipe(Schema.mutable);\nexport type EmailSpec = Schema.Schema.Type<typeof EmailSpec>;\n\nexport const QueueSpec = Schema.Struct({\n kind: Schema.Literal('queue').annotations(kindLiteralAnnotations),\n\n // TODO(dmaretskyi): Change to a reference.\n queue: DXN.Schema,\n}).pipe(Schema.mutable);\nexport type QueueSpec = Schema.Schema.Type<typeof QueueSpec>;\n\n/**\n * Subscription.\n */\nexport const SubscriptionSpec = Schema.Struct({\n kind: Schema.Literal('subscription').annotations(kindLiteralAnnotations),\n query: Schema.Struct({\n raw: Schema.optional(Schema.String.annotations({ title: 'Query' })),\n ast: QueryAST.Query,\n }).pipe(Schema.mutable),\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 SubscriptionSpec = Schema.Schema.Type<typeof SubscriptionSpec>;\n\n/**\n * Cron timer.\n */\nexport const TimerSpec = Schema.Struct({\n kind: Schema.Literal('timer').annotations(kindLiteralAnnotations),\n cron: Schema.String.annotations({\n title: 'Cron',\n [SchemaAST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n}).pipe(Schema.mutable);\nexport type TimerSpec = Schema.Schema.Type<typeof TimerSpec>;\n\n/**\n * Webhook.\n */\nexport const WebhookSpec = Schema.Struct({\n kind: Schema.Literal('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 WebhookSpec = Schema.Schema.Type<typeof WebhookSpec>;\n\n/**\n * Trigger schema.\n */\nexport const Spec = Schema.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({\n title: 'Trigger',\n});\nexport type Spec = Schema.Schema.Type<typeof Spec>;\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 */\nconst Trigger_ = 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(Spec),\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}).pipe(\n Type.Obj({\n typename: 'dxos.org/type/Trigger',\n version: '0.1.0',\n }),\n);\nexport interface Trigger extends Schema.Schema.Type<typeof Trigger_> {}\nexport interface TriggerEncoded extends Schema.Schema.Encoded<typeof Trigger_> {}\nexport const Trigger: Schema.Schema<Trigger, TriggerEncoded> = Trigger_;\n\nexport const make = (props: Obj.MakeProps<typeof Trigger>) => Obj.make(Trigger, props);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { DXN, Obj, Type } from '@dxos/echo';\n\nexport type TriggerEvent = EmailEvent | QueueEvent | SubscriptionEvent | TimerEvent | WebhookEvent;\n\n// TODO(burdon): Reuse trigger schema from @dxos/functions (TriggerType).\nexport const EmailEvent = 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 EmailEvent = Schema.Schema.Type<typeof EmailEvent>;\n\nexport const QueueEvent = Schema.mutable(\n Schema.Struct({\n queue: DXN.Schema,\n item: Schema.Any,\n cursor: Schema.String,\n }),\n);\nexport type QueueEvent = Schema.Schema.Type<typeof QueueEvent>;\n\nexport const SubscriptionEvent = Schema.Struct({\n /**\n * Type of the mutation.\n */\n // TODO(dmaretskyi): Specify enum.\n type: Schema.String,\n\n /**\n * Reference to the object that was changed or created.\n */\n subject: Type.Ref(Obj.Any),\n\n /**\n * @deprecated\n */\n changedObjectId: Schema.optional(Schema.String),\n}).pipe(Schema.mutable);\nexport type SubscriptionEvent = Schema.Schema.Type<typeof SubscriptionEvent>;\n\nexport const TimerEvent = Schema.mutable(Schema.Struct({ tick: Schema.Number }));\nexport type TimerEvent = Schema.Schema.Type<typeof TimerEvent>;\n\nexport const WebhookEvent = 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 WebhookEvent = Schema.Schema.Type<typeof WebhookEvent>;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../handler';\n\nexport default defineFunction({\n key: 'example.org/function/reply',\n name: 'Reply',\n description: 'Function that echoes the input',\n inputSchema: Schema.Any,\n outputSchema: Schema.Any,\n handler: Effect.fn(function* ({ data }) {\n yield* Console.log('reply', { data });\n return data;\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../handler';\n\nexport default defineFunction({\n key: 'example.org/function/sleep',\n name: 'Sleep',\n description: 'Function that sleeps for a given amount of time',\n inputSchema: Schema.Struct({\n duration: Schema.optional(Schema.Number).annotations({\n description: 'Milliseconds to sleep',\n default: 100_000,\n }),\n }),\n outputSchema: Schema.Void,\n handler: Effect.fn(function* ({ data: { duration = 100_000 } }) {\n yield* Effect.sleep(duration);\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { default as fib$ } from './fib';\nimport { default as reply$ } from './reply';\nimport { default as sleep$ } from './sleep';\n\nexport namespace Example {\n export const fib = fib$;\n export const reply = reply$;\n export const sleep = sleep$;\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\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\n/**\n * @deprecated Use `FunctionInvocationService`\n */\nexport class FunctionExecutor {\n constructor(private readonly _services: ServiceContainer) {}\n\n /**\n * Invoke function.\n */\n // TODO(dmaretskyi): Invocation context: queue, space, etc...\n async invoke<F extends FunctionDefinition<any, any>>(\n functionDef: 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 = functionDef.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 = functionDef.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 = functionDef.outputSchema?.pipe(Schema.asserts);\n (assertOutput as any)(data);\n\n return data as any;\n }\n}\n", "//\n// Copyright 2025 DXOS.org\n//\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { AiService } from '@dxos/ai';\n\nimport { type FunctionDefinition } from '../handler';\n\nimport { CredentialsService } from './credentials';\nimport { DatabaseService } from './database';\nimport {\n FunctionImplementationResolver,\n type InvocationServices,\n LocalFunctionExecutionService,\n} from './local-function-execution';\nimport { QueueService } from './queues';\nimport { RemoteFunctionExecutionService } from './remote-function-execution-service';\n\nexport class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<\n FunctionInvocationService,\n {\n invokeFunction<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;\n }\n>() {\n static invokeFunction = Effect.serviceFunctionEffect(FunctionInvocationService, (_) => _.invokeFunction);\n\n static layer = Layer.effect(\n FunctionInvocationService,\n Effect.gen(function* () {\n const localExecutioner = yield* LocalFunctionExecutionService;\n const remoteExecutioner = yield* RemoteFunctionExecutionService;\n\n return {\n invokeFunction: <I, O>(\n functionDef: FunctionDefinition<I, O>,\n input: I,\n ): Effect.Effect<O, never, InvocationServices> =>\n Effect.gen(function* () {\n if (functionDef.meta?.deployedFunctionId) {\n return yield* remoteExecutioner.callFunction<I, O>(functionDef.meta.deployedFunctionId, input);\n }\n\n return yield* localExecutioner.invokeFunction(functionDef, input);\n }),\n } satisfies Context.Tag.Service<FunctionInvocationService>;\n }),\n );\n\n // TODO(dmaretskyi): Don't provide `FunctionImplementationResolver`.\n static layerTest = ({\n functions = [],\n }: {\n functions?: readonly FunctionDefinition<any, any>[];\n } = {}): Layer.Layer<\n FunctionInvocationService,\n never,\n AiService.AiService | CredentialsService | DatabaseService | QueueService\n > =>\n FunctionInvocationService.layer.pipe(\n Layer.provide(LocalFunctionExecutionService.layerLive),\n Layer.provide(FunctionImplementationResolver.layerTest({ functions })),\n Layer.provide(RemoteFunctionExecutionService.layerMock),\n );\n\n // TODO(dmaretskyi): This shouldn't default to all services being not available.\n // TODO(dmaretskyi): Don't provide `FunctionImplementationResolver`.\n /**\n * @deprecated Use {@link layerTest} instead.\n */\n static layerTestMocked = ({\n functions,\n }: {\n functions?: readonly FunctionDefinition<any, any>[];\n }): Layer.Layer<FunctionInvocationService> =>\n FunctionInvocationService.layerTest({ functions }).pipe(\n Layer.provide(AiService.notAvailable),\n Layer.provide(CredentialsService.configuredLayer([])),\n Layer.provide(DatabaseService.notAvailable),\n Layer.provide(QueueService.notAvailable),\n );\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\n\nimport { AiService } from '@dxos/ai';\nimport { todo } from '@dxos/debug';\nimport { log } from '@dxos/log';\n\nimport { FunctionError, FunctionNotFoundError } from '../errors';\nimport type { FunctionContext, FunctionDefinition } from '../handler';\n\nimport { CredentialsService } from './credentials';\nimport { DatabaseService } from './database';\nimport { type ComputeEventLogger } from './event-logger';\nimport { QueueService } from './queues';\nimport { RemoteFunctionExecutionService } from './remote-function-execution-service';\nimport { type Services } from './service-container';\nimport { type TracingService } from './tracing';\n\n/**\n * Services that are provided at the function call site.\n */\nexport type InvocationServices = TracingService | ComputeEventLogger;\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<I, O>(functionDef: FunctionDefinition<I, O>, input: I): Effect.Effect<O, never, InvocationServices>;\n }\n>() {\n static layerLive = Layer.effect(\n LocalFunctionExecutionService,\n Effect.gen(function* () {\n // TODO(dmaretskyi): Use `yield* Effect.context()`;\n const resolver = yield* FunctionImplementationResolver;\n const ai = yield* AiService.AiService;\n const credentials = yield* CredentialsService;\n const database = yield* DatabaseService;\n const queues = yield* QueueService;\n // TODO(mykola): Delete, should not be required for local execution.\n const functionCallService = yield* RemoteFunctionExecutionService;\n return {\n // TODO(dmaretskyi): Better error types.\n invokeFunction: <I, O>(\n functionDef: FunctionDefinition<I, O>,\n input: I,\n ): Effect.Effect<O, never, InvocationServices> =>\n Effect.gen(function* () {\n const resolved = yield* resolver.resolveFunctionImplementation(functionDef).pipe(Effect.orDie);\n const output = yield* invokeFunction(resolved, input);\n return output as O;\n }).pipe(\n Effect.provideService(AiService.AiService, ai),\n Effect.provideService(CredentialsService, credentials),\n Effect.provideService(DatabaseService, database),\n Effect.provideService(QueueService, queues),\n Effect.provideService(RemoteFunctionExecutionService, functionCallService),\n ),\n };\n }),\n );\n\n static invokeFunction: <F extends FunctionDefinition.Any>(\n functionDef: 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 = (\n functionDef: FunctionDefinition<any, any>,\n input: any,\n): Effect.Effect<unknown, never, Services> =>\n Effect.gen(function* () {\n // Assert input matches schema.\n try {\n const assertInput = functionDef.inputSchema.pipe(Schema.asserts);\n (assertInput as any)(input);\n } catch (e) {\n throw new FunctionError({ message: 'Invalid function input', context: { name: functionDef.name }, cause: e });\n }\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 log.info('invoking function', { name: functionDef.name, input });\n\n // TODO(dmaretskyi): This should be delegated to a function invoker service.\n const data = yield* Effect.gen(function* () {\n const result = functionDef.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({ context: { name: functionDef.name }, cause: defect })),\n ),\n );\n\n log.info('completed', { function: functionDef.name, input, data });\n\n // Assert output matches schema.\n try {\n const assertOutput = functionDef.outputSchema?.pipe(Schema.asserts);\n (assertOutput as any)(data);\n } catch (e) {\n throw new FunctionError({ message: 'Invalid function output', context: { name: functionDef.name }, cause: e });\n }\n\n return data;\n }).pipe(Effect.withSpan('invokeFunction', { attributes: { name: functionDef.name } }));\n\nexport class FunctionImplementationResolver extends Context.Tag('@dxos/functions/FunctionImplementationResolver')<\n FunctionImplementationResolver,\n {\n resolveFunctionImplementation<I, O>(\n functionDef: FunctionDefinition<I, O>,\n ): Effect.Effect<FunctionDefinition<I, O>, FunctionNotFoundError>;\n }\n>() {\n static layerTest = ({ functions }: { functions: readonly FunctionDefinition<any, any>[] }) =>\n Layer.succeed(FunctionImplementationResolver, {\n resolveFunctionImplementation: <I, O>(functionDef: FunctionDefinition<I, O>) => {\n const resolved = functions.find((f) => f.key === functionDef.key);\n if (!resolved) {\n return Effect.fail(new FunctionNotFoundError(functionDef.name));\n }\n return Effect.succeed(resolved);\n },\n });\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { type Ref, Type } from '@dxos/echo';\nimport { ObjectId } from '@dxos/echo/internal';\nimport { Queue } from '@dxos/echo-db';\nimport { log } from '@dxos/log';\n\nimport { Trigger } 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 timestamp: 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 timestamp: 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: Schema.optional(Type.Ref(Queue)),\n /**\n * DXN of the invoked function/workflow.\n */\n invocationTarget: Schema.optional(Type.Ref(Type.Expando)),\n /**\n * Present for automatic invocations.\n */\n trigger: Schema.optional(Type.Ref(Trigger.Trigger)),\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 timestamp: 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 timestamp: 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 timestamp: number;\n duration: number;\n outcome: InvocationOutcome;\n input: object;\n invocationTraceQueue?: Ref.Ref<Queue>;\n invocationTarget?: Ref.Ref<Type.Expando>;\n trigger?: Ref.Ref<Trigger.Trigger>;\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 timestamp: start.timestamp,\n duration: isInProgress ? now - start.timestamp : end!.timestamp - start.timestamp,\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 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { Obj, Ref } from '@dxos/echo';\nimport { type Queue } from '@dxos/echo-db';\nimport { DXN, ObjectId } from '@dxos/keys';\n\nimport { QueueService } from '../services';\nimport {\n InvocationOutcome,\n InvocationTraceEndEvent,\n InvocationTraceEventType,\n InvocationTraceStartEvent,\n} from '../trace';\nimport type { Trigger } from '../types';\n\nexport type FunctionInvocationPayload = {\n data?: any;\n inputNodeId?: string;\n trigger?: {\n id: string;\n kind: Trigger.Kind;\n };\n};\n\nexport type TraceData = {\n invocationId: ObjectId;\n invocationTraceQueue: Queue;\n};\n\nexport class InvocationTracer extends Context.Tag('@dxos/functions/InvocationTracer')<\n InvocationTracer,\n {\n traceInvocationStart({\n payload,\n target,\n }: {\n payload: FunctionInvocationPayload;\n target?: DXN;\n }): Effect.Effect<TraceData, never, QueueService>;\n\n traceInvocationEnd({ trace, exception }: { trace: TraceData; exception?: any }): Effect.Effect<void>;\n }\n>() {\n static layerLive = (opts: { invocationTraceQueue: Queue }) =>\n Layer.effect(\n InvocationTracer,\n Effect.gen(function* () {\n return {\n traceInvocationStart: Effect.fn('traceInvocationStart')(function* ({ payload, target }) {\n const invocationId = ObjectId.random();\n const invocationTraceQueue = yield* QueueService.createQueue({ subspaceTag: 'trace' });\n const now = Date.now();\n const traceEvent = Obj.make(InvocationTraceStartEvent, {\n type: InvocationTraceEventType.START,\n invocationId,\n timestamp: now,\n // TODO(dmaretskyi): Not json-stringifying this makes ECHO fail when one ECHO object becomes embedded in another ECHO object.\n input: JSON.parse(JSON.stringify(payload.data ?? {})),\n invocationTraceQueue: Ref.fromDXN(invocationTraceQueue.dxn),\n invocationTarget: target ? Ref.fromDXN(target) : undefined,\n trigger: payload.trigger ? Ref.fromDXN(DXN.fromLocalObjectId(payload.trigger.id)) : undefined,\n });\n yield* QueueService.append(opts.invocationTraceQueue, [traceEvent]);\n\n return { invocationId, invocationTraceQueue };\n }),\n traceInvocationEnd: Effect.fn('traceInvocationEnd')(function* ({ trace, exception }) {\n const now = Date.now();\n const traceEvent = Obj.make(InvocationTraceEndEvent, {\n type: InvocationTraceEventType.END,\n invocationId: trace.invocationId,\n timestamp: now,\n outcome: exception ? InvocationOutcome.FAILURE : InvocationOutcome.SUCCESS,\n exception: exception\n ? {\n name: exception.constructor.name,\n timestamp: now,\n message: exception?.message ?? 'Unknown error',\n stack: exception?.stack,\n }\n : undefined,\n });\n yield* QueueService.append(opts.invocationTraceQueue, [traceEvent]);\n }),\n };\n }),\n );\n\n static layerTest = Layer.unwrapEffect(\n Effect.gen(function* () {\n const queue = yield* QueueService.createQueue({ subspaceTag: 'trace' });\n return InvocationTracer.layerLive({ invocationTraceQueue: queue });\n }),\n );\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Cause from 'effect/Cause';\nimport * as Context from 'effect/Context';\nimport * as Cron from 'effect/Cron';\nimport * as Duration from 'effect/Duration';\nimport * as Effect from 'effect/Effect';\nimport * as Either from 'effect/Either';\nimport * as Exit from 'effect/Exit';\nimport * as Fiber from 'effect/Fiber';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Record from 'effect/Record';\nimport * as Schedule from 'effect/Schedule';\n\nimport { DXN, Filter, Obj, Query } from '@dxos/echo';\nimport { causeToError } from '@dxos/effect';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { KEY_QUEUE_POSITION } from '@dxos/protocols';\n\nimport { deserializeFunction } from '../handler';\nimport {\n ComputeEventLogger,\n DatabaseService,\n FunctionInvocationService,\n QueueService,\n TracingService,\n} from '../services';\nimport { Function, Trigger, type TriggerEvent } from '../types';\n\nimport { createInvocationPayload } from './input-builder';\nimport { InvocationTracer } from './invocation-tracer';\nimport { type TriggerState, TriggerStateStore } from './trigger-state-store';\n\nexport type TimeControl = 'natural' | 'manual';\n\nexport interface TriggerDispatcherOptions {\n /**\n * Time control mode.\n * - 'natural': Use real time.\n * - 'manual': Use internal clock for testing.\n */\n timeControl: TimeControl;\n\n /**\n * Starting time for manual time control mode.\n * @default current time\n */\n startingTime?: Date;\n\n /**\n * Poll interval for cron triggers in 'natural' time control mode.\n * @default 1 second\n */\n livePollInterval?: Duration.Duration;\n}\n\nexport interface InvokeTriggerOptions {\n trigger: Trigger.Trigger;\n event: TriggerEvent.TriggerEvent;\n}\nexport interface TriggerExecutionResult {\n triggerId: string;\n result: Exit.Exit<unknown>;\n}\n\n/**\n * Cront trigger runtime state.\n */\ninterface ScheduledTrigger {\n trigger: Trigger.Trigger;\n cron: Cron.Cron;\n nextExecution: Date;\n}\n\n// TODO(dmaretskyi): Refactor service management.\ntype TriggerDispatcherServices =\n | FunctionInvocationService\n // TODO(dmaretskyi): Move those into layer deps.\n | TriggerStateStore\n | InvocationTracer\n | QueueService\n | DatabaseService;\n\nexport class TriggerDispatcher extends Context.Tag('@dxos/functions/TriggerDispatcher')<\n TriggerDispatcher,\n {\n readonly timeControl: TimeControl;\n\n get running(): boolean;\n\n /**\n * Start the trigger dispatcher.\n * Will automatically invoke triggers.\n */\n start(): Effect.Effect<void, never, TriggerDispatcherServices>;\n\n /**\n * Stop the trigger dispatcher.\n */\n stop(): Effect.Effect<void>;\n\n /**\n * Refresh triggers.\n */\n refreshTriggers(): Effect.Effect<void, never, DatabaseService>;\n\n /**\n * Manually invoke a specific trigger.\n */\n invokeTrigger(\n options: InvokeTriggerOptions,\n ): Effect.Effect<TriggerExecutionResult, never, TriggerDispatcherServices>;\n\n /**\n * Invoke all scheduled triggers who are due.\n */\n invokeScheduledTriggers(opts?: {\n kinds?: Trigger.Kind[];\n }): Effect.Effect<TriggerExecutionResult[], never, TriggerDispatcherServices>;\n\n /**\n * Advance the internal clock (manual time control only).\n * Note: Does not invoke triggers.\n */\n advanceTime(duration: Duration.Duration): Effect.Effect<void>;\n\n /**\n * Get current time based on time control mode.\n */\n getCurrentTime(): Date;\n }\n>() {\n static layer = (options: Omit<TriggerDispatcherOptions, 'database'>) =>\n Layer.effect(\n TriggerDispatcher,\n Effect.gen(function* () {\n return new TriggerDispatcherImpl(options);\n }),\n );\n}\n\nclass TriggerDispatcherImpl implements Context.Tag.Service<TriggerDispatcher> {\n readonly livePollInterval: Duration.Duration;\n readonly timeControl: TimeControl;\n\n private _running = false;\n private _internalTime: Date;\n private _timerFiber: Fiber.Fiber<void, void> | undefined;\n private _scheduledTriggers = new Map<string, ScheduledTrigger>();\n\n constructor(options: TriggerDispatcherOptions) {\n this.timeControl = options.timeControl;\n this.livePollInterval = options.livePollInterval ?? Duration.seconds(1);\n this._internalTime = options.startingTime ?? new Date();\n }\n\n get running(): boolean {\n return this._running;\n }\n\n start = (): Effect.Effect<void, never, TriggerDispatcherServices> =>\n Effect.gen(this, function* () {\n if (this._running) {\n return;\n }\n\n this._running = true;\n\n // Start natural time processing if enabled\n if (this.timeControl === 'natural') {\n this._timerFiber = yield* this._startNaturalTimeProcessing().pipe(\n Effect.tapErrorCause((cause) => {\n const error = causeToError(cause);\n log.error('trigger dispatcher error', { error });\n this._running = false;\n return Effect.void;\n }),\n Effect.forkDaemon,\n );\n } else {\n return yield* Effect.dieMessage('TriggerDispatcher started in manual time control mode');\n }\n\n log.info('TriggerDispatcher started', { timeControl: this.timeControl });\n });\n\n stop = (): Effect.Effect<void> =>\n Effect.gen(this, function* () {\n if (!this._running) {\n return;\n }\n\n this._running = false;\n\n // Stop timer processing\n if (this._timerFiber) {\n yield* Fiber.interrupt(this._timerFiber);\n this._timerFiber = undefined;\n }\n\n // Clear scheduled triggers\n this._scheduledTriggers.clear();\n\n log.info('TriggerDispatcher stopped');\n });\n\n invokeTrigger = (\n options: InvokeTriggerOptions,\n ): Effect.Effect<TriggerExecutionResult, never, TriggerDispatcherServices> =>\n Effect.gen(this, function* () {\n const { trigger, event } = options;\n log.info('running trigger', { triggerId: trigger.id, spec: trigger.spec, event });\n\n const tracer = yield* InvocationTracer;\n const trace = yield* tracer.traceInvocationStart({\n target: trigger.function?.dxn,\n payload: {\n trigger: {\n id: trigger.id,\n // TODO(dmaretskyi): Is `spec` always there>\n kind: trigger.spec!.kind,\n },\n data: event,\n },\n });\n\n // Sandboxed section.\n const result = yield* Effect.gen(this, function* () {\n if (!trigger.enabled) {\n return yield* Effect.dieMessage('Attempting to invoke disabled trigger');\n }\n\n if (!trigger.function) {\n return yield* Effect.dieMessage('Trigger has no function reference');\n }\n\n // Resolve the function\n const serialiedFunction = yield* DatabaseService.load(trigger.function!).pipe(Effect.orDie);\n invariant(Obj.instanceOf(Function.Function, serialiedFunction));\n const functionDef = deserializeFunction(serialiedFunction);\n\n // Prepare input data\n const inputData = this._prepareInputData(trigger, event);\n\n // Invoke the function\n return yield* FunctionInvocationService.invokeFunction(functionDef, inputData).pipe(\n Effect.provide(\n ComputeEventLogger.layerFromTracing.pipe(\n Layer.provideMerge(TracingService.layerQueue(trace.invocationTraceQueue)),\n ),\n ),\n );\n }).pipe(Effect.exit);\n\n const triggerExecutionResult: TriggerExecutionResult = {\n triggerId: trigger.id,\n result,\n };\n if (Exit.isSuccess(result)) {\n log.info('trigger execution success', {\n triggerId: trigger.id,\n });\n } else {\n log.error('trigger execution failure', {\n error: causeToError(result.cause),\n });\n }\n yield* tracer.traceInvocationEnd({\n trace,\n // TODO(dmaretskyi): Might miss errors.\n exception: Exit.isFailure(result) ? Cause.prettyErrors(result.cause)[0] : undefined,\n });\n return triggerExecutionResult;\n });\n\n invokeScheduledTriggers = ({ kinds = ['timer', 'queue', 'subscription'] } = {}): Effect.Effect<\n TriggerExecutionResult[],\n never,\n TriggerDispatcherServices\n > =>\n Effect.gen(this, function* () {\n const invocations: TriggerExecutionResult[] = [];\n for (const kind of kinds) {\n switch (kind) {\n case 'timer':\n {\n yield* this.refreshTriggers();\n const now = this.getCurrentTime();\n const triggersToInvoke: Trigger.Trigger[] = [];\n\n for (const [triggerId, scheduledTrigger] of this._scheduledTriggers.entries()) {\n if (scheduledTrigger.nextExecution <= now) {\n triggersToInvoke.push(scheduledTrigger.trigger);\n\n // Update next execution time using Effect's Cron\n scheduledTrigger.nextExecution = Cron.next(scheduledTrigger.cron, now);\n }\n }\n\n // Invoke all due triggers\n invocations.push(\n ...(yield* Effect.forEach(\n triggersToInvoke,\n (trigger) =>\n this.invokeTrigger({\n trigger,\n event: { tick: now.getTime() } satisfies TriggerEvent.TimerEvent,\n }),\n { concurrency: 1 },\n )),\n );\n }\n break;\n case 'queue': {\n const triggers = yield* this._fetchTriggers();\n for (const trigger of triggers) {\n const spec = trigger.spec;\n if (spec?.kind !== 'queue') {\n continue;\n }\n const cursor = Obj.getKeys(trigger, KEY_QUEUE_CURSOR).at(0)?.id;\n const queue = yield* QueueService.getQueue(DXN.parse(spec.queue));\n\n // TODO(dmaretskyi): Include cursor & limit in the query.\n const objects = yield* Effect.promise(() => queue.queryObjects());\n for (const object of objects) {\n const objectPos = Obj.getKeys(object, KEY_QUEUE_POSITION).at(0)?.id;\n // TODO(dmaretskyi): Extract methods for managing queue position.\n if (!objectPos || (cursor && parseInt(cursor) >= parseInt(objectPos))) {\n continue;\n }\n\n invocations.push(\n yield* this.invokeTrigger({\n trigger,\n event: {\n queue: spec.queue,\n item: object,\n cursor: objectPos,\n } satisfies TriggerEvent.QueueEvent,\n }),\n );\n\n // Update trigger cursor.\n Obj.deleteKeys(trigger, KEY_QUEUE_CURSOR);\n Obj.getMeta(trigger).keys.push({ source: KEY_QUEUE_CURSOR, id: objectPos });\n yield* DatabaseService.flush();\n\n // We only invoke one trigger for each queue at a time.\n break;\n }\n }\n break;\n }\n case 'subscription': {\n const triggers = yield* this._fetchTriggers();\n for (const trigger of triggers) {\n const spec = Obj.getSnapshot(trigger).spec;\n if (spec?.kind !== 'subscription') {\n continue;\n }\n\n const { objects } = yield* DatabaseService.runQuery(Query.fromAst(spec.query.ast));\n\n const state: TriggerState = yield* TriggerStateStore.getState(trigger.id).pipe(\n Effect.catchTag('TRIGGER_STATE_NOT_FOUND', () =>\n Effect.succeed({\n version: '1',\n triggerId: trigger.id,\n state: {\n _tag: 'subscription',\n processedVersions: {} as Record<string, string>,\n },\n } satisfies TriggerState),\n ),\n );\n invariant(state.state?._tag === 'subscription');\n\n let updated = false;\n for (const object of objects) {\n const existingVersion = Record.get(state.state.processedVersions, object.id).pipe(\n Option.map(Obj.decodeVersion),\n );\n const currentVersion = Obj.version(object);\n const run =\n Option.isNone(existingVersion) ||\n Obj.compareVersions(currentVersion, existingVersion.value) === 'different';\n\n if (!run) {\n continue;\n }\n\n const { db } = yield* DatabaseService;\n invocations.push(\n yield* this.invokeTrigger({\n trigger,\n event: {\n // TODO(dmaretskyi): Change type not supported.\n type: 'unknown',\n\n subject: db.ref(Obj.getDXN(object)),\n\n changedObjectId: object.id,\n } satisfies TriggerEvent.SubscriptionEvent,\n }),\n );\n (state.state.processedVersions as any)[object.id] = Obj.encodeVersion(currentVersion);\n updated = true;\n }\n\n if (updated) {\n yield* TriggerStateStore.saveState(state);\n }\n }\n break;\n }\n default: {\n return yield* Effect.dieMessage(`Unknown trigger kind: ${kind}`);\n }\n }\n }\n return invocations;\n });\n\n advanceTime = (duration: Duration.Duration): Effect.Effect<void> =>\n Effect.gen(this, function* () {\n if (this.timeControl !== 'manual') {\n return yield* Effect.dieMessage('advanceTime can only be used in manual time control mode');\n }\n\n const millis = Duration.toMillis(duration);\n this._internalTime = new Date(this._internalTime.getTime() + millis);\n\n log('Advanced internal time', {\n newTime: this._internalTime,\n advancedBy: Duration.format(duration),\n });\n }).pipe(Effect.orDie);\n\n getCurrentTime = (): Date => {\n if (this.timeControl === 'natural') {\n return new Date();\n } else {\n return new Date(this._internalTime);\n }\n };\n\n refreshTriggers = (): Effect.Effect<void, never, DatabaseService> =>\n Effect.gen(this, function* () {\n const triggers = yield* this._fetchTriggers();\n const currentTriggerIds = new Set(triggers.map((t) => t.id));\n\n // Remove triggers that are no longer present\n for (const triggerId of this._scheduledTriggers.keys()) {\n if (!currentTriggerIds.has(triggerId)) {\n this._scheduledTriggers.delete(triggerId);\n }\n }\n\n // Add or update triggers\n for (const trigger of triggers) {\n if (trigger.spec?.kind === 'timer' && trigger.enabled) {\n const timerSpec = trigger.spec as Trigger.TimerSpec;\n\n // Parse cron expression using Effect's Cron module\n const cronEither = Cron.parse(timerSpec.cron);\n\n if (Either.isRight(cronEither)) {\n const cron = cronEither.right;\n const existing = this._scheduledTriggers.get(trigger.id);\n const now = this.getCurrentTime();\n const nextExecution = existing?.nextExecution ?? Cron.next(cron, now);\n\n log('Updated scheduled trigger', {\n triggerId: trigger.id,\n cron: timerSpec.cron,\n nextExecution,\n now,\n });\n this._scheduledTriggers.set(trigger.id, {\n trigger,\n cron,\n nextExecution,\n });\n } else {\n log.error('Invalid cron expression', {\n triggerId: trigger.id,\n cron: timerSpec.cron,\n error: cronEither.left.message,\n });\n }\n }\n }\n\n log('Updated scheduled triggers', { count: this._scheduledTriggers.size });\n }).pipe(Effect.withSpan('TriggerDispatcher.refreshTriggers'));\n\n private _fetchTriggers = () =>\n Effect.gen(this, function* () {\n const { objects } = yield* DatabaseService.runQuery(Filter.type(Trigger.Trigger));\n return objects;\n }).pipe(Effect.withSpan('TriggerDispatcher.fetchTriggers'));\n\n private _startNaturalTimeProcessing = (): Effect.Effect<void, never, TriggerDispatcherServices> =>\n Effect.gen(this, function* () {\n yield* this.invokeScheduledTriggers();\n }).pipe(Effect.repeat(Schedule.fixed(this.livePollInterval)), Effect.asVoid);\n\n private _prepareInputData = (trigger: Trigger.Trigger, event: TriggerEvent.TriggerEvent): any => {\n return createInvocationPayload(trigger, event);\n };\n}\n\n/**\n * Key for the current queue cursor for queue triggers.\n */\nconst KEY_QUEUE_CURSOR = 'dxos.org/key/local-trigger-dispatcher/queue-cursor';\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Trigger, type TriggerEvent } from '../types';\n\nexport const createInvocationPayload = (trigger: Trigger.Trigger, event: TriggerEvent.TriggerEvent): any => {\n if (!trigger.input) {\n return event;\n }\n\n const payload: any = {};\n for (const [key, value] of Object.entries(trigger.input)) {\n if (typeof value !== 'string' || !(value.startsWith('{{') && value.endsWith('}}'))) {\n payload[key] = value;\n continue;\n }\n\n const propertyPath = value.slice(2, -2);\n let valueSubstitution: any = propertyPath.startsWith('trigger.')\n ? trigger\n : propertyPath.startsWith('event.')\n ? event\n : undefined;\n\n for (const pathSegment of propertyPath.split('.').slice(1)) {\n if (valueSubstitution && typeof valueSubstitution === 'object') {\n valueSubstitution = valueSubstitution[pathSegment];\n }\n }\n\n payload[key] = valueSubstitution;\n }\n return payload;\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as KeyValueStore from '@effect/platform/KeyValueStore';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Schema from 'effect/Schema';\n\nimport { ObjectId } from '@dxos/keys';\n\nimport { TriggerStateNotFoundError } from '../errors';\n\nexport const TriggerState = Schema.Struct({\n version: Schema.Literal('1'),\n triggerId: Schema.String,\n state: Schema.optional(\n Schema.Union(\n Schema.TaggedStruct('subscription', {\n processedVersions: Schema.Record({ key: ObjectId, value: Schema.String }),\n }),\n ),\n ),\n});\nexport interface TriggerState extends Schema.Schema.Type<typeof TriggerState> {}\n\nexport class TriggerStateStore extends Context.Tag('@dxos/functions/TriggerStateStore')<\n TriggerStateStore,\n {\n getState(triggerId: ObjectId): Effect.Effect<TriggerState, TriggerStateNotFoundError>;\n saveState(state: TriggerState): Effect.Effect<void>;\n }\n>() {\n static getState = Effect.serviceFunctionEffect(TriggerStateStore, (_) => _.getState);\n static saveState = Effect.serviceFunctionEffect(TriggerStateStore, (_) => _.saveState);\n\n static layerKv = Layer.effect(\n TriggerStateStore,\n Effect.gen(function* () {\n const kv = yield* KeyValueStore.KeyValueStore;\n const schemaStore = kv.forSchema(Schema.parseJson(TriggerState));\n const store: Context.Tag.Service<TriggerStateStore> = {\n getState: Effect.fn('TriggerStateStore.getState')(function* (triggerId: ObjectId) {\n const valueOption = yield* schemaStore.get(triggerId).pipe(Effect.orDie);\n if (Option.isNone(valueOption)) {\n return yield* Effect.fail(new TriggerStateNotFoundError());\n }\n return valueOption.value;\n }),\n saveState: Effect.fn('TriggerStateStore.saveState')(function* (state: TriggerState) {\n yield* schemaStore.set(state.triggerId, state).pipe(Effect.orDie);\n }),\n };\n return store;\n }),\n );\n\n static layerMemory = TriggerStateStore.layerKv.pipe(Layer.provide(KeyValueStore.layerMemory));\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,YAAYA,aAAY;AACxB,YAAYC,aAAY;;;ACAxB,YAAYC,YAAY;AACxB,YAAYC,aAAY;AAExB,SAASC,OAAAA,MAAKC,QAAAA,aAAY;AAG1B,SAASC,sBAAsB;;;ACX/B;;;cAAAC;;AAIA,YAAYC,aAAY;AAExB,SAASC,OAAAA,MAAKC,QAAAA,aAAY;AAC1B,SAASC,gBAAgBC,mBAAAA,kBAAiBC,OAAAA,YAAW;;;ACPrD;;;;;AAIA,YAAYC,YAAY;AAExB,SAASC,KAAKC,KAAKC,YAAY;A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AAO+I,WAAWK,KAAKC;UACzB,GAAA;;;;;;QACF;MACF;IACF;AAEAnJ,IAAAA,KAAI,8BAA8B;MAAEoJ,OAAO,KAAKjK,mBAAmBkK;IAAK,GAAA;;;;;;EAC1E,CAAA,EAAG1J,KAAY2J,kBAAS,mCAAA,CAAA;EAElB7E,iBAAiB,MAChB7F,aAAI,MAAM,aAAA;AACf,UAAM,EAAEuG,QAAO,IAAK,OAAOvD,gBAAgBqE,SAASsD,OAAO9B,KAAK+B,gBAAQA,OAAO,CAAA;AAC/E,WAAOrE;EACT,CAAA,EAAGxF,KAAY2J,kBAAS,iCAAA,CAAA;EAElB5J,8BAA8B,MAC7Bd,aAAI,MAAM,aAAA;AACf,WAAO,KAAK2E,wBAAuB;EACrC,CAAA,EAAG5D,KAAY8J,gBAAgBC,eAAM,KAAK5K,gBAAgB,CAAA,GAAW6K,eAAM;EAErErH,oBAAoB,CAAC5B,SAA0BC,UAAAA;AACrD,WAAOiJ,wBAAwBlJ,SAASC,KAAAA;EAC1C;AACF;AAKA,IAAMiE,mBAAmB;",
6
- "names": ["Effect", "Schema", "Effect", "Schema", "Obj", "Type", "assertArgument", "make", "Schema", "Obj", "Type", "JsonSchemaType", "LabelAnnotation", "Ref", "Schema", "Obj", "Ref", "Type", "FormAnnotation", "LabelAnnotation", "DataType", "Script", "Struct", "name", "String", "pipe", "optional", "description", "changed", "Boolean", "FormAnnotation", "set", "source", "Type", "Ref", "DataType", "Text", "Obj", "typename", "version", "LabelAnnotation", "make", "props", "makeText", "Function", "Struct", "key", "optional", "String", "annotations", "description", "name", "NonEmptyString", "version", "source", "Ref", "Script", "inputSchema", "JsonSchemaType", "outputSchema", "binding", "pipe", "Type", "Obj", "typename", "LabelAnnotation", "set", "make", "props", "make", "Schema", "SchemaAST", "Obj", "QueryAST", "Type", "Expando", "OptionsAnnotationId", "Ref", "DXN", "Kinds", "kindLiteralAnnotations", "title", "EmailSpec", "Struct", "kind", "Literal", "annotations", "pipe", "mutable", "QueueSpec", "queue", "DXN", "Schema", "SubscriptionSpec", "query", "raw", "optional", "String", "ast", "QueryAST", "Query", "options", "deep", "Boolean", "delay", "Number", "TimerSpec", "cron", "ExamplesAnnotationId", "WebhookSpec", "method", "OptionsAnnotationId", "port", "Spec", "Union", "Trigger_", "function", "Ref", "Expando", "inputNodeId", "enabled", "spec", "input", "Record", "key", "value", "Any", "Type", "Obj", "typename", "version", "Trigger", "make", "props", "Schema", "DXN", "Obj", "Type", "EmailEvent", "mutable", "Struct", "from", "String", "to", "subject", "created", "body", "QueueEvent", "queue", "DXN", "Schema", "item", "Any", "cursor", "SubscriptionEvent", "type", "Type", "Ref", "Obj", "changedObjectId", "optional", "pipe", "TimerEvent", "tick", "Number", "WebhookEvent", "url", "method", "Literal", "headers", "Record", "key", "value", "bodyText", "typeId", "Symbol", "for", "defineFunction", "key", "name", "description", "inputSchema", "outputSchema", "Any", "handler", "isSchema", "Error", "limit", "stackTraceLimit", "traceError", "cache", "captureStackTrace", "stack", "undefined", "split", "trim", "handlerWithSpan", "args", "result", "isEffect", "withSpan", "FunctionDefinition", "make", "isFunction", "value", "serialize", "functionDef", "assertArgument", "serializeFunction", "deserialize", "functionObj", "Obj", "instanceOf", "Function", "deserializeFunction", "fn", "version", "Type", "toJsonSchema", "meta", "deployedFunctionId", "setUserFunctionIdInMetadata", "getMeta", "Unknown", "toEffectSchema", "getUserFunctionIdInMetadata", "defineFunction", "key", "name", "description", "inputSchema", "Struct", "iterations", "optional", "Number", "annotations", "default", "outputSchema", "result", "String", "handler", "fn", "data", "a", "b", "i", "toString", "Console", "Effect", "Schema", "defineFunction", "key", "name", "description", "inputSchema", "Any", "outputSchema", "handler", "fn", "data", "log", "Effect", "Schema", "defineFunction", "key", "name", "description", "inputSchema", "Struct", "duration", "optional", "Number", "annotations", "default", "outputSchema", "Void", "handler", "fn", "data", "sleep", "Example", "fib", "fib$", "reply", "reply$", "sleep", "sleep$", "Effect", "Schema", "runAndForwardErrors", "FunctionExecutor", "_services", "invoke", "functionDef", "input", "assertInput", "inputSchema", "pipe", "asserts", "context", "space", "undefined", "getService", "bind", "getSpace", "_spaceId", "Error", "result", "handler", "data", "isEffect", "provide", "createLayer", "runAndForwardErrors", "assertOutput", "outputSchema", "Context", "Effect", "Layer", "AiService", "Context", "Effect", "Layer", "Schema", "AiService", "todo", "log", "LocalFunctionExecutionService", "Tag", "layerLive", "effect", "gen", "resolver", "FunctionImplementationResolver", "ai", "AiService", "credentials", "CredentialsService", "database", "DatabaseService", "queues", "QueueService", "functionCallService", "RemoteFunctionExecutionService", "invokeFunction", "functionDef", "input", "resolved", "resolveFunctionImplementation", "pipe", "orDie", "output", "provideService", "serviceFunctionEffect", "_", "assertInput", "inputSchema", "asserts", "e", "FunctionError", "message", "context", "name", "cause", "space", "undefined", "getService", "todo", "getSpace", "_spaceId", "Error", "log", "info", "data", "result", "handler", "isEffect", "then", "promise", "catchAllDefect", "defect", "die", "function", "assertOutput", "outputSchema", "withSpan", "attributes", "layerTest", "functions", "succeed", "find", "f", "key", "fail", "FunctionNotFoundError", "FunctionInvocationService", "Tag", "invokeFunction", "serviceFunctionEffect", "_", "layer", "effect", "gen", "localExecutioner", "LocalFunctionExecutionService", "remoteExecutioner", "RemoteFunctionExecutionService", "functionDef", "input", "meta", "deployedFunctionId", "callFunction", "layerTest", "functions", "pipe", "provide", "layerLive", "FunctionImplementationResolver", "layerMock", "layerTestMocked", "AiService", "notAvailable", "CredentialsService", "configuredLayer", "DatabaseService", "QueueService", "Schema", "Type", "ObjectId", "Queue", "log", "InvocationOutcome", "InvocationTraceEventType", "TraceEventException", "Struct", "timestamp", "Number", "message", "String", "name", "stack", "optional", "InvocationTraceStartEvent", "id", "ObjectId", "type", "Literal", "invocationId", "input", "Object", "invocationTraceQueue", "Type", "Ref", "Queue", "invocationTarget", "Expando", "trigger", "Trigger", "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", "duration", "Context", "Effect", "Layer", "Obj", "Ref", "DXN", "ObjectId", "InvocationTracer", "Tag", "layerLive", "opts", "effect", "gen", "traceInvocationStart", "fn", "payload", "target", "invocationId", "ObjectId", "random", "invocationTraceQueue", "QueueService", "createQueue", "subspaceTag", "now", "Date", "traceEvent", "Obj", "make", "InvocationTraceStartEvent", "type", "InvocationTraceEventType", "START", "timestamp", "input", "JSON", "parse", "stringify", "data", "Ref", "fromDXN", "dxn", "invocationTarget", "undefined", "trigger", "DXN", "fromLocalObjectId", "id", "append", "traceInvocationEnd", "trace", "exception", "InvocationTraceEndEvent", "END", "outcome", "InvocationOutcome", "FAILURE", "SUCCESS", "name", "message", "stack", "layerTest", "unwrapEffect", "queue", "Cause", "Context", "Cron", "Duration", "Effect", "Either", "Exit", "Fiber", "Layer", "Option", "Record", "Schedule", "DXN", "Filter", "Obj", "Query", "causeToError", "invariant", "log", "KEY_QUEUE_POSITION", "createInvocationPayload", "trigger", "event", "input", "payload", "key", "value", "Object", "entries", "startsWith", "endsWith", "propertyPath", "slice", "valueSubstitution", "undefined", "pathSegment", "split", "KeyValueStore", "Context", "Effect", "Layer", "Option", "Schema", "ObjectId", "TriggerState", "Struct", "version", "Literal", "triggerId", "String", "state", "optional", "Union", "TaggedStruct", "processedVersions", "Record", "key", "ObjectId", "value", "TriggerStateStore", "Tag", "getState", "serviceFunctionEffect", "_", "saveState", "layerKv", "effect", "gen", "kv", "KeyValueStore", "schemaStore", "forSchema", "parseJson", "store", "fn", "valueOption", "get", "pipe", "orDie", "isNone", "fail", "TriggerStateNotFoundError", "set", "layerMemory", "provide", "TriggerDispatcher", "Tag", "layer", "options", "effect", "gen", "TriggerDispatcherImpl", "livePollInterval", "timeControl", "_running", "_internalTime", "_timerFiber", "_scheduledTriggers", "Map", "seconds", "startingTime", "Date", "running", "start", "_startNaturalTimeProcessing", "pipe", "tapErrorCause", "cause", "error", "causeToError", "log", "void", "forkDaemon", "dieMessage", "info", "stop", "interrupt", "undefined", "clear", "invokeTrigger", "trigger", "event", "triggerId", "id", "spec", "tracer", "InvocationTracer", "trace", "traceInvocationStart", "target", "function", "dxn", "payload", "kind", "data", "result", "enabled", "serialiedFunction", "DatabaseService", "load", "orDie", "invariant", "Obj", "instanceOf", "Function", "functionDef", "deserializeFunction", "inputData", "_prepareInputData", "FunctionInvocationService", "invokeFunction", "provide", "ComputeEventLogger", "layerFromTracing", "provideMerge", "TracingService", "layerQueue", "invocationTraceQueue", "exit", "triggerExecutionResult", "isSuccess", "traceInvocationEnd", "exception", "isFailure", "prettyErrors", "invokeScheduledTriggers", "kinds", "invocations", "refreshTriggers", "now", "getCurrentTime", "triggersToInvoke", "scheduledTrigger", "entries", "nextExecution", "push", "next", "cron", "forEach", "tick", "getTime", "concurrency", "triggers", "_fetchTriggers", "cursor", "getKeys", "KEY_QUEUE_CURSOR", "at", "queue", "QueueService", "getQueue", "DXN", "parse", "objects", "promise", "queryObjects", "object", "objectPos", "KEY_QUEUE_POSITION", "parseInt", "item", "deleteKeys", "getMeta", "keys", "source", "flush", "getSnapshot", "runQuery", "Query", "fromAst", "query", "ast", "state", "TriggerStateStore", "getState", "catchTag", "succeed", "version", "_tag", "processedVersions", "updated", "existingVersion", "get", "map", "decodeVersion", "currentVersion", "run", "isNone", "compareVersions", "value", "db", "type", "subject", "ref", "getDXN", "changedObjectId", "encodeVersion", "saveState", "advanceTime", "duration", "millis", "toMillis", "newTime", "advancedBy", "format", "currentTriggerIds", "Set", "t", "has", "delete", "timerSpec", "cronEither", "isRight", "right", "existing", "set", "left", "message", "count", "size", "withSpan", "Filter", "Trigger", "repeat", "fixed", "asVoid", "createInvocationPayload"]
3
+ "sources": ["../../../src/errors.ts", "../../../src/example/fib.ts", "../../../src/sdk.ts", "../../../src/types/Function.ts", "../../../src/types/Script.ts", "../../../src/types/Trigger.ts", "../../../src/types/TriggerEvent.ts", "../../../src/types/url.ts", "../../../src/example/reply.ts", "../../../src/example/sleep.ts", "../../../src/example/index.ts", "../../../src/services/credentials.ts", "../../../src/services/event-logger.ts", "../../../src/services/tracing.ts", "../../../src/services/function-invocation-service.ts", "../../../src/services/queues.ts", "../../../src/protocol/protocol.ts", "../../../src/protocol/functions-ai-http-client.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2025 DXOS.org\n//\n\nimport { BaseError, type BaseErrorOptions } from '@dxos/errors';\n\nexport class ServiceNotAvailableError extends BaseError.extend('ServiceNotAvailable', 'Service not available') {\n constructor(service: string, options?: Omit<BaseErrorOptions, 'context'>) {\n super({ context: { service }, ...options });\n }\n}\n\nexport class FunctionNotFoundError extends BaseError.extend('FunctionNotFound', 'Function not found') {\n constructor(functionKey: string, options?: Omit<BaseErrorOptions, 'context'>) {\n super({ context: { function: functionKey }, ...options });\n }\n}\n\nexport class FunctionError extends BaseError.extend('FunctionError', 'Function invocation error') {}\n\nexport class TriggerStateNotFoundError extends BaseError.extend('TriggerStateNotFound', 'Trigger state not found') {}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../sdk';\n\nexport default defineFunction({\n key: 'example.org/function/fib',\n name: 'Fibonacci',\n description: 'Function that calculates a Fibonacci number',\n inputSchema: Schema.Struct({\n iterations: Schema.optional(Schema.Number).annotations({\n description: 'Number of iterations',\n default: 100_000,\n }),\n }),\n outputSchema: Schema.Struct({\n result: Schema.String,\n }),\n handler: Effect.fn(function* ({ data: { iterations = 100_000 } }) {\n let a = 0n;\n let b = 1n;\n for (let i = 0; i < iterations; i++) {\n a += b;\n b = a - b;\n }\n return { result: a.toString() };\n }),\n});\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport type * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { type AiService } from '@dxos/ai';\nimport { Obj, Type } from '@dxos/echo';\nimport { type Database } from '@dxos/echo';\nimport { assertArgument, failedInvariant } from '@dxos/invariant';\nimport { Operation } from '@dxos/operation';\n\nimport {\n type CredentialsService,\n type FunctionInvocationService,\n type QueueService,\n type TracingService,\n} from './services';\nimport { Function } from './types';\nimport { getUserFunctionIdInMetadata, setUserFunctionIdInMetadata } from './types';\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 * Services that are provided at the function call site by the caller.\n */\nexport type InvocationServices = TracingService;\n\n/**\n * Services that are available to invoked functions.\n */\nexport type FunctionServices =\n | InvocationServices\n | AiService.AiService\n | CredentialsService\n | Database.Service\n | QueueService\n | FunctionInvocationService;\n\n/**\n * Function handler.\n */\nexport type FunctionHandler<TData = {}, TOutput = any, S extends FunctionServices = FunctionServices> = (params: {\n /**\n * 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, S>;\n\n/**\n * Function context.\n */\nexport interface FunctionContext {\n // TODO(dmaretskyi): Consider what we should put into context.\n}\n\nconst typeId = Symbol.for('@dxos/functions/FunctionDefinition');\n\nexport type FunctionDefinition<T = any, O = any, S extends FunctionServices = FunctionServices> = {\n [typeId]: true;\n key: string;\n name: string;\n description?: string;\n inputSchema: Schema.Schema<T, any>;\n outputSchema?: Schema.Schema<O, any>;\n\n /**\n * List of types the function uses.\n * This is used to ensure that the types are available when the function is executed.\n */\n types: readonly Type.Entity.Any[];\n\n /**\n * Keys of the required services.\n */\n services: readonly string[];\n\n handler: FunctionHandler<T, O, S>;\n meta?: {\n /**\n * Tools that are projected from functions have this annotation.\n *\n * deployedFunctionId:\n * - Backend deployment ID assigned by the EDGE function service (typically a UUID).\n * - Used for remote invocation via `FunctionInvocationService` → `RemoteFunctionExecutionService`.\n * - Persisted on the corresponding ECHO `Function.Function` object's metadata under the\n * `FUNCTIONS_META_KEY` and retrieved with `getUserFunctionIdInMetadata`.\n */\n deployedFunctionId?: string;\n };\n};\n\nexport declare namespace FunctionDefinition {\n export type Any = FunctionDefinition<any, any, any>;\n export type Input<T extends Any> = T extends FunctionDefinition<infer I, infer _O, infer _S> ? I : never;\n export type Output<T extends Any> = T extends FunctionDefinition<infer _I, infer O, infer _S> ? O : never;\n export type Services<T extends Any> = T extends FunctionDefinition<infer _I, infer _O, infer S> ? S : never;\n}\n\nexport type FunctionProps<T, O> = {\n key: string;\n name: string;\n description?: string;\n inputSchema: Schema.Schema<T, any>;\n outputSchema?: Schema.Schema<O, any>;\n\n /**\n * List of types the function uses.\n * This is used to ensure that the types are available when the function is executed.\n */\n types?: readonly Type.Entity.Any[];\n // TODO(dmaretskyi): This currently doesn't cause a compile-time error if the handler requests a service that is not specified\n services?: readonly Context.Tag<any, any>[];\n\n handler: FunctionHandler<T, O, FunctionServices>;\n};\n\n// TODO(dmaretskyi): Output type doesn't get typechecked.\nexport const defineFunction: {\n <I, O>(params: FunctionProps<I, O>): FunctionDefinition<I, O, FunctionServices>;\n} = ({ key, name, description, inputSchema, outputSchema = Schema.Any, handler, types, services }) => {\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 // Captures the function definition location.\n const limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 2;\n const traceError = new Error();\n Error.stackTraceLimit = limit;\n let cache: false | string = false;\n const captureStackTrace = () => {\n if (cache !== false) {\n return cache;\n }\n if (traceError.stack !== undefined) {\n const stack = traceError.stack.split('\\n');\n if (stack[2] !== undefined) {\n cache = stack[2].trim();\n return cache;\n }\n }\n };\n\n const handlerWithSpan = (...args: any[]) => {\n const result = (handler as any)(...args);\n if (Effect.isEffect(result)) {\n return Effect.withSpan(result, `${key ?? name}`, {\n captureStackTrace,\n });\n }\n return result;\n };\n\n return {\n [typeId]: true,\n key,\n name,\n description,\n inputSchema,\n outputSchema,\n handler: handlerWithSpan,\n types: types ?? [],\n services: !services ? [] : getServiceKeys(services),\n } satisfies FunctionDefinition.Any;\n};\n\nconst getServiceKeys = (services: readonly Context.Tag<any, any>[]) => {\n return services.map((tag: any) => {\n if (typeof tag.key === 'string') {\n return tag.key;\n }\n failedInvariant();\n });\n};\n\n/**\n * Converts a FunctionDefinition to an OperationDefinition with handler.\n * The function handler is adapted to the OperationHandler format.\n *\n * Note: FunctionDefinition stores service keys as strings, not Tag types,\n * so we can't use Operation.withHandler's type inference here.\n */\nexport const toOperation = <T, O, S extends FunctionServices = FunctionServices>(\n functionDef: FunctionDefinition<T, O, S>,\n): Operation.Definition<T, O> & { handler: Operation.Handler<T, O, any, S> } => {\n const op = Operation.make({\n schema: {\n input: functionDef.inputSchema,\n output: functionDef.outputSchema ?? Schema.Any,\n },\n meta: {\n key: functionDef.key,\n name: functionDef.name,\n description: functionDef.description,\n },\n });\n\n // Adapt FunctionHandler signature to OperationHandler format.\n // FunctionHandler expects { context, data }, OperationHandler expects just input.\n const operationHandler: Operation.Handler<T, O, any, S> = (input: T) => {\n const result = functionDef.handler({\n context: {} as FunctionContext,\n data: input,\n });\n\n // Convert Promise or plain value to Effect.\n if (Effect.isEffect(result)) {\n return result;\n }\n if (result instanceof Promise) {\n return Effect.tryPromise(() => result);\n }\n return Effect.succeed(result as O);\n };\n\n // Manually attach handler since FunctionDefinition stores service keys as strings,\n // not Tag types, so withHandler's type inference doesn't apply.\n return {\n ...op,\n handler: operationHandler,\n };\n};\n\nexport const FunctionDefinition = {\n make: defineFunction,\n isFunction: (value: unknown): value is FunctionDefinition.Any => {\n return typeof value === 'object' && value !== null && Symbol.for('@dxos/functions/FunctionDefinition') in value;\n },\n serialize: (functionDef: FunctionDefinition.Any): Function.Function => {\n assertArgument(FunctionDefinition.isFunction(functionDef), 'functionDef');\n return serializeFunction(functionDef);\n },\n deserialize: (functionObj: Function.Function): FunctionDefinition.Any => {\n assertArgument(Obj.instanceOf(Function.Function, functionObj), 'functionObj');\n return deserializeFunction(functionObj);\n },\n toOperation,\n};\n\nexport const serializeFunction = (functionDef: FunctionDefinition.Any): Function.Function => {\n const fn = Function.make({\n key: functionDef.key,\n name: functionDef.name,\n version: '0.1.0',\n description: functionDef.description,\n inputSchema: Type.toJsonSchema(functionDef.inputSchema),\n outputSchema: !functionDef.outputSchema ? undefined : Type.toJsonSchema(functionDef.outputSchema),\n services: functionDef.services,\n });\n if (functionDef.meta?.deployedFunctionId) {\n Obj.change(fn, (fn) => setUserFunctionIdInMetadata(Obj.getMeta(fn), functionDef.meta!.deployedFunctionId!));\n }\n return fn;\n};\n\nexport const deserializeFunction = (functionObj: Function.Function): FunctionDefinition<unknown, unknown> => {\n return {\n [typeId]: true,\n // TODO(dmaretskyi): Fix key.\n key: functionObj.key ?? functionObj.name,\n name: functionObj.name,\n description: functionObj.description,\n inputSchema: !functionObj.inputSchema ? Schema.Unknown : Type.toEffectSchema(functionObj.inputSchema),\n outputSchema: !functionObj.outputSchema ? undefined : Type.toEffectSchema(functionObj.outputSchema),\n // TODO(dmaretskyi): This should throw error.\n handler: () => {},\n services: functionObj.services ?? [],\n types: [],\n meta: {\n deployedFunctionId: getUserFunctionIdInMetadata(Obj.getMeta(functionObj)),\n },\n };\n};\n", "//\n// Copyright 2024 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, JsonSchema, Obj, Type } from '@dxos/echo';\nimport { SystemTypeAnnotation } from '@dxos/echo/internal';\n\nimport { Script } from './Script';\n\n/**\n * Function deployment.\n */\nexport const Function = Schema.Struct({\n /**\n * Global registry ID.\n * NOTE: The `key` property refers to the original registry entry.\n */\n // TODO(burdon): Create Format type for DXN-like ids, such as this and schema type.\n // TODO(dmaretskyi): Consider making it part of ECHO meta.\n // TODO(dmaretskyi): Make required.\n key: Schema.optional(Schema.String).annotations({\n description: 'Unique registration key for the blueprint',\n }),\n\n name: Schema.NonEmptyString,\n version: Schema.String,\n\n description: Schema.optional(Schema.String),\n\n /**\n * ISO date string of the last deployment.\n */\n updated: 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(Type.Ref(Script)),\n\n inputSchema: Schema.optional(JsonSchema.JsonSchema),\n outputSchema: Schema.optional(JsonSchema.JsonSchema),\n\n /**\n * List of required services.\n * Match the Context.Tag keys of the FunctionServices variants.\n */\n services: Schema.optional(Schema.Array(Schema.String)),\n\n // Local binding to a function name.\n binding: Schema.optional(Schema.String),\n}).pipe(\n Type.object({\n typename: 'dxos.org/type/Function',\n version: '0.1.0',\n }),\n Annotation.LabelAnnotation.set(['name']),\n SystemTypeAnnotation.set(true),\n);\n\nexport interface Function extends Schema.Schema.Type<typeof Function> {}\n\nexport const make = (props: Obj.MakeProps<typeof Function>) => Obj.make(Function, props);\n\n/**\n * Copies properties from source to target.\n * @param target - Target object to copy properties to.\n * @param source - Source object to copy properties from.\n */\nexport const setFrom = (target: Function, source: Function) => {\n Obj.change(target, (t) => {\n t.key = source.key ?? target.key;\n t.name = source.name ?? target.name;\n t.version = source.version;\n t.description = source.description;\n t.updated = source.updated;\n // TODO(dmaretskyi): A workaround for an ECHO bug.\n t.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;\n t.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;\n Obj.getMeta(t).keys = JSON.parse(JSON.stringify(Obj.getMeta(source).keys));\n });\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation, Obj, Ref, Type } from '@dxos/echo';\nimport { FormInputAnnotation } from '@dxos/echo/internal';\nimport { Text } from '@dxos/schema';\n\n/**\n * Source script.\n */\nexport const Script = Schema.Struct({\n name: Schema.String.pipe(Schema.optional),\n description: Schema.String.pipe(Schema.optional),\n // TODO(burdon): Change to hash of deployed content.\n // Whether source has changed since last deploy.\n changed: Schema.Boolean.pipe(FormInputAnnotation.set(false), Schema.optional),\n source: Type.Ref(Text.Text).pipe(FormInputAnnotation.set(false)),\n}).pipe(\n Type.object({\n typename: 'dxos.org/type/Script',\n version: '0.1.0',\n }),\n Annotation.LabelAnnotation.set(['name']),\n);\n\nexport interface Script extends Schema.Schema.Type<typeof Script> {}\n\ntype Props = Omit<Obj.MakeProps<typeof Script>, 'source'> & { source?: string };\n\nexport const make = ({ source = '', ...props }: Props = {}): Script =>\n Obj.make(Script, { ...props, source: Ref.make(Text.make(source)) });\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { Obj, QueryAST, Type } from '@dxos/echo';\nimport { OptionsAnnotationId, SystemTypeAnnotation } from '@dxos/echo/internal';\nimport { DXN } from '@dxos/keys';\nimport { Expando } from '@dxos/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 const Kinds = ['email', 'queue', 'subscription', 'timer', 'webhook'] as const;\nexport type Kind = (typeof Kinds)[number];\n\nconst kindLiteralAnnotations = { title: 'Kind' };\n\nexport const EmailSpec = Schema.Struct({\n kind: Schema.Literal('email').annotations(kindLiteralAnnotations),\n});\nexport type EmailSpec = Schema.Schema.Type<typeof EmailSpec>;\n\nexport const QueueSpec = Schema.Struct({\n kind: Schema.Literal('queue').annotations(kindLiteralAnnotations),\n\n // TODO(dmaretskyi): Change to a reference.\n queue: DXN.Schema,\n});\nexport type QueueSpec = Schema.Schema.Type<typeof QueueSpec>;\n\n/**\n * Subscription.\n */\nexport const SubscriptionSpec = Schema.Struct({\n kind: Schema.Literal('subscription').annotations(kindLiteralAnnotations),\n query: Schema.Struct({\n raw: Schema.optional(Schema.String.annotations({ title: 'Query' })),\n ast: QueryAST.Query,\n }),\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});\nexport type SubscriptionSpec = Schema.Schema.Type<typeof SubscriptionSpec>;\n\n/**\n * Cron timer.\n */\nexport const TimerSpec = Schema.Struct({\n kind: Schema.Literal('timer').annotations(kindLiteralAnnotations),\n cron: Schema.String.annotations({\n title: 'Cron',\n [SchemaAST.ExamplesAnnotationId]: ['0 0 * * *'],\n }),\n});\nexport type TimerSpec = Schema.Schema.Type<typeof TimerSpec>;\n\n/**\n * Webhook.\n */\nexport const WebhookSpec = Schema.Struct({\n kind: Schema.Literal('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});\nexport type WebhookSpec = Schema.Schema.Type<typeof WebhookSpec>;\n\n/**\n * Trigger schema.\n */\nexport const Spec = Schema.Union(EmailSpec, QueueSpec, SubscriptionSpec, TimerSpec, WebhookSpec).annotations({\n title: 'Trigger',\n});\nexport type Spec = Schema.Schema.Type<typeof Spec>;\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 */\nconst TriggerSchema = 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(Type.Ref(Expando.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 // TODO(burdon): NO BOOLEAN PROPERTIES (enabld/disabled/paused, etc.)\n // Need lint rule; or agent rule to require PR review for \"boolean\" key word.\n enabled: Schema.optional(Schema.Boolean.annotations({ title: 'Enabled' })),\n\n spec: Schema.optional(Spec),\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.Record({ key: Schema.String, value: Schema.Any })),\n}).pipe(\n Type.object({\n typename: 'dxos.org/type/Trigger',\n version: '0.1.0',\n }),\n SystemTypeAnnotation.set(true),\n);\n\nexport interface Trigger extends Schema.Schema.Type<typeof TriggerSchema> {}\nexport const Trigger: Type.Obj<Trigger> = TriggerSchema as any;\n\nexport const make = (props: Obj.MakeProps<typeof Trigger>) => Obj.make(Trigger, props);\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { DXN, Type } from '@dxos/echo';\n\n// TODO(wittjosiah): Review this type.\n// - Should be discriminated union.\n// - Should be more consistent (e.g. subject vs item).\n// - Should re-use schemas if possible.\n\n// TODO(burdon): Reuse trigger schema from @dxos/functions (TriggerType).\nexport const EmailEvent = Schema.Struct({\n from: Schema.String,\n to: Schema.String,\n subject: Schema.String,\n created: Schema.String,\n body: Schema.String,\n});\nexport type EmailEvent = Schema.Schema.Type<typeof EmailEvent>;\n\nexport const QueueEvent = Schema.Struct({\n queue: DXN.Schema,\n item: Schema.Any,\n cursor: Schema.String,\n});\nexport type QueueEvent = Schema.Schema.Type<typeof QueueEvent>;\n\nexport const SubscriptionEvent = Schema.Struct({\n /**\n * Type of the mutation.\n */\n // TODO(dmaretskyi): Specify enum.\n type: Schema.String,\n\n /**\n * Reference to the object that was changed or created.\n */\n subject: Type.Ref(Type.Obj),\n\n /**\n * @deprecated\n */\n changedObjectId: Schema.optional(Schema.String),\n});\nexport type SubscriptionEvent = Schema.Schema.Type<typeof SubscriptionEvent>;\n\nexport const TimerEvent = Schema.Struct({ tick: Schema.Number });\nexport type TimerEvent = Schema.Schema.Type<typeof TimerEvent>;\n\nexport const WebhookEvent = 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});\nexport type WebhookEvent = Schema.Schema.Type<typeof WebhookEvent>;\n\nexport const TriggerEvent = Schema.Union(EmailEvent, QueueEvent, SubscriptionEvent, TimerEvent, WebhookEvent);\nexport type TriggerEvent = Schema.Schema.Type<typeof TriggerEvent>;\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { type Obj } from '@dxos/echo';\n\n// TODO: use URL scheme for source?\nexport const FUNCTIONS_META_KEY = 'dxos.org/service/function';\n\nexport const FUNCTIONS_PRESET_META_KEY = 'dxos.org/service/function-preset';\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n */\nexport const getUserFunctionIdInMetadata = (meta: Obj.ReadonlyMeta) => {\n return meta.keys.find((key) => key.source === FUNCTIONS_META_KEY)?.id;\n};\n\n/**\n * NOTE: functionId is backend ID, not ECHO object id.\n * Must be called inside Obj.changeMeta() since it mutates the meta.\n */\nexport const setUserFunctionIdInMetadata = (meta: Obj.Meta, functionId: string) => {\n const key = meta.keys.find((key) => key.source === FUNCTIONS_META_KEY);\n if (key) {\n if (key.id !== functionId) {\n throw new Error('Metadata mismatch');\n }\n } else {\n meta.keys.push({ source: FUNCTIONS_META_KEY, id: functionId });\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../sdk';\n\nexport default defineFunction({\n key: 'example.org/function/reply',\n name: 'Reply',\n description: 'Function that echoes the input',\n inputSchema: Schema.Any,\n outputSchema: Schema.Any,\n handler: Effect.fn(function* ({ data }) {\n yield* Console.log('reply', { data });\n return data;\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\n\nimport { defineFunction } from '../sdk';\n\nexport default defineFunction({\n key: 'example.org/function/sleep',\n name: 'Sleep',\n description: 'Function that sleeps for a given amount of time',\n inputSchema: Schema.Struct({\n duration: Schema.optional(Schema.Number).annotations({\n description: 'Milliseconds to sleep',\n default: 100_000,\n }),\n }),\n outputSchema: Schema.Void,\n handler: Effect.fn(function* ({ data: { duration = 100_000 } }) {\n yield* Effect.sleep(duration);\n }),\n});\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport { default as fib$ } from './fib';\nimport { default as reply$ } from './reply';\nimport { default as sleep$ } from './sleep';\n\nexport namespace Example {\n export const fib = fib$;\n export const reply = reply$;\n export const sleep = sleep$;\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientRequest from '@effect/platform/HttpClientRequest';\nimport type * as Config from 'effect/Config';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Redacted from 'effect/Redacted';\n\nimport { Query } from '@dxos/echo';\nimport { Database } from '@dxos/echo';\nimport { AccessToken } from '@dxos/types';\n\nexport type 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 getApiKey = (query: CredentialQuery): Effect.Effect<Redacted.Redacted<string>, never, CredentialsService> =>\n Effect.gen(function* () {\n const credential = yield* CredentialsService.getCredential(query);\n if (!credential.apiKey) {\n throw new Error(`API key not found for service: ${query.service}`);\n }\n return Redacted.make(credential.apiKey);\n });\n\n static configuredLayer = (credentials: ServiceCredential[]) =>\n Layer.succeed(CredentialsService, new ConfiguredCredentialsService(credentials));\n\n static layerConfig = (\n credentials: {\n service: string;\n apiKey: Config.Config<Redacted.Redacted<string>>;\n }[],\n ) =>\n Layer.effect(\n CredentialsService,\n Effect.gen(function* () {\n const serviceCredentials = yield* Effect.forEach(credentials, ({ service, apiKey }) =>\n Effect.gen(function* () {\n return {\n service,\n apiKey: Redacted.value(yield* apiKey),\n };\n }),\n );\n\n return new ConfiguredCredentialsService(serviceCredentials);\n }),\n );\n\n static layerFromDatabase = ({ caching = false }: { caching?: boolean } = {}) =>\n Layer.effect(\n CredentialsService,\n Effect.gen(function* () {\n const dbService = yield* Database.Service;\n const cache = new Map<string, ServiceCredential[]>();\n\n const queryCredentials = async (query: CredentialQuery): Promise<ServiceCredential[]> => {\n const cacheKey = JSON.stringify(query);\n if (caching && cache.has(cacheKey)) {\n return cache.get(cacheKey)!;\n }\n\n const accessTokens = await dbService.db.query(Query.type(AccessToken.AccessToken)).run();\n const credentials = accessTokens\n .filter((accessToken) => accessToken.source === query.service)\n .map((accessToken) => ({\n service: accessToken.source,\n apiKey: accessToken.token,\n }));\n\n if (caching) {\n cache.set(cacheKey, credentials);\n }\n\n return credentials;\n };\n\n return {\n getCredential: async (query) => {\n const credentials = await queryCredentials(query);\n if (credentials.length === 0) {\n throw new Error(`Credential not found for service: ${query.service}`);\n }\n\n return credentials[0];\n },\n queryCredentials: async (query) => {\n return queryCredentials(query);\n },\n };\n }),\n );\n}\n\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\n return credential;\n }\n}\n\n/**\n * Maps the request to include the given token in the Authorization header.\n */\nexport const withAuthorization = (token: string, kind?: 'Bearer' | 'Basic') =>\n HttpClient.mapRequest((request) => {\n const authorization = kind ? `${kind} ${token}` : token;\n return HttpClientRequest.setHeader(request, 'Authorization', authorization);\n });\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\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 /**\n * Names of the inputs begin computed.\n */\n inputs: Schema.Array(Schema.String),\n }),\n Schema.Struct({\n type: Schema.Literal('end-compute'),\n nodeId: Schema.String,\n /**\n * Names of the outputs computed.\n */\n outputs: Schema.Array(Schema.String),\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.object({ 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 }), tracing.getTraceContext());\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 * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { AgentStatus } from '@dxos/ai';\nimport { type DXN, Obj } from '@dxos/echo';\nimport { ObjectId } from '@dxos/keys';\nimport { Message } from '@dxos/types';\n\nimport type { Trigger } from '../types';\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 * Gets the parent message ID.\n */\n getTraceContext: () => TracingService.TraceContext;\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: Obj.Unknown, traceContext: TracingService.TraceContext) => void;\n\n traceInvocationStart({\n payload,\n target,\n }: {\n payload: TracingService.FunctionInvocationPayload;\n target?: DXN;\n }): Effect.Effect<TracingService.InvocationTraceData>;\n\n traceInvocationEnd({\n trace,\n exception,\n }: {\n trace: TracingService.InvocationTraceData;\n exception?: any;\n }): Effect.Effect<void>;\n }\n>() {\n static noop: Context.Tag.Service<TracingService> = {\n getTraceContext: () => ({}),\n write: () => {},\n traceInvocationStart: () =>\n Effect.sync(() => ({ invocationId: ObjectId.random(), invocationTraceQueue: undefined })),\n traceInvocationEnd: () => Effect.sync(() => {}),\n };\n\n static layerNoop: Layer.Layer<TracingService> = Layer.succeed(TracingService, TracingService.noop);\n\n /**\n * Creates a TracingService layer that emits events to the parent tracing service.\n */\n static layerSubframe = (mapContext: (currentContext: TracingService.TraceContext) => TracingService.TraceContext) =>\n Layer.effect(\n TracingService,\n Effect.gen(function* () {\n const tracing = yield* TracingService;\n const context = mapContext(tracing.getTraceContext());\n return {\n write: (event, context) => tracing.write(event, context),\n getTraceContext: () => context,\n traceInvocationStart: () => Effect.die('Tracing invocation inside another invocation is not supported.'),\n traceInvocationEnd: () => Effect.die('Tracing invocation inside another invocation is not supported.'),\n };\n }),\n );\n\n /**\n * Create sublayer to trace an invocation.\n * @param data\n * @returns\n */\n static layerInvocation = (data: TracingService.InvocationTraceData) =>\n TracingService.layerSubframe((context) => ({\n ...context,\n currentInvocation: data,\n }));\n\n /**\n * Emit the current human-readable execution status.\n */\n static emitStatus: (\n data: Omit<Obj.MakeProps<typeof AgentStatus>, 'created'>,\n ) => Effect.Effect<void, never, TracingService> = Effect.fnUntraced(function* (data) {\n const tracing = yield* TracingService;\n tracing.write(\n Obj.make(AgentStatus, {\n parentMessage: tracing.getTraceContext().parentMessage,\n toolCallId: tracing.getTraceContext().toolCallId,\n created: new Date().toISOString(),\n ...data,\n }),\n tracing.getTraceContext(),\n );\n });\n\n static emitConverationMessage: (\n data: Obj.MakeProps<typeof Message.Message>,\n ) => Effect.Effect<void, never, TracingService> = Effect.fnUntraced(function* (data) {\n const tracing = yield* TracingService;\n tracing.write(\n Obj.make(Message.Message, {\n parentMessage: tracing.getTraceContext().parentMessage,\n ...data,\n properties: {\n [MESSAGE_PROPERTY_TOOL_CALL_ID]: tracing.getTraceContext().toolCallId,\n ...data.properties,\n },\n }),\n tracing.getTraceContext(),\n );\n });\n}\n\nexport namespace TracingService {\n export interface TraceContext {\n currentInvocation?: InvocationTraceData;\n\n /**\n * If this thread sprung from a tool call, this is the ID of the message containing the tool call.\n */\n parentMessage?: ObjectId;\n\n /**\n * If the current thread is a byproduct of a tool call, this is the ID of the tool call.\n */\n toolCallId?: string;\n\n debugInfo?: unknown;\n }\n\n /**\n * Trace data for a function/trigger invocation.\n */\n export interface InvocationTraceData {\n invocationId: ObjectId;\n invocationTraceQueue?: DXN.String;\n }\n\n /**\n * Payload for a function/trigger invocation.\n */\n export interface FunctionInvocationPayload {\n data?: any;\n inputNodeId?: string;\n trigger?: {\n id: string;\n kind: Trigger.Kind;\n };\n }\n}\n\n/**\n * Goes into {@link Message['properties']}\n */\nexport const MESSAGE_PROPERTY_TOOL_CALL_ID = 'toolCallId' as const;\n", "//\n// Copyright 2025 DXOS.org\n//\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport type { FunctionNotFoundError } from '../errors';\nimport { type FunctionDefinition, type InvocationServices } from '../sdk';\n\nexport class FunctionInvocationService extends Context.Tag('@dxos/functions/FunctionInvocationService')<\n FunctionInvocationService,\n {\n invokeFunction<I, O>(\n functionDef: FunctionDefinition<I, O, any>,\n input: I,\n ): Effect.Effect<O, never, InvocationServices>;\n\n resolveFunction(key: string): Effect.Effect<FunctionDefinition.Any, FunctionNotFoundError>;\n }\n>() {\n static layerNotAvailable = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('FunctionInvocationService is not avaialble.'),\n resolveFunction: () => Effect.die('FunctionInvocationService is not available.'),\n });\n\n static invokeFunction = <I, O>(\n functionDef: FunctionDefinition<I, O, any>,\n input: I,\n ): Effect.Effect<O, never, FunctionInvocationService | InvocationServices> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.invokeFunction)(functionDef, input);\n\n static resolveFunction = (\n key: string,\n ): Effect.Effect<FunctionDefinition.Any, FunctionNotFoundError, FunctionInvocationService> =>\n Effect.serviceFunctionEffect(FunctionInvocationService, (service) => service.resolveFunction)(key);\n}\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport type { Entity } 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 Entity.Unknown = Entity.Unknown>(\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 Entity.Unknown = Entity.Unknown>(options?: {\n subspaceTag?: QueueSubspaceTag;\n }): Effect.Effect<Queue<T>, never, QueueService> =>\n QueueService.pipe(Effect.map(({ queues }) => queues.create<T>(options)));\n\n static append = <T extends Entity.Unknown = Entity.Unknown>(queue: Queue<T>, objects: T[]): Effect.Effect<void> =>\n Effect.promise(() => queue.append(objects));\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 * as AnthropicClient from '@effect/ai-anthropic/AnthropicClient';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Schema from 'effect/Schema';\nimport * as SchemaAST from 'effect/SchemaAST';\n\nimport { AiModelResolver, AiService } from '@dxos/ai';\nimport { AnthropicResolver } from '@dxos/ai/resolvers';\nimport { LifecycleState, Resource } from '@dxos/context';\nimport { Database, Ref, Type } from '@dxos/echo';\nimport { refFromEncodedReference } from '@dxos/echo/internal';\nimport { EchoClient, type EchoDatabaseImpl, type QueueFactory } from '@dxos/echo-db';\nimport { runAndForwardErrors } from '@dxos/effect';\nimport { assertState, failedInvariant, invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { type FunctionProtocol } from '@dxos/protocols';\n\nimport { FunctionError } from '../errors';\nimport { FunctionDefinition, type FunctionServices } from '../sdk';\nimport { CredentialsService, FunctionInvocationService, QueueService, TracingService } from '../services';\n\nimport { FunctionsAiHttpClient } from './functions-ai-http-client';\n\n/**\n * Wraps a function handler made with `defineFunction` to a protocol that the functions-runtime expects.\n */\nexport const wrapFunctionHandler = (func: FunctionDefinition): FunctionProtocol.Func => {\n if (!FunctionDefinition.isFunction(func)) {\n throw new TypeError('Invalid function definition');\n }\n\n return {\n meta: {\n key: func.key,\n name: func.name,\n description: func.description,\n inputSchema: Type.toJsonSchema(func.inputSchema),\n outputSchema: func.outputSchema === undefined ? undefined : Type.toJsonSchema(func.outputSchema),\n services: func.services,\n },\n handler: async ({ data, context }) => {\n if (\n (func.services.includes(Database.Service.key) || func.services.includes(QueueService.key)) &&\n (!context.services.dataService || !context.services.queryService)\n ) {\n throw new FunctionError({\n message: 'Services not provided: dataService, queryService',\n });\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (!SchemaAST.isAnyKeyword(func.inputSchema.ast)) {\n try {\n Schema.validateSync(func.inputSchema)(data);\n } catch (error) {\n throw new FunctionError({ message: 'Invalid input schema', cause: error });\n }\n }\n\n await using funcContext = await new FunctionContext(context).open();\n\n if (func.types.length > 0) {\n invariant(funcContext.db, 'Database is required for functions with types');\n await funcContext.db.graph.schemaRegistry.register(func.types as Type.Entity.Any[]);\n }\n\n const dataWithDecodedRefs =\n funcContext.db && !SchemaAST.isAnyKeyword(func.inputSchema.ast)\n ? decodeRefsFromSchema(func.inputSchema.ast, data, funcContext.db)\n : data;\n\n let result = await func.handler({\n // TODO(dmaretskyi): Fix the types.\n context: context as any,\n data: dataWithDecodedRefs,\n });\n\n if (Effect.isEffect(result)) {\n result = await runAndForwardErrors(\n (result as Effect.Effect<unknown, unknown, FunctionServices>).pipe(\n Effect.orDie,\n Effect.provide(funcContext.createLayer()),\n ),\n );\n }\n\n if (func.outputSchema && !SchemaAST.isAnyKeyword(func.outputSchema.ast)) {\n Schema.validateSync(func.outputSchema)(result);\n }\n\n return result;\n } catch (error) {\n // TODO(dmaretskyi): We might do error wrapping here and add extra context.\n throw error;\n }\n },\n };\n};\n\n/**\n * Container for services and context for a function.\n */\nclass FunctionContext extends Resource {\n readonly context: FunctionProtocol.Context;\n readonly client: EchoClient | undefined;\n db: EchoDatabaseImpl | undefined;\n queues: QueueFactory | undefined;\n\n constructor(context: FunctionProtocol.Context) {\n super();\n this.context = context;\n if (context.services.dataService && context.services.queryService) {\n this.client = new EchoClient().connectToService({\n dataService: context.services.dataService,\n queryService: context.services.queryService,\n queueService: context.services.queueService,\n });\n }\n }\n\n override async _open() {\n await this.client?.open();\n this.db =\n this.client && this.context.spaceId\n ? this.client.constructDatabase({\n spaceId: this.context.spaceId ?? failedInvariant(),\n spaceKey: PublicKey.fromHex(this.context.spaceKey ?? failedInvariant('spaceKey missing in context')),\n reactiveSchemaQuery: false,\n preloadSchemaOnOpen: false,\n })\n : undefined;\n\n await this.db?.setSpaceRoot(this.context.spaceRootUrl ?? failedInvariant('spaceRootUrl missing in context'));\n await this.db?.open();\n this.queues =\n this.client && this.context.spaceId ? this.client.constructQueueFactory(this.context.spaceId) : undefined;\n }\n\n override async _close() {\n await this.db?.close();\n await this.client?.close();\n }\n\n createLayer(): Layer.Layer<FunctionServices> {\n assertState(this._lifecycleState === LifecycleState.OPEN, 'FunctionContext is not open');\n\n const dbLayer = this.db ? Database.Service.layer(this.db) : Database.Service.notAvailable;\n const queuesLayer = this.queues ? QueueService.layer(this.queues) : QueueService.notAvailable;\n const credentials = dbLayer\n ? CredentialsService.layerFromDatabase({ caching: true }).pipe(Layer.provide(dbLayer))\n : CredentialsService.configuredLayer([]);\n const functionInvocationService = MockedFunctionInvocationService;\n const tracing = TracingService.layerNoop;\n\n const aiLayer = this.context.services.functionsAiService\n ? AiModelResolver.AiModelResolver.buildAiService.pipe(\n Layer.provide(\n AnthropicResolver.make().pipe(\n Layer.provide(\n AnthropicClient.layer({\n // Note: It doesn't matter what is base url here, it will be proxied to ai gateway in edge.\n apiUrl: 'http://internal/provider/anthropic',\n }).pipe(Layer.provide(FunctionsAiHttpClient.layer(this.context.services.functionsAiService))),\n ),\n ),\n ),\n )\n : AiService.notAvailable;\n\n return Layer.mergeAll(\n dbLayer, //\n queuesLayer,\n credentials,\n functionInvocationService,\n aiLayer,\n tracing,\n );\n }\n}\n\nconst MockedFunctionInvocationService = Layer.succeed(FunctionInvocationService, {\n invokeFunction: () => Effect.die('Calling functions from functions is not implemented yet.'),\n resolveFunction: () => Effect.die('Not implemented.'),\n});\n\nconst decodeRefsFromSchema = (ast: SchemaAST.AST, value: unknown, db: EchoDatabaseImpl): unknown => {\n if (value == null) {\n return value;\n }\n\n const encoded = SchemaAST.encodedBoundAST(ast);\n if (Ref.isRefType(encoded)) {\n if (Ref.isRef(value)) {\n return value;\n }\n\n if (typeof value === 'object' && value !== null && typeof (value as any)['/'] === 'string') {\n const resolver = db.graph.createRefResolver({ context: { space: db.spaceId } });\n return refFromEncodedReference(value as any, resolver);\n }\n\n return value;\n }\n\n switch (encoded._tag) {\n case 'TypeLiteral': {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return value;\n }\n const result: Record<string, unknown> = { ...(value as any) };\n for (const prop of SchemaAST.getPropertySignatures(encoded)) {\n const key = prop.name.toString();\n if (key in result) {\n result[key] = decodeRefsFromSchema(prop.type, (result as any)[key], db);\n }\n }\n return result;\n }\n\n case 'TupleType': {\n if (!Array.isArray(value)) {\n return value;\n }\n\n // For arrays, effect uses TupleType with empty elements and a single rest element.\n if (encoded.elements.length === 0 && encoded.rest.length === 1) {\n const elementType = encoded.rest[0].type;\n return (value as unknown[]).map((item) => decodeRefsFromSchema(elementType, item, db));\n }\n\n return value;\n }\n\n case 'Union': {\n // Optional values are represented as union with undefined.\n const nonUndefined = encoded.types.filter((t) => !SchemaAST.isUndefinedKeyword(t));\n if (nonUndefined.length === 1) {\n return decodeRefsFromSchema(nonUndefined[0], value, db);\n }\n\n // For other unions we can't safely pick a branch without validating.\n return value;\n }\n\n case 'Suspend': {\n return decodeRefsFromSchema(encoded.f(), value, db);\n }\n\n case 'Refinement': {\n return decodeRefsFromSchema(encoded.from, value, db);\n }\n\n default: {\n return value;\n }\n }\n};\n", "//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Headers from '@effect/platform/Headers';\nimport * as HttpClient from '@effect/platform/HttpClient';\nimport * as HttpClientError from '@effect/platform/HttpClientError';\nimport * as HttpClientResponse from '@effect/platform/HttpClientResponse';\nimport * as Effect from 'effect/Effect';\nimport * as FiberRef from 'effect/FiberRef';\nimport * as Layer from 'effect/Layer';\nimport * as Stream from 'effect/Stream';\n\nimport { log } from '@dxos/log';\nimport { type EdgeFunctionEnv, ErrorCodec } from '@dxos/protocols';\n/**\n * Copy pasted from https://github.com/Effect-TS/effect/blob/main/packages/platform/src/internal/fetchHttpClient.ts\n */\nexport const requestInitTagKey = '@effect/platform/FetchHttpClient/FetchOptions';\n\nexport class FunctionsAiHttpClient {\n static make = (service: EdgeFunctionEnv.FunctionsAiService) =>\n HttpClient.make((request, url, signal, fiber) => {\n const context = fiber.getFiberRef(FiberRef.currentContext);\n const options: RequestInit = context.unsafeMap.get(requestInitTagKey) ?? {};\n const headers = options.headers\n ? Headers.merge(Headers.fromInput(options.headers), request.headers)\n : request.headers;\n\n const send = (body: BodyInit | undefined) =>\n Effect.tryPromise({\n try: () =>\n service.fetch(\n new Request(url, {\n ...options,\n method: request.method,\n headers,\n body,\n // Note: Don't pass signal - it can't be serialized through RPC\n }),\n ),\n catch: (cause) => {\n log.error('Failed to fetch', { errorSerialized: ErrorCodec.encode(cause as Error) });\n return new HttpClientError.RequestError({\n request,\n reason: 'Transport',\n cause,\n });\n },\n }).pipe(Effect.map((response) => HttpClientResponse.fromWeb(request, response)));\n\n switch (request.body._tag) {\n case 'Raw':\n case 'Uint8Array':\n return send(request.body.body as any);\n case 'FormData':\n return send(request.body.formData);\n case 'Stream':\n return Stream.toReadableStreamEffect(request.body.stream).pipe(Effect.flatMap(send));\n }\n\n return send(undefined);\n });\n\n static layer = (service: EdgeFunctionEnv.FunctionsAiService) =>\n Layer.succeed(HttpClient.HttpClient, FunctionsAiHttpClient.make(service));\n}\n"],
5
+ "mappings": ";;;;;;;AAIA,SAASA,iBAAwC;AAE1C,IAAMC,2BAAN,cAAuCC,UAAUC,OAAO,uBAAuB,uBAAA,EAAA;EACpF,YAAYC,SAAiBC,SAA6C;AACxE,UAAM;MAAEC,SAAS;QAAEF;MAAQ;MAAG,GAAGC;IAAQ,CAAA;EAC3C;AACF;AAEO,IAAME,wBAAN,cAAoCL,UAAUC,OAAO,oBAAoB,oBAAA,EAAA;EAC9E,YAAYK,aAAqBH,SAA6C;AAC5E,UAAM;MAAEC,SAAS;QAAEG,UAAUD;MAAY;MAAG,GAAGH;IAAQ,CAAA;EACzD;AACF;AAEO,IAAMK,gBAAN,cAA4BR,UAAUC,OAAO,iBAAiB,2BAAA,EAAA;AAA8B;AAE5F,IAAMQ,4BAAN,cAAwCT,UAAUC,OAAO,wBAAwB,yBAAA,EAAA;AAA4B;;;AChBpH,YAAYS,aAAY;AACxB,YAAYC,aAAY;;;ACAxB,YAAYC,YAAY;AACxB,YAAYC,aAAY;AAGxB,SAASC,OAAAA,MAAKC,QAAAA,aAAY;AAE1B,SAASC,gBAAgBC,uBAAuB;AAChD,SAASC,iBAAiB;;;ACZ1B;;;cAAAC;EAAA;;AAIA,YAAYC,aAAY;AAExB,SAASC,cAAAA,aAAYC,YAAYC,OAAAA,MAAKC,QAAAA,aAAY;AAClD,SAASC,4BAA4B;;;ACPrC;;;;;AAIA,YAAYC,YAAY;AAExB,SAASC,YAAYC,KAAKC,KAAKC,YAAY;AAC3C,SAASC,2BAA2B;AACpC,SAASC,YAAY;AAKd,IAAMC,SAAgBC,cAAO;EAClCC,MAAaC,cAAOC,KAAYC,eAAQ;EACxCC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,cAAMnG,MAAM+G,KAAK9G,KAAKgH,SAAQ;AAC9B,YAAIjH,OAAOsC,QAAQ;AACjBA,iBAAOtC,GAAAA,IAAOqC,qBAAqB0E,KAAKG,MAAO5E,OAAetC,GAAAA,GAAMgC,EAAAA;QACtE;MACF;AACA,aAAOM;IACT;IAEA,KAAK,aAAa;AAChB,UAAI,CAACuE,MAAMC,QAAQZ,MAAAA,GAAQ;AACzB,eAAOA;MACT;AAGA,UAAIC,QAAQgB,SAASrF,WAAW,KAAKqE,QAAQiB,KAAKtF,WAAW,GAAG;AAC9D,cAAMuF,cAAclB,QAAQiB,KAAK,CAAA,EAAGF;AACpC,eAAQhB,OAAoBoB,IAAI,CAACC,SAASlF,qBAAqBgF,aAAaE,MAAMvF,EAAAA,CAAAA;MACpF;AAEA,aAAOkE;IACT;IAEA,KAAK,SAAS;AAEZ,YAAMsB,eAAerB,QAAQtE,MAAM4F,OAAO,CAACC,MAAM,CAAWC,8BAAmBD,CAAAA,CAAAA;AAC/E,UAAIF,aAAa1F,WAAW,GAAG;AAC7B,eAAOO,qBAAqBmF,aAAa,CAAA,GAAItB,QAAOlE,EAAAA;MACtD;AAGA,aAAOkE;IACT;IAEA,KAAK,WAAW;AACd,aAAO7D,qBAAqB8D,QAAQyB,EAAC,GAAI1B,QAAOlE,EAAAA;IAClD;IAEA,KAAK,cAAc;AACjB,aAAOK,qBAAqB8D,QAAQ0B,MAAM3B,QAAOlE,EAAAA;IACnD;IAEA,SAAS;AACP,aAAOkE;IACT;EACF;AACF;",
6
+ "names": ["BaseError", "ServiceNotAvailableError", "BaseError", "extend", "service", "options", "context", "FunctionNotFoundError", "functionKey", "function", "FunctionError", "TriggerStateNotFoundError", "Effect", "Schema", "Effect", "Schema", "Obj", "Type", "assertArgument", "failedInvariant", "Operation", "make", "Schema", "Annotation", "JsonSchema", "Obj", "Type", "SystemTypeAnnotation", "Schema", "Annotation", "Obj", "Ref", "Type", "FormInputAnnotation", "Text", "Script", "Struct", "name", "String", "pipe", "optional", "description", "changed", "Boolean", "FormInputAnnotation", "set", "source", "Type", "Ref", "Text", "object", "typename", "version", "Annotation", "LabelAnnotation", "make", "props", "Obj", "Function", "Struct", "key", "optional", "String", "annotations", "description", "name", "NonEmptyString", "version", "updated", "source", "Type", "Ref", "Script", "inputSchema", "JsonSchema", "outputSchema", "services", "Array", "binding", "pipe", "object", "typename", "Annotation", "LabelAnnotation", "set", "SystemTypeAnnotation", "make", "props", "Obj", "setFrom", "target", "change", "t", "JSON", "parse", "stringify", "undefined", "getMeta", "keys", "make", "Schema", "SchemaAST", "Obj", "QueryAST", "Type", "OptionsAnnotationId", "SystemTypeAnnotation", "DXN", "Expando", "Kinds", "kindLiteralAnnotations", "title", "EmailSpec", "Struct", "kind", "Literal", "annotations", "QueueSpec", "queue", "DXN", "Schema", "SubscriptionSpec", "query", "raw", "optional", "String", "ast", "QueryAST", "Query", "options", "deep", "Boolean", "delay", "Number", "TimerSpec", "cron", "ExamplesAnnotationId", "WebhookSpec", "method", "OptionsAnnotationId", "port", "Spec", "Union", "TriggerSchema", "function", "Type", "Ref", "Expando", "inputNodeId", "enabled", "spec", "input", "Record", "key", "value", "Any", "pipe", "object", "typename", "version", "SystemTypeAnnotation", "set", "Trigger", "make", "props", "Obj", "Schema", "DXN", "Type", "EmailEvent", "Struct", "from", "String", "to", "subject", "created", "body", "QueueEvent", "queue", "DXN", "Schema", "item", "Any", "cursor", "SubscriptionEvent", "type", "Type", "Ref", "Obj", "changedObjectId", "optional", "TimerEvent", "tick", "Number", "WebhookEvent", "url", "method", "Literal", "headers", "Record", "key", "value", "bodyText", "TriggerEvent", "Union", "FUNCTIONS_META_KEY", "FUNCTIONS_PRESET_META_KEY", "getUserFunctionIdInMetadata", "meta", "keys", "find", "key", "source", "id", "setUserFunctionIdInMetadata", "functionId", "Error", "push", "typeId", "Symbol", "for", "defineFunction", "key", "name", "description", "inputSchema", "outputSchema", "Any", "handler", "types", "services", "isSchema", "Error", "limit", "stackTraceLimit", "traceError", "cache", "captureStackTrace", "stack", "undefined", "split", "trim", "handlerWithSpan", "args", "result", "isEffect", "withSpan", "getServiceKeys", "map", "tag", "failedInvariant", "toOperation", "functionDef", "op", "Operation", "make", "schema", "input", "output", "meta", "operationHandler", "context", "data", "Promise", "tryPromise", "succeed", "FunctionDefinition", "isFunction", "value", "serialize", "assertArgument", "serializeFunction", "deserialize", "functionObj", "Obj", "instanceOf", "Function", "deserializeFunction", "fn", "version", "Type", "toJsonSchema", "deployedFunctionId", "change", "setUserFunctionIdInMetadata", "getMeta", "Unknown", "toEffectSchema", "getUserFunctionIdInMetadata", "defineFunction", "key", "name", "description", "inputSchema", "Struct", "iterations", "optional", "Number", "annotations", "default", "outputSchema", "result", "String", "handler", "fn", "data", "a", "b", "i", "toString", "Console", "Effect", "Schema", "defineFunction", "key", "name", "description", "inputSchema", "Any", "outputSchema", "handler", "fn", "data", "log", "Effect", "Schema", "defineFunction", "key", "name", "description", "inputSchema", "Struct", "duration", "optional", "Number", "annotations", "default", "outputSchema", "Void", "handler", "fn", "data", "sleep", "Example", "fib", "fib$", "reply", "reply$", "sleep", "sleep$", "HttpClient", "HttpClientRequest", "Context", "Effect", "Layer", "Redacted", "Query", "Database", "AccessToken", "CredentialsService", "Tag", "getCredential", "query", "gen", "credentials", "promise", "getApiKey", "credential", "apiKey", "Error", "service", "make", "configuredLayer", "succeed", "ConfiguredCredentialsService", "layerConfig", "effect", "serviceCredentials", "forEach", "value", "layerFromDatabase", "caching", "dbService", "Database", "Service", "cache", "Map", "queryCredentials", "cacheKey", "JSON", "stringify", "has", "get", "accessTokens", "db", "Query", "type", "AccessToken", "run", "filter", "accessToken", "source", "map", "token", "set", "length", "addCredentials", "push", "find", "withAuthorization", "kind", "mapRequest", "request", "authorization", "setHeader", "Context", "Effect", "Layer", "Schema", "Obj", "Type", "invariant", "LogLevel", "log", "Context", "Effect", "Layer", "AgentStatus", "Obj", "ObjectId", "Message", "TracingService", "Tag", "noop", "getTraceContext", "write", "traceInvocationStart", "sync", "invocationId", "ObjectId", "random", "invocationTraceQueue", "undefined", "traceInvocationEnd", "layerNoop", "succeed", "layerSubframe", "mapContext", "effect", "gen", "tracing", "context", "event", "die", "layerInvocation", "data", "currentInvocation", "emitStatus", "fnUntraced", "Obj", "make", "AgentStatus", "parentMessage", "toolCallId", "created", "Date", "toISOString", "emitConverationMessage", "Message", "properties", "MESSAGE_PROPERTY_TOOL_CALL_ID", "ComputeEventPayload", "Union", "Struct", "type", "Literal", "nodeId", "String", "inputs", "Array", "outputs", "property", "value", "Any", "event", "ComputeEvent", "payload", "pipe", "Type", "object", "typename", "version", "ComputeEventLogger", "Tag", "noop", "log", "undefined", "layerFromTracing", "effect", "gen", "tracing", "TracingService", "write", "Obj", "make", "getTraceContext", "logCustomEvent", "data", "logger", "Error", "createDefectLogger", "catchAll", "error", "createEventLogger", "level", "message", "logFunction", "LogLevel", "WARN", "warn", "VERBOSE", "verbose", "DEBUG", "debug", "INFO", "info", "ERROR", "invariant", "Context", "Effect", "Layer", "FunctionInvocationService", "Tag", "layerNotAvailable", "succeed", "invokeFunction", "die", "resolveFunction", "functionDef", "input", "serviceFunctionEffect", "service", "key", "Context", "Effect", "Layer", "QueueService", "Tag", "notAvailable", "succeed", "queues", "get", "_dxn", "Error", "create", "queue", "undefined", "make", "layer", "getQueue", "dxn", "pipe", "map", "createQueue", "options", "append", "objects", "promise", "ContextQueueService", "AnthropicClient", "Effect", "Layer", "Schema", "SchemaAST", "AiModelResolver", "AiService", "AnthropicResolver", "LifecycleState", "Resource", "Database", "Ref", "Type", "refFromEncodedReference", "EchoClient", "runAndForwardErrors", "assertState", "failedInvariant", "invariant", "PublicKey", "Headers", "HttpClient", "HttpClientError", "HttpClientResponse", "Effect", "FiberRef", "Layer", "Stream", "log", "ErrorCodec", "requestInitTagKey", "FunctionsAiHttpClient", "make", "service", "request", "url", "signal", "fiber", "context", "getFiberRef", "currentContext", "options", "unsafeMap", "get", "headers", "merge", "fromInput", "send", "body", "tryPromise", "try", "fetch", "Request", "method", "catch", "cause", "error", "errorSerialized", "encode", "RequestError", "reason", "pipe", "map", "response", "fromWeb", "_tag", "formData", "toReadableStreamEffect", "stream", "flatMap", "undefined", "layer", "succeed", "wrapFunctionHandler", "func", "FunctionDefinition", "isFunction", "TypeError", "meta", "key", "name", "description", "inputSchema", "Type", "toJsonSchema", "outputSchema", "undefined", "services", "handler", "data", "context", "includes", "Database", "Service", "QueueService", "dataService", "queryService", "FunctionError", "message", "isAnyKeyword", "ast", "Schema", "validateSync", "error", "cause", "funcContext", "FunctionContext", "open", "types", "length", "invariant", "db", "graph", "schemaRegistry", "register", "dataWithDecodedRefs", "decodeRefsFromSchema", "result", "isEffect", "runAndForwardErrors", "pipe", "orDie", "provide", "createLayer", "Resource", "client", "queues", "EchoClient", "connectToService", "queueService", "_open", "spaceId", "constructDatabase", "failedInvariant", "spaceKey", "PublicKey", "fromHex", "reactiveSchemaQuery", "preloadSchemaOnOpen", "setSpaceRoot", "spaceRootUrl", "constructQueueFactory", "_close", "close", "assertState", "_lifecycleState", "LifecycleState", "OPEN", "dbLayer", "layer", "notAvailable", "queuesLayer", "credentials", "CredentialsService", "layerFromDatabase", "caching", "configuredLayer", "functionInvocationService", "MockedFunctionInvocationService", "tracing", "TracingService", "layerNoop", "aiLayer", "functionsAiService", "AiModelResolver", "buildAiService", "AnthropicResolver", "make", "apiUrl", "FunctionsAiHttpClient", "AiService", "mergeAll", "succeed", "FunctionInvocationService", "invokeFunction", "die", "resolveFunction", "value", "encoded", "encodedBoundAST", "Ref", "isRefType", "isRef", "resolver", "createRefResolver", "space", "refFromEncodedReference", "_tag", "Array", "isArray", "prop", "getPropertySignatures", "toString", "type", "elements", "rest", "elementType", "map", "item", "nonUndefined", "filter", "t", "isUndefinedKeyword", "f", "from"]
7
7
  }