@dxos/compute 0.16.0 → 0.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/AiMetering.mjs +1 -0
- package/dist/lib/Hook.mjs +1 -0
- package/dist/lib/Operation.mjs +3 -3
- package/dist/lib/Process.mjs +2 -2
- package/dist/lib/Trace.mjs +1 -1
- package/dist/lib/chunk-AgentIdentity.mjs +1 -1
- package/dist/lib/chunk-AgentService.mjs.map +1 -1
- package/dist/lib/chunk-AiMetering.mjs +77 -0
- package/dist/lib/chunk-AiMetering.mjs.map +1 -0
- package/dist/lib/chunk-Cancellation.mjs +1 -1
- package/dist/lib/chunk-Hook.mjs +78 -0
- package/dist/lib/chunk-Hook.mjs.map +1 -0
- package/dist/lib/chunk-Instructions.mjs +1 -1
- package/dist/lib/chunk-Operation.mjs +169 -5
- package/dist/lib/chunk-Operation.mjs.map +1 -1
- package/dist/lib/chunk-OperationHandlerSet.mjs +1 -1
- package/dist/lib/chunk-OperationRegistry.mjs +1 -1
- package/dist/lib/chunk-OperationRegistry.mjs.map +1 -1
- package/dist/lib/chunk-Process.mjs +18 -10
- package/dist/lib/chunk-Process.mjs.map +1 -1
- package/dist/lib/chunk-Project.mjs +52 -24
- package/dist/lib/chunk-Project.mjs.map +1 -1
- package/dist/lib/chunk-Reducer.mjs +827 -0
- package/dist/lib/chunk-Reducer.mjs.map +1 -0
- package/dist/lib/chunk-Routine.mjs +1 -1
- package/dist/lib/chunk-Runnable.mjs +1 -1
- package/dist/lib/chunk-ServiceResolver.mjs +1 -1
- package/dist/lib/chunk-Skill.mjs +10 -47
- package/dist/lib/chunk-Skill.mjs.map +1 -1
- package/dist/lib/chunk-Spec.mjs +49 -0
- package/dist/lib/chunk-Spec.mjs.map +1 -0
- package/dist/lib/chunk-SpecReview.mjs +98 -0
- package/dist/lib/chunk-SpecReview.mjs.map +1 -0
- package/dist/lib/chunk-SqlService.mjs.map +1 -1
- package/dist/lib/chunk-StorageService.mjs +1 -1
- package/dist/lib/chunk-Template.mjs +2 -2
- package/dist/lib/chunk-Trace.mjs +97 -13
- package/dist/lib/chunk-Trace.mjs.map +1 -1
- package/dist/lib/chunk-Trajectory.mjs +326 -0
- package/dist/lib/chunk-Trajectory.mjs.map +1 -0
- package/dist/lib/chunk-Transcript.mjs +84 -0
- package/dist/lib/chunk-Transcript.mjs.map +1 -0
- package/dist/lib/chunk-definitions.mjs +1 -1
- package/dist/lib/errors.mjs +3 -1
- package/dist/lib/errors.mjs.map +1 -1
- package/dist/lib/index.mjs +14 -8
- package/dist/lib/testing.mjs +2 -2
- package/dist/lib/trajectory/Reducer.mjs +1 -0
- package/dist/lib/trajectory/Trajectory.mjs +1 -0
- package/dist/lib/trajectory/Transcript.mjs +1 -0
- package/dist/lib/types/Project.mjs +1 -1
- package/dist/lib/types/Skill.mjs +1 -1
- package/dist/lib/types/Spec.mjs +1 -0
- package/dist/lib/types/SpecReview.mjs +1 -0
- package/dist/types/src/AgentService.d.ts +9 -0
- package/dist/types/src/AgentService.d.ts.map +1 -1
- package/dist/types/src/AiMetering.d.ts +23 -0
- package/dist/types/src/AiMetering.d.ts.map +1 -0
- package/dist/types/src/AiMetering.test.d.ts +2 -0
- package/dist/types/src/AiMetering.test.d.ts.map +1 -0
- package/dist/types/src/Hook.d.ts +84 -0
- package/dist/types/src/Hook.d.ts.map +1 -0
- package/dist/types/src/Hook.test.d.ts +2 -0
- package/dist/types/src/Hook.test.d.ts.map +1 -0
- package/dist/types/src/Operation.d.ts +276 -2
- package/dist/types/src/Operation.d.ts.map +1 -1
- package/dist/types/src/Process.d.ts +26 -4
- package/dist/types/src/Process.d.ts.map +1 -1
- package/dist/types/src/Script.test.d.ts +2 -0
- package/dist/types/src/Script.test.d.ts.map +1 -0
- package/dist/types/src/Trace.d.ts +103 -1
- package/dist/types/src/Trace.d.ts.map +1 -1
- package/dist/types/src/errors.d.ts +30 -0
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +3 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/trajectory/Reducer.d.ts +191 -0
- package/dist/types/src/trajectory/Reducer.d.ts.map +1 -0
- package/dist/types/src/trajectory/Reducer.test.d.ts +2 -0
- package/dist/types/src/trajectory/Reducer.test.d.ts.map +1 -0
- package/dist/types/src/trajectory/Trajectory.d.ts +3211 -0
- package/dist/types/src/trajectory/Trajectory.d.ts.map +1 -0
- package/dist/types/src/trajectory/Trajectory.test.d.ts +2 -0
- package/dist/types/src/trajectory/Trajectory.test.d.ts.map +1 -0
- package/dist/types/src/trajectory/Transcript.d.ts +40 -0
- package/dist/types/src/trajectory/Transcript.d.ts.map +1 -0
- package/dist/types/src/trajectory/index.d.ts +4 -0
- package/dist/types/src/trajectory/index.d.ts.map +1 -0
- package/dist/types/src/trajectory/light-threads.test.d.ts +2 -0
- package/dist/types/src/trajectory/light-threads.test.d.ts.map +1 -0
- package/dist/types/src/trajectory/samples.test.d.ts +2 -0
- package/dist/types/src/trajectory/samples.test.d.ts.map +1 -0
- package/dist/types/src/types/Project.d.ts +11 -12
- package/dist/types/src/types/Project.d.ts.map +1 -1
- package/dist/types/src/types/Skill.d.ts +6 -51
- package/dist/types/src/types/Skill.d.ts.map +1 -1
- package/dist/types/src/types/Spec.d.ts +26 -0
- package/dist/types/src/types/Spec.d.ts.map +1 -0
- package/dist/types/src/types/SpecReview.d.ts +76 -0
- package/dist/types/src/types/SpecReview.d.ts.map +1 -0
- package/dist/types/src/types/index.d.ts +2 -0
- package/dist/types/src/types/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +59 -26
- package/src/AgentService.ts +9 -0
- package/src/AiMetering.test.ts +89 -0
- package/src/AiMetering.ts +93 -0
- package/src/Hook.test.ts +75 -0
- package/src/Hook.ts +154 -0
- package/src/Operation.test.ts +23 -0
- package/src/Operation.ts +334 -0
- package/src/Process.ts +33 -6
- package/src/Script.test.ts +74 -0
- package/src/Trace.ts +97 -4
- package/src/errors.ts +3 -0
- package/src/index.ts +3 -1
- package/src/trajectory/Reducer.test.ts +575 -0
- package/src/trajectory/Reducer.ts +1026 -0
- package/src/trajectory/Trajectory.test.ts +114 -0
- package/src/trajectory/Trajectory.ts +440 -0
- package/src/trajectory/Transcript.ts +113 -0
- package/src/trajectory/index.ts +7 -0
- package/src/trajectory/light-threads.test.ts +310 -0
- package/src/trajectory/samples.test.ts +285 -0
- package/src/types/Project.test.ts +2 -1
- package/src/types/Project.ts +43 -27
- package/src/types/Skill.ts +6 -61
- package/src/types/Spec.ts +68 -0
- package/src/types/SpecReview.ts +98 -0
- package/src/types/index.ts +2 -0
- package/dist/lib/McpServer.mjs +0 -1
- package/dist/lib/chunk-McpServer.mjs +0 -124
- package/dist/lib/chunk-McpServer.mjs.map +0 -1
- package/dist/types/src/McpServer.d.ts +0 -113
- package/dist/types/src/McpServer.d.ts.map +0 -1
- package/src/McpServer.ts +0 -142
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-Operation.mjs","names":["op","Schema$"],"sources":["../../src/Operation.ts"],"sourcesContent":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Cause from 'effect/Cause';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport type * as Exit from 'effect/Exit';\nimport * as Function from 'effect/Function';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Pipeable from 'effect/Pipeable';\nimport * as Rpc from 'effect/rpc/Rpc';\nimport * as RpcGroup from 'effect/rpc/RpcGroup';\nimport * as Schema from 'effect/Schema';\nimport * as Schema$ from 'effect/Schema';\nimport * as Scope from 'effect/Scope';\nimport * as Struct from 'effect/Struct';\nimport type * as Types from 'effect/Types';\n\nimport { Annotation, DXN, JsonSchema, type Key, Migration, Obj, Ref, Type } from '@dxos/echo';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport type { URI } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { type NoHandlerError, RunAgainError } from './errors.ts';\nimport type { Operation } from './index.ts';\nimport type * as Process from './Process.ts';\nimport type * as StorageService from './StorageService.ts';\nimport type * as Trace from './Trace.ts';\n\n/**\n * Schema type that accepts any Encoded form but requires no Context.\n * This allows ECHO object schemas where Type !== Encoded due to [KindId] symbol.\n */\ntype Schema<T> = Schema$.Codec<T, any, never, never>;\n\nexport const DefinitionTypeId = '~@dxos/operation/OperationDefinition' as const;\nexport type DefinitionTypeId = typeof DefinitionTypeId;\n\n/**\n * Serializable definition of an Operation.\n * Contains schema and metadata, but no runtime logic.\n */\nexport interface Definition<I, O, S = any> extends Pipeable.Pipeable, Definition.Variance<I, O, S> {\n /**\n * Input schema for the operation.\n */\n readonly input: Schema<I>;\n /**\n * Output schema for the operation.\n */\n readonly output: Schema<O>;\n\n readonly meta: {\n readonly key: DXN.DXN;\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n /**\n * Phosphor icon identifier in `ph--<name>--<variant>` format (e.g. `ph--file-text--regular`).\n */\n readonly icon?: string;\n /**\n * Deployment ID for remote invocation.\n * Assigned by the EDGE function service when deployed.\n */\n readonly deployedId?: string;\n\n /**\n * Dictionary of annotations for the operation.\n */\n // TODO(dmaretskyi): Make required, but this complicates `make` to fill in defaults.\n readonly annotations?: Annotation.Dictionary;\n\n /**\n * When true, this operation is not serialized into the hypergraph registry.\n * Use for UI-only operations that should not be discoverable by the AI agent.\n */\n readonly skipRegistry?: boolean;\n };\n\n /**\n * Execution mode for the operation.\n * - 'sync': Operation completes synchronously (fast, UI-blocking acceptable).\n * - 'async': Operation may take time (should not block UI).\n */\n readonly executionMode: 'sync' | 'async';\n\n /**\n * ECHO types the operation uses.\n * Ensures types are available when the operation is executed remotely.\n */\n readonly types: readonly Type.AnyEntity[];\n\n /**\n * Effect services required by this operation.\n * These services will be automatically provided to the handler at invocation time.\n */\n readonly services: readonly Context.Key<S, unknown>[];\n}\n\n/**\n * Namespace for OperationDefinition helper types.\n */\nexport declare namespace Definition {\n export interface Variance<I, O, S> {\n [DefinitionTypeId]: {\n readonly _Input: Types.Contravariant<I>;\n readonly _Output: Types.Covariant<O>;\n readonly _Services: Types.Covariant<S>;\n };\n }\n\n /**\n * Any operation definition, regardless of input/output types.\n */\n export type Any = Definition<any, any, any>;\n\n /**\n * Extract the input type from an operation definition.\n */\n export type Input<T extends Any> = T extends Variance<infer I, infer _O, infer _S> ? I : never;\n\n /**\n * Extract the output type from an operation definition.\n */\n export type Output<T extends Any> = T extends Variance<infer _I, infer O, infer _S> ? O : never;\n\n /**\n * Extract the service identifier types from an operation's services array.\n * Returns `never` if the operation has no services declared.\n */\n export type Services<T extends Any> = T extends Variance<infer _I, infer _O, infer S> ? S : never;\n\n export type HandlerType<T extends Any> =\n T extends Variance<infer I, infer O, infer S> ? Handler<I, O, any, S> : never;\n}\n\n/**\n * Runtime handler for an Operation.\n */\nexport type Handler<I, O, E = Error, R = never> = (input: I) => Effect.Effect<O, E, R>;\n\nexport type WithHandler<T extends Definition.Any> = T & {\n handler: Definition.HandlerType<T>;\n};\n\nexport const LazyHandlerTypeId = '~@dxos/operation/LazyHandler' as const;\nexport type LazyHandlerTypeId = typeof LazyHandlerTypeId;\n\n/**\n * A definition paired with the module that implements it. The pairing is TYPED — the loaded\n * module's default must be `WithHandler<Def>` for the same `Def` — so a definition can no longer be\n * wired to another operation's handler and fail only at dispatch.\n */\nexport interface LazyHandler<Def extends Definition.Any = Definition.Any> {\n readonly [LazyHandlerTypeId]: LazyHandlerTypeId;\n readonly definition: Def;\n readonly load: () => Promise<{ default: WithHandler<Def> }>;\n}\n\n/** Whether a value is a {@link LazyHandler}. */\nexport const isLazyHandler = (value: unknown): value is LazyHandler =>\n typeof value === 'object' && value !== null && LazyHandlerTypeId in value;\n\n/**\n * Pairs a definition with a lazily-imported handler module, keeping the handler body out of the\n * static graph while checking that it implements THIS definition.\n *\n * @example\n * ```ts\n * GetBlueskyTargets.pipe(Operation.lazyHandler(() => import('./get-bluesky-targets')))\n * ```\n */\nexport const lazyHandler: {\n <Def extends Definition<any, any>>(load: () => Promise<{ default: WithHandler<Def> }>): (op: Def) => LazyHandler<Def>;\n <Def extends Definition<any, any>>(op: Def, load: () => Promise<{ default: WithHandler<Def> }>): LazyHandler<Def>;\n} = (<Def extends Definition<any, any>>(\n opOrLoad: Def | (() => Promise<{ default: WithHandler<Def> }>),\n load?: () => Promise<{ default: WithHandler<Def> }>,\n) => {\n const make = (op: Def, loader: () => Promise<{ default: WithHandler<Def> }>): LazyHandler<Def> => ({\n [LazyHandlerTypeId]: LazyHandlerTypeId,\n definition: op,\n load: loader,\n });\n return load === undefined\n ? (op: Def) => make(op, opOrLoad as () => Promise<{ default: WithHandler<Def> }>)\n : make(opOrLoad as Def, load);\n}) as any;\n\n/**\n * Checks if a value is an operation definition.\n */\nexport const isOperationDefinition = (value: unknown): value is Definition.Any => {\n return typeof value === 'object' && value !== null && DefinitionTypeId in value;\n};\n\n/**\n * Checks if a value is an operation with a handler.\n */\nexport const isOperationWithHandler = (value: unknown): value is WithHandler<Definition.Any> => {\n return isOperationDefinition(value) && 'handler' in value;\n};\n\n/**\n * Props for creating an Operation definition.\n * Derived from OperationDefinition with executionMode made optional (defaults to 'async').\n */\nexport type Props<I, O> = Omit<Definition<I, O>, DefinitionTypeId | 'pipe' | 'executionMode' | 'types' | 'services'> & {\n readonly executionMode?: 'sync' | 'async';\n readonly types?: Definition<I, O>['types'];\n readonly services?: Definition<I, O>['services'];\n};\n\n/**\n * Creates a new Operation definition.\n * Applies default executionMode of 'async' if not specified.\n * The returned type preserves the literal types of props (including services).\n */\nexport const make = <const P extends Types.NoExcessProperties<Props<any, any>, P>>(\n props: P,\n): Definition<\n Schema$.Schema.Type<P['input']>,\n Schema$.Schema.Type<P['output']>,\n Context.Service.Identifier<NonNullable<P['services']>[number]>\n> => {\n return {\n [DefinitionTypeId]: {},\n ...props,\n executionMode: props.executionMode ?? 'async',\n types: props.types ?? [],\n services: props.services ?? [],\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n },\n } as any;\n};\n\n/**\n * Attaches a handler to an Operation definition.\n * The handler may use any services declared in the operation, plus Operation.Service (always available).\n * Dual API: can be called directly or used in a pipe.\n *\n * @example\n * ```ts\n * const MyOp = Operation.make({\n * input: Schema.Void,\n * output: Schema.Void,\n * meta: { key: 'my-op' },\n * services: [DatabaseService],\n * });\n *\n * // Direct call - handler can use DatabaseService\n * const op = Operation.withHandler(MyOp, (input) =>\n * Effect.gen(function* () {\n * const db = yield* DatabaseService;\n * return {};\n * }),\n * );\n *\n * // Piped call\n * const op = MyOp.pipe(Operation.withHandler((input) => Effect.succeed({})));\n * ```\n */\nexport const withHandler: {\n <Def extends Definition<any, any>, E = never>(\n handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n ): (op: Def) => WithHandler<Def>;\n <Def extends Definition<any, any>, E = never>(\n op: Def,\n handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n ): WithHandler<Def>;\n} = <Def extends Definition<any, any>, E = never>(\n opOrHandler: Def | Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n handler?: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n): WithHandler<Def> => {\n // If called with just handler (piped usage).\n if (handler === undefined) {\n const handlerFn = opOrHandler as Handler<\n Definition.Input<Def>,\n Definition.Output<Def>,\n E,\n Definition.Services<Def> | Service\n >;\n return ((op: Def) => ({\n ...op,\n handler: handlerFn,\n })) as any;\n }\n\n // If called with both op and handler (direct usage).\n const op = opOrHandler as Def;\n return {\n ...op,\n handler,\n } as any;\n};\n\n/**\n * Helper to make the handler type opaque.\n * Workaround for TypeScript's inability to infer the handler type from the operation definition:\n * ```\n * error TS2742: The inferred type of 'default' cannot be named without a reference.\n * ```\n *\n * Most of the time the exact handler type is not needed.\n *\n * @example\n * ```ts\n * const MyOp = Operation.make({\n * input: Schema.Void,\n * output: Schema.Void,\n * meta: { key: 'my-op' },\n * services: [DatabaseService],\n * });\n *\n * export default MyOp.pipe(\n * Operation.withHandler(\n * Effect.fn(function* (input) {\n * return { result: 'ok' };\n * }),\n * ),\n * Operation.opaqueHandler,\n * );\n * ```\n */\nexport const opaqueHandler = <T extends Operation.Definition.Any>(\n handler: Operation.WithHandler<T>,\n): Operation.WithHandler<Operation.Definition.Any> => handler;\n\n//\n// Durable operations.\n//\n\n/**\n * Handler of a durable operation: the callbacks of one running process instance.\n *\n * Process lifecycle: Initial -> Running <-> Suspended -> Terminated.\n *\n * - onSpawn -> called once when the process is spawned.\n * - onInput -> called for every input submitted to the process.\n * - onAlarm -> called for processes scheduling alarms.\n * - onChildEvent -> called when child process produces output or exits.\n */\nexport interface DurableHandler<_Input, _Output, _Requirements, _Rpcs extends Rpc.Any> {\n /**\n * Called when the process is spawned.\n * Not called for processes that are resumed from a previously suspended state.\n *\n * @returns A signal indicating to the runtime whether the process is finished, or should be resumed later.\n * @throws Throwing in the handler will terminate the process with an error.\n *\n * Note: This function should aim to complete in under 5 seconds to avoid exceeding limits in serverless environments.\n */\n onSpawn(): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Called when there's input available to process.\n *\n * The function can be called in parallel.\n *\n * @returns A signal indicating to the runtime whether the process is finished, or should be resumed later.\n * @throws Throwing in the handler will terminate the process with an error.\n *\n * Note: This function should aim to complete in under 5 seconds to avoid exceeding limits in serverless environments.\n */\n onInput(input: _Input): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Called when the process's alarm is triggered.\n *\n * @throws Throwing in the handler will terminate the process with an error.\n */\n onAlarm(): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Called when the process's child process produces output or exits.\n *\n * This allows the parent process to hibernate while a long-running child process is running.\n */\n onChildEvent(event: ChildEvent<unknown>): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Handlers for the RPCs provided by the process.\n */\n rpcHandlers: Context.Context<Rpc.ToHandler<_Rpcs>>;\n}\n\n/**\n * Services that are always available to all processes.\n * Provided unconditionally by the runtime, so handlers may use them without declaring them\n * in {@link DurableProps.services}.\n */\nexport type BaseServices = Trace.TraceService | StorageService.StorageService;\n\nexport type ChildEvent<T> =\n | {\n readonly _tag: 'output';\n readonly pid: Process.ID;\n readonly data: T;\n }\n | {\n readonly _tag: 'exited';\n readonly pid: Process.ID;\n readonly result: Exit.Exit<void>;\n };\n\n/**\n * Runtime context handed to a durable operation's `create`.\n */\nexport interface DurableContext<I, O> {\n readonly id: Process.ID;\n\n /**\n * Parameters assigned during process creation.\n */\n readonly params: Process.Params;\n\n /**\n * Complete this process with sucessful result.\n * No additional events will be pushed to the process.\n */\n succeed(): void;\n\n /**\n * Complete this process with an error.\n * No additional events will be pushed to the process.\n */\n fail(error: Error): void;\n\n /**\n * Submit output of the process.\n */\n submitOutput(output: O): void;\n\n /**\n * Set an alarm for the process to be woken up later. `onAlarm` runs with the process's own\n * context, not the caller's: an alarm scheduled from inside a handler does not nest under it.\n *\n * @param timeout - Optional timeout in milliseconds. If not provided, the process is woken up as soon as possible.\n */\n setAlarm(timeout?: number): Effect.Effect<void>;\n}\n\nexport const DurableDefinitionTypeId = '~@dxos/operation/DurableDefinition' as const;\nexport type DurableDefinitionTypeId = typeof DurableDefinitionTypeId;\n\n/**\n * Declaration of a durable operation, without its handler.\n * Created by {@link makeDurable}; {@link withDurableHandler} attaches the handler factory to produce a {@link Durable}.\n */\nexport interface DurableDefinition<_Input, _Output, _Requirements = never, _Rpcs extends Rpc.Any = never>\n extends Pipeable.Pipeable, DurableDefinition.Variance<_Input, _Output, _Requirements, _Rpcs> {\n /**\n * Unique identifier for the executable in the reverse DNS format.\n */\n readonly key: string;\n\n /**\n * Human-readable label, when provided.\n */\n readonly name?: string;\n\n readonly services: readonly Context.Key<any, any>[];\n\n /**\n * Codecs for the process's inputs and outputs, from {@link DurableProps}. Exposed on the\n * interface so a caller that moves a value across a boundary (a remote runtime) can encode it\n * with the definition's own schema rather than assuming the value is already JSON.\n */\n readonly input: Schema.Codec<_Input, any>;\n readonly output: Schema.Codec<_Output, any>;\n\n /** Schemas to register with the process's database; see {@link DurableProps.types}. */\n readonly types?: readonly Type.AnyEntity[];\n\n // Runtime RPC group, stored as `any`. `RpcGroup`/`RpcClient` are invariant in their type\n // argument (and `DurableHandler.rpcHandlers` is contravariant in it), so referencing `_Rpcs` in the\n // structural fields would block `Durable<…, never>` from being assignable to `Durable.Any`.\n // The precise group is carried by the covariant `Variance` phantom and recovered at `spawn`.\n // See design spec §4.4.\n readonly rpcs: RpcGroup.RpcGroup<any>;\n}\n\nexport declare namespace DurableDefinition {\n export interface Variance<_Input, _Output, _Requirements, _Rpcs> {\n readonly [DurableDefinitionTypeId]: {\n readonly _Input: Types.Contravariant<_Input>;\n readonly _Output: Types.Covariant<_Output>;\n readonly _Requirements: Types.Covariant<_Requirements>;\n\n // Phantom-covariant: lets `never`-RPC processes stay assignable to `Durable.Any` while\n // `spawn` still recovers the precise group from this slot. See design spec §4.4.\n readonly _Rpcs: Types.Covariant<_Rpcs>;\n };\n }\n\n export type Any = DurableDefinition<any, any, any, any>;\n\n export type Input<T extends Any> = T extends Variance<infer I, infer _O, infer _R, infer _P> ? I : never;\n export type Output<T extends Any> = T extends Variance<infer _I, infer O, infer _R, infer _P> ? O : never;\n export type Requirements<T extends Any> = T extends Variance<infer _I, infer _O, infer R, infer _P> ? R : never;\n export type Rpcs<T extends Any> =\n T extends Variance<infer _I, infer _O, infer _R, infer P extends Rpc.Any> ? P : never;\n\n /**\n * The handler factory {@link withDurableHandler} accepts for a definition: callbacks may be omitted and default to no-ops.\n */\n export type Create<T extends Any> = (\n ctx: DurableContext<Input<T>, Output<T>>,\n ) => Effect.Effect<\n Partial<DurableHandler<Input<T>, Output<T>, Requirements<T>, Rpcs<T>>>,\n never,\n Requirements<T> | BaseServices | Scope.Scope\n >;\n\n /**\n * The durable operation produced by attaching a handler to a definition.\n */\n export type WithHandler<T extends Any> = Durable<Input<T>, Output<T>, Requirements<T>, Rpcs<T>>;\n}\n\nexport const DurableTypeId = '~@dxos/operation/Durable' as const;\nexport type DurableTypeId = typeof DurableTypeId;\n\n/**\n * A durable operation: declaration plus a handler factory, run by a process runtime.\n * Can be instantiated multiple times to produce new process instances with separate state and handlers.\n * `create` is used to instantiate a new process.\n * Can store runtime state in scope of `create` function.\n */\nexport interface Durable<_Input, _Output, _Requirements = never, _Rpcs extends Rpc.Any = never>\n extends\n DurableDefinition<_Input, _Output, _Requirements, _Rpcs>,\n Durable.Variance<_Input, _Output, _Requirements, _Rpcs> {\n /**\n * Create a new instance of the process.\n */\n create(\n ctx: DurableContext<_Input, _Output>,\n ): Effect.Effect<\n DurableHandler<_Input, _Output, _Requirements, any>,\n never,\n _Requirements | BaseServices | Scope.Scope\n >;\n}\n\nexport const isDurableDefinition = (value: unknown): value is DurableDefinition.Any =>\n typeof value === 'object' && value !== null && DurableDefinitionTypeId in value;\n\nexport const isDurable = (executable: unknown): executable is Durable.Any =>\n typeof executable === 'object' && executable !== null && DurableTypeId in executable;\n\nexport namespace Durable {\n export interface Variance<_Input, _Output, _Requirements, _Rpcs> {\n readonly [DurableTypeId]: {\n readonly _Input: Types.Contravariant<_Input>;\n readonly _Output: Types.Covariant<_Output>;\n readonly _Requirements: Types.Covariant<_Requirements>;\n readonly _Rpcs: Types.Covariant<_Rpcs>;\n };\n }\n\n export type Any = Durable<any, any, any, any>;\n}\n\nexport interface DurableProps {\n /**\n * Unique identifier for the process in the reverse DNS format.\n */\n readonly key: string;\n\n /**\n * Human-readable label; `Process.spawn` names the process after it.\n */\n readonly name?: string;\n\n readonly input: Schema.Codec<any, any>;\n readonly output: Schema.Codec<any, any>;\n readonly services: readonly Context.Key<any, any>[];\n readonly rpcs?: RpcGroup.RpcGroup<any>;\n\n /**\n * Schemas the process's own data model needs, registered with its database at spawn.\n *\n * Declared here beside `services` because a host cannot know them: it resolves a process by key\n * and has no view of the types that process queries. Unregistered, a TYPED query silently matches\n * nothing — a queue append succeeds and the read back returns empty, which reads as a lost write\n * rather than a missing schema.\n */\n readonly types?: readonly Type.AnyEntity[];\n}\n\n/**\n * Declares a durable operation; attach its handler factory with {@link withDurableHandler}.\n *\n * @example\n * ```ts\n * const Counter = Operation.makeDurable({ key: 'example.counter', input: Schema.Number, output: Schema.Number, services: [] }).pipe(\n * Operation.withDurableHandler((ctx) =>\n * Effect.succeed({ onInput: (input) => Effect.sync(() => ctx.submitOutput(input + 1)) }),\n * ),\n * );\n * ```\n */\nexport const makeDurable = <const Opts extends Types.NoExcessProperties<DurableProps, Opts>>(\n opts: Opts,\n): DurableDefinition<\n Schema.Schema.Type<Opts['input']>,\n Schema.Schema.Type<Opts['output']>,\n Context.Service.Identifier<NonNullable<Opts['services']>[number]>,\n RpcGroup.Rpcs<Opts['rpcs']>\n> => {\n assertArgument(/^[a-z0-9]([a-z0-9.\\-/]*[a-z0-9])?$/i.test(opts.key), 'key', 'Invalid key');\n return {\n [DurableDefinitionTypeId]: {} as any,\n ...opts,\n rpcs: opts.rpcs ?? RpcGroup.make(),\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n },\n };\n};\n\n/**\n * Attaches the handler factory to a durable operation definition.\n * Dual API: can be called directly or used in a pipe.\n */\nexport const withDurableHandler: {\n <Def extends DurableDefinition.Any>(\n create: DurableDefinition.Create<Def>,\n ): (def: Def) => DurableDefinition.WithHandler<Def>;\n <Def extends DurableDefinition.Any>(\n def: Def,\n create: DurableDefinition.Create<Def>,\n ): DurableDefinition.WithHandler<Def>;\n} = Function.dual(2, <Def extends DurableDefinition.Any>(def: Def, create: DurableDefinition.Create<Def>) =>\n attachDurableHandler(def, create),\n);\n\nconst attachDurableHandler = <Def extends DurableDefinition.Any>(\n def: Def,\n create: DurableDefinition.Create<Def>,\n): DurableDefinition.WithHandler<Def> => ({\n ...def,\n [DurableTypeId]: {} as any,\n create: (ctx) =>\n create(ctx).pipe(\n Effect.map((partial) => ({\n onSpawn: () => Effect.void,\n onInput: () => Effect.void,\n onAlarm: () => Effect.void,\n onChildEvent: () => Effect.void,\n ...partial,\n rpcHandlers: sanitizeRpcs(def.rpcs, partial.rpcHandlers),\n })),\n ),\n});\n\n// Returns `Context.Context<any>`: the runtime handler bag is stored untyped because\n// `DurableHandler.rpcHandlers` is contravariant in `_Rpcs` (see design spec §4.4); the precise\n// handler contract is enforced by `withDurableHandler`'s `create` parameter, not by this internal helper.\nconst sanitizeRpcs = <Rpcs extends Rpc.Any>(\n defined: RpcGroup.RpcGroup<Rpcs> | undefined,\n provided: Context.Context<Rpc.ToHandler<Rpcs>> | undefined,\n): Context.Context<any> => {\n // Handlers are required only when a non-empty RPC group is declared.\n const needsRpcs = defined !== undefined && defined.requests.size > 0;\n if (!needsRpcs) {\n // `Context.empty()` is `Context<never>`; `Context`'s requirement parameter is contravariant,\n // so the empty (no-handler) context needs widening to the untyped bag.\n return provided ?? (Context.empty() as Context.Context<any>);\n }\n if (!provided) {\n throw new TypeError('Durable operation declared RPCs but did not provide any handlers');\n }\n return provided;\n};\n\n//\n// Tool projection\n//\n\n/**\n * Constant namespace prefix elided from tool names; keys outside it (examples, third-party) keep every segment.\n */\nconst TOOL_NAME_KEY_PREFIX = 'org.dxos.operation.';\n\n/**\n * Derives the model-facing tool name for an operation from its DXN key — never from `meta.name`,\n * which is display copy and must stay freely editable without renaming the tool the model calls.\n * The key's namespace segment prefixes the name, which is what removes the cross-skill collisions\n * that a bare verb produced (three skills each claimed `create`).\n *\n * The mapping is not injective: kebab-casing makes a camelCase segment and an already-hyphenated one\n * converge, so `webSearch` and `web-search` both yield `web-search`, and hyphenated segments are in\n * live keys (`plugin-crm`, `web-search`). Registry-key uniqueness therefore does not by itself\n * guarantee tool-name uniqueness. Two such keys are an authoring error, caught in the two places both\n * keys are visible at once: {@link findToolNameCollisions} over a whole set, and the tool resolver.\n *\n * @example `org.dxos.operation.markdown.create` → `markdown-create`\n * @example `org.dxos.operation.assistantToolkit.addArtifact` → `assistant-toolkit-add-artifact`\n */\nexport const toolName = (op: Definition.Any): string => toolNameFromKey(op.meta.key);\n\n/**\n * {@link toolName} for a raw registry key (a DXN or bare NSID), e.g. a persisted record's meta key.\n */\nexport const toolNameFromKey = (key: string): string => {\n const name = deriveToolName(key);\n invariant(TOOL_NAME_REGEXP.test(name), `Invalid tool name: ${name}`);\n return name;\n};\n\n/** Shape every derived tool name must have — the model-facing identifier contract. */\nconst TOOL_NAME_REGEXP = /^[a-z][a-z0-9-_]*$/;\n\nconst deriveToolName = (key: string): string => {\n const nsid = DXN.isDXN(key) ? DXN.getName(key) : key;\n const stripped = nsid.startsWith(TOOL_NAME_KEY_PREFIX) ? nsid.slice(TOOL_NAME_KEY_PREFIX.length) : nsid;\n return stripped.split('.').map(kebabCase).join('-');\n};\n\nconst kebabCase = (segment: string): string => segment.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * {@link toolNameFromKey} for a key that is not known to be well-formed — a record off the wire, whose\n * `@meta.key` is untrusted JSON. Returns undefined instead of failing, so one malformed entry costs its\n * own tool rather than every tool in the projection.\n */\nexport const tryToolNameFromKey = (key: string): string | undefined => {\n const name = deriveToolName(key);\n return TOOL_NAME_REGEXP.test(name) ? name : undefined;\n};\n\n/**\n * Groups a set of operations by derived tool name, returning only the names claimed more than once.\n *\n * {@link toolName} is not injective (see its note), so a set of registry-unique keys can still\n * collide. Call this wherever a complete operation set is assembled — the resolver sees keys one at a\n * time and can only catch a collision once a colliding name is actually requested.\n */\nexport const findToolNameCollisions = (operations: readonly Definition.Any[]): Map<string, readonly DXN.DXN[]> => {\n // Keyed by key, not by occurrence: one operation bound by two skills is the same tool, not a clash.\n const byName = new Map<string, Set<DXN.DXN>>();\n for (const op of operations) {\n const name = toolName(op);\n byName.set(name, (byName.get(name) ?? new Set()).add(op.meta.key));\n }\n return new Map([...byName].filter(([, keys]) => keys.size > 1).map(([name, keys]) => [name, [...keys]]));\n};\n\n//\n// Invocation Interfaces\n//\n\n/**\n * Local invocation of an operation.\n */\nexport type Invoke = <I, O, E>(op: Definition<I, O>, input: I) => Effect.Effect<O, E>;\n\n/**\n * Remote invocation of an operation.\n */\nexport type InvokeRemote = <I, O, E>(\n op: Definition<I, O>,\n input: I,\n options?: { timeout?: number },\n) => Effect.Effect<O, E>;\n\n/**\n * Database record of an operation.\n * The registry `key` and `version` live in the object meta — access via\n * `Obj.getMeta(record).key` and `Obj.getMeta(record).version`.\n */\n// TODO(dmaretskyi): Keep typename as 'org.dxos.type.function' (not 'operation') to maintain\n// backward compatibility with existing data and avoid requiring data migration.\nexport class PersistentOperation extends Type.makeObject<PersistentOperation>(\n DXN.make('org.dxos.type.function', '0.2.0'),\n)(\n Schema$.Struct({\n name: Schema$.NonEmptyString,\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(Ref.Ref(Obj.Unknown)),\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 services the operation handler declares.\n */\n services: Schema$.optional(Schema$.Array(Schema$.String)),\n\n // Local binding to a function name.\n // TODO(dmaretskyi): Add this field to Operation.Definition.\n binding: Schema$.optional(Schema$.String),\n\n /**\n * Phosphor icon identifier in `ph--<name>--<variant>` format (e.g. `ph--file-text--regular`).\n */\n icon: Schema$.optional(Schema$.String),\n }).pipe(\n Annotation.LabelAnnotation.set(['name']),\n Annotation.IconAnnotation.set({ icon: 'ph--function--regular', hue: 'blue' }),\n ),\n) {}\n\nconst FUNCTION_META_KEY = 'org.dxos.service.function';\n\n/**\n * Get the registry key for a persistent operation record (from the object meta).\n */\nexport const getKey = (record: PersistentOperation): string | undefined => Obj.getMeta(record).key;\n\n/**\n * Get the registry version for a persistent operation record (from the object meta).\n */\nexport const getVersion = (record: PersistentOperation): string | undefined => Obj.getMeta(record).version;\n\n/**\n * Serialize an operation definition to a persistent operation record.\n */\nexport const serialize = (operation: Definition.Any, options?: Obj.MakeOptions): PersistentOperation => {\n return Obj.make(\n PersistentOperation,\n {\n [Obj.Meta]: {\n key: operation.meta.key,\n version: operation.meta.version ?? '0.0.0',\n keys: operation.meta.deployedId ? [{ source: FUNCTION_META_KEY, id: operation.meta.deployedId }] : [],\n annotations: operation.meta.annotations,\n },\n name: operation.meta.name ?? '',\n description: operation.meta.description,\n icon: operation.meta.icon,\n updated: undefined,\n source: undefined,\n inputSchema: JsonSchema.toJsonSchema(operation.input),\n outputSchema: JsonSchema.toJsonSchema(operation.output),\n services: operation.services.map((service) => service.key),\n },\n options,\n );\n};\n\n/**\n * Serializes each definition, dropping any whose schema cannot render as JSON Schema, so one\n * unserializable operation (e.g. `space.importSpace`) does not fail registry population for every\n * other.\n */\nexport const serializable = (operations: readonly Definition.Any[]): PersistentOperation[] =>\n operations.flatMap((operation) => {\n try {\n return [serialize(operation)];\n } catch (error) {\n log.verbose('operation is not serializable; excluded from the registry', {\n key: String(operation.meta.key),\n error: String(error),\n });\n return [];\n }\n });\n\n/**\n * Deserialize a persistent operation record to an operation definition.\n */\nexport const deserialize = (record: PersistentOperation): Definition.Any => {\n const meta = Obj.getMeta(record);\n // Extract deployed function ID from ECHO meta keys (matches FUNCTIONS_META_KEY in @dxos/functions).\n const deployedId = meta.keys.find((key) => key.source === FUNCTION_META_KEY)?.id;\n return make({\n input: record.inputSchema ? JsonSchema.toEffectSchema(record.inputSchema) : Schema$.Unknown,\n output: record.outputSchema ? JsonSchema.toEffectSchema(record.outputSchema) : Schema$.Unknown,\n services: record.services?.map((service) => Context.Service(service)) ?? [],\n executionMode: 'async',\n types: [],\n meta: {\n key: DXN.tryMake(meta.key ?? record.name) ?? DXN.make(meta.key ?? record.name),\n name: record.name,\n version: meta.version ?? '0.0.0',\n description: record.description,\n icon: record.icon,\n deployedId,\n annotations: meta.annotations ?? {},\n },\n });\n};\n\n/**\n * Update properties on the target operation record from the source operation record.\n */\nexport const setFrom = (target: PersistentOperation, source: PersistentOperation) => {\n Obj.update(target, (target) => {\n target.name = source.name ?? target.name;\n target.description = source.description;\n target.icon = source.icon;\n target.updated = source.updated;\n // TODO(dmaretskyi): A workaround for an ECHO bug.\n target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;\n target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;\n const sourceMeta = Obj.getMeta(source);\n const targetMeta = Obj.getMeta(target);\n targetMeta.key = sourceMeta.key ?? targetMeta.key;\n targetMeta.version = sourceMeta.version;\n // Only overwrite foreign keys when the source actually carries them; otherwise we'd wipe\n // bindings (e.g. the deployedId set by `deserialize`) on records produced by `serialize`.\n if (sourceMeta.keys.length > 0) {\n targetMeta.keys = JSON.parse(JSON.stringify(sourceMeta.keys));\n }\n targetMeta.annotations = sourceMeta.annotations ?? targetMeta.annotations;\n });\n};\n\n/**\n * Translatable label — a plain string or an i18next-style `[key, options]` tuple.\n * Defined locally to avoid a core dependency on UI translation packages; structurally compatible with\n * the app-level `Label` type so values flow into UI toasts unchanged.\n */\nexport const Label = Schema.Union([\n Schema.String,\n // `Schema.mutable` mirrors the app-level `Label` (whose tuple is mutable), so decoded values are\n // assignable to UI toast `title`/`label` slots without a readonly-vs-mutable tuple mismatch.\n Schema.mutable(\n Schema.Tuple([\n Schema.String,\n Schema.Struct({\n ns: Schema.String,\n count: Schema.optional(Schema.Number),\n defaultValue: Schema.optional(Schema.String),\n }).mapFields(Struct.map(Schema.mutableKey)),\n ]),\n ),\n]);\nexport type Label = Schema.Schema.Type<typeof Label>;\n\n/**\n * Per-phase user notification messages for an invocation.\n * A phase is notified to the user iff its message is provided; messages are translatable {@link Label}s.\n */\nexport const NotifyOptions = Schema.Struct({\n /** Shown when the invocation starts. */\n start: Schema.optional(Label),\n /** Shown when the invocation succeeds. */\n success: Schema.optional(Label),\n /** Shown when the invocation fails. */\n error: Schema.optional(Label),\n});\nexport type NotifyOptions = Schema.Schema.Type<typeof NotifyOptions>;\n\n/**\n * Annotation that configures the process to notify the user at the given invocation phases.\n */\nexport const NotifyOptionsAnnotation = Annotation.make({\n id: 'org.dxos.operation.notify-options',\n schema: NotifyOptions,\n});\n\n/**\n * A serializable reference to an operation invocation — the target operation's key plus its input.\n * Describes a deferred/late-bound invocation that must survive a serialization boundary (e.g. riding\n * on a process-failure error, or persisted) where a live {@link Definition} cannot. Resolve the key\n * with `OperationHandlerSet.getHandlerByKey` and hand the result to the invoker. Carries no functions,\n * so `input` must itself be serializable.\n */\nexport interface SerializedInvocation {\n /** Target operation key as a URI (a DXN, e.g. `dxn:org.dxos.plugin.deck.operation.open`). */\n readonly operation: URI.URI;\n /** Input passed to the operation; must be serializable. */\n readonly input?: unknown;\n}\n\n/**\n * Builds a {@link SerializedInvocation} from a live {@link Definition} and its input — the serializable\n * counterpart to a direct `invoke`, for describing an invocation that must cross a serialization\n * boundary (e.g. a deferred toast action). Resolve it later with `OperationHandlerSet.getHandlerByKey`.\n */\nexport const prepare = <I, O>(operation: Definition<I, O>, input: I): SerializedInvocation => ({\n operation: operation.meta.key,\n input,\n});\n\n/**\n * Options for operation invocation.\n */\nexport interface InvokeOptions {\n /**\n * Space ID to provide database context for the handler.\n */\n spaceId?: Key.SpaceId;\n /**\n * Request user-facing notifications at the given invocation phases.\n */\n notify?: NotifyOptions;\n /**\n * URI of the conversation feed (queue) — today always an EID, but typed as\n * `URI.URI` to accommodate future entity-kind extensions. Narrow with `EID.parse`\n * at the point of use.\n * Passed to the process environment so nested operations can resolve HarnessService and related services.\n */\n conversation?: URI.URI;\n /**\n * Tracing metadata stamped on the process that runs the invocation.\n */\n tracing?: Trace.Meta;\n\n /**\n * Specifies the runtime environment for the operation.\n * By default, the operation is executed on the local runtime.\n */\n on?: 'edge' | 'local';\n}\n\n/**\n * Annotation that marks an operation as idempotent — safe to retry even if a previous execution\n * was interrupted mid-handler. When absent the operation is treated as non-idempotent, and the\n * process runtime will fail (rather than re-run) any handler that was interrupted.\n */\nexport const IdempotentAnnotation = Annotation.make({\n id: 'org.dxos.operation.idempotent',\n schema: Schema$.Boolean,\n});\n\n/**\n * Returns true when the operation is explicitly annotated as idempotent.\n */\nexport const isIdempotent = (op: Definition.Any): boolean =>\n op.meta.annotations\n ? Option.getOrElse(Annotation.getDictionary(op.meta.annotations, IdempotentAnnotation), () => false)\n : false;\n\n/**\n * Attaches an annotation to an operation definition, returning a new definition.\n * Combinators never mutate their input — operation definitions are module-level singletons\n * shared across handler sets, skills, and the registry, so a fresh value keeps the\n * annotated definition distinct from any other reference to the original.\n *\n * Type-preserving: an annotation does not change the operation's input/output/service types, so the\n * returned definition keeps `Def` (preserving `withHandler` inference and downstream usage).\n */\nexport const annotate =\n <T>(annotation: Annotation.Annotation<T>, value: T) =>\n <Def extends Definition.Any>(op: Def): Def => {\n const annotations = { ...(op.meta.annotations ?? {}) };\n Annotation.setDictionary(annotations, annotation, value);\n // The spread reconstructs the same shape with only `meta.annotations` changed; the checker can't\n // track the branded variance symbol through the untyped dictionary mutation, so reassert `Def`.\n return { ...op, meta: { ...op.meta, annotations } } as Def;\n };\n\n/**\n * Marks an operation as visible on user-facing operation surfaces (trigger/automation pickers,\n * manual invocation). Absent ⇒ internal: invoked programmatically by plugins and hidden from pickers.\n *\n * Same polarity as the schema-level `Annotation.UserType`: operations are hidden by default, since most\n * are internal plugin machinery and only a minority are user-facing.\n */\nexport const VisibleAnnotation = Annotation.make({\n id: 'org.dxos.operation.visible',\n schema: Schema$.Boolean,\n});\n\n/**\n * The operation's effect on state: `none` is side-effect free, `write` mutates but is not\n * irreversible, `destructive` deletes or otherwise cannot be undone. Absent ⇒ unclassified, which\n * consumers treat conservatively (an MCP client badges the tool as possibly destructive).\n */\nexport const MutationAnnotation = Annotation.make({\n id: 'org.dxos.operation.mutation',\n schema: Schema$.Literals(['none', 'write', 'destructive']),\n});\n\nexport type Mutation = Schema$.Schema.Type<typeof MutationAnnotation.schema>;\n\n/**\n * Pipeable combinator classifying the operation's effect on state — see {@link MutationAnnotation}.\n * Apply at the definition site: `Operation.make({ ... }).pipe(Operation.mutation('none'))`.\n */\nexport const mutation = (value: Mutation) => annotate(MutationAnnotation, value);\n\n/** The operation's mutation class, or undefined when unclassified. Reads from the persisted record. */\nexport const getMutation = (op: PersistentOperation): Mutation | undefined =>\n Option.getOrUndefined(Annotation.get(op, MutationAnnotation));\n\n/**\n * Pipeable combinator that marks an operation visible. Apply at the definition site:\n * `Operation.make({ ... }).pipe(Operation.visible)`.\n */\nexport const visible = annotate(VisibleAnnotation, true);\n\n/**\n * Returns true when an operation is annotated as visible on user-facing surfaces (trigger/automation\n * pickers, manual invocation). Reads from the persisted operation — the form every consumer holds.\n */\nexport const isVisible = (op: PersistentOperation): boolean =>\n Option.getOrElse(Annotation.get(op, VisibleAnnotation), () => false);\n\n/**\n * Pipeable combinator that marks an operation idempotent — see {@link IdempotentAnnotation}. Apply at\n * the definition site: `Operation.make({ ... }).pipe(Operation.idempotent)`.\n */\nexport const idempotent = annotate(IdempotentAnnotation, true);\n\n/**\n * Operation service interface - provides unified access to operation invocation and scheduling.\n * This service is automatically provided to operation handlers.\n */\nexport interface OperationService {\n /**\n * Invoke an operation as an Effect.\n * Returns an Effect that resolves to the operation output.\n */\n invoke: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Effect.Effect<O, NoHandlerError>;\n\n /**\n * Schedule an operation to run as a followup.\n * The followup is tracked and won't be cancelled when the parent operation completes.\n * Returns an Effect that completes immediately after scheduling.\n */\n schedule: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Effect.Effect<void>;\n\n /**\n * Invoke an operation and return a Promise.\n * Useful for async contexts where Effect is not available.\n */\n invokePromise: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Promise<{ data?: O; error?: Error }>;\n}\n\n/**\n * Context tag for the Operation service.\n * Operation handlers can yield this to invoke other operations or schedule followups.\n *\n * @example\n * ```ts\n * const handler = (input) => Effect.gen(function* () {\n * // Schedule a followup (fire and forget)\n * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });\n *\n * // Invoke another operation\n * return yield* Operation.invoke(OtherOperation, { data: input.data });\n * });\n * ```\n */\n// TODO(dmaretskyi): Rename Operation.Invoker\nexport class Service extends Context.Service<Service, OperationService>()('@dxos/operation/Service') {}\n\n//\n// Namespace functions - ergonomic access to Operation.Service methods.\n//\n\n/**\n * Invoke an operation as an Effect.\n * Yields the Operation.Service internally.\n *\n * @example\n * ```ts\n * yield* Operation.invoke(MyOperation, { data: 'test' });\n * ```\n */\nexport const invoke = <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n): Effect.Effect<O, NoHandlerError, Service> =>\n Effect.flatMap(Service, (ops) => ops.invoke(op, ...(args as [I, InvokeOptions?]))).pipe(\n Effect.withSpan('Operation.invoke'),\n );\n\n/**\n * Schedule an operation to run as a followup.\n * Yields the Operation.Service internally.\n *\n * @example\n * ```ts\n * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });\n * yield* Operation.schedule(VoidOperation); // input optional when void\n * ```\n */\nexport const schedule = <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n): Effect.Effect<void, never, Service> =>\n Effect.flatMap(Service, (ops) => ops.schedule(op, ...(args as [I, InvokeOptions?]))).pipe(\n Effect.withSpan('Operation.schedule'),\n );\n\n/**\n * Call inside an operation to stop the current invocation and have the system re-run it (e.g. a capped\n * sync run with more work left). Surfaces as a {@link RunAgainError} defect; the trigger dispatcher\n * re-queues the same event FIFO to continue. A caller invoking via `Operation.invoke` directly gets the\n * defect and does not auto-continue.\n */\nexport const runAgain = (): Effect.Effect<never, void> => Effect.failCauseSync(() => Cause.die(new RunAgainError()));\n\n/**\n * Provides additional invocation options to all invocations.\n */\nexport const withInvocationOptions = (options: InvokeOptions): Layer.Layer<Service, never, Service> =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const service = yield* Service;\n return Service.of({\n invoke: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.invoke(op, input, { ...options, ...invocationOptions })) as any,\n invokePromise: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.invokePromise(op, input, { ...options, ...invocationOptions })) as any,\n schedule: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.schedule(op, input, { ...options, ...invocationOptions })) as any,\n });\n }),\n );\n\n//\n// Legacy schemas and migrations.\n//\n\n/**\n * Persistent operation schema v0.1.0 — `key` and `version` are stored as data properties.\n * @deprecated Use {@link PersistentOperation} (v0.2.0) instead; the `key` and `version` now live in the object meta.\n */\nexport class PersistentOperation_v0_1_0 extends Type.makeObject<PersistentOperation_v0_1_0>(\n DXN.make('org.dxos.type.function', '0.1.0'),\n)(\n Schema$.Struct({\n key: Schema$.optional(Schema$.String),\n name: Schema$.NonEmptyString,\n version: Schema$.String,\n description: Schema$.optional(Schema$.String),\n updated: Schema$.optional(Schema$.String),\n source: Schema$.optional(Ref.Ref(Obj.Unknown)),\n inputSchema: Schema$.optional(JsonSchema.JsonSchema),\n outputSchema: Schema$.optional(JsonSchema.JsonSchema),\n services: Schema$.optional(Schema$.Array(Schema$.String)),\n binding: Schema$.optional(Schema$.String),\n }),\n) {}\n\n/**\n * Migration from {@link PersistentOperation_v0_1_0} (v0.1.0) to {@link PersistentOperation} (v0.2.0).\n * Moves `key` and `version` from the data section into the object meta.\n */\nconst _migration = Migration.define({\n from: PersistentOperation_v0_1_0,\n to: PersistentOperation,\n transform: async (from) => ({\n [Obj.Meta]: { key: from.key, version: from.version },\n name: from.name,\n description: from.description,\n updated: from.updated,\n source: from.source,\n inputSchema: from.inputSchema,\n outputSchema: from.outputSchema,\n services: from.services,\n binding: from.binding,\n }),\n});\n\n/**\n * Schema migrations exported by this module.\n * Exported as an array for extensibility — append future versions here.\n */\nexport const migrations = [_migration];\n\nexport {\n FunctionError,\n FunctionNotFoundError,\n InvalidOperationInputError,\n InvalidOperationOutputError,\n InvokerNotInitializedError,\n NoHandlerError,\n} from './errors.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,mBAAmB;AA+GhC,IAAa,oBAAoB;;AAejC,IAAa,iBAAiB,UAC5B,OAAO,UAAU,YAAY,UAAU,QAAA,kCAA6B;;;;;;;;;;AAWtE,IAAa,gBAIX,UACA,SACG;CACH,MAAM,QAAQ,IAAS,YAA4E;GAChG,oBAAoB;EACrB,YAAY;EACZ,MAAM;CACR;CACA,OAAO,SAAS,KAAA,KACX,OAAY,KAAK,IAAI,QAAwD,IAC9E,KAAK,UAAiB,IAAI;AAChC;;;;AAKA,IAAa,yBAAyB,UAA4C;CAChF,OAAO,OAAO,UAAU,YAAY,UAAU,QAAA,0CAA4B;AAC5E;;;;AAKA,IAAa,0BAA0B,UAAyD;CAC9F,OAAO,sBAAsB,KAAK,KAAK,aAAa;AACtD;;;;;;AAiBA,IAAa,QACX,UAKG;CACH,OAAO;GACJ,mBAAmB,CAAC;EACrB,GAAG;EACH,eAAe,MAAM,iBAAiB;EACtC,OAAO,MAAM,SAAS,CAAC;EACvB,UAAU,MAAM,YAAY,CAAC;EAC7B,OAAO;GAEL,OAAO,SAAS,cAAc,MAAM,SAAS;EAC/C;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,eASX,a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Content":["//\n// Copyright 2025 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Cause from 'effect/Cause';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport type * as Exit from 'effect/Exit';\nimport * as Function from 'effect/Function';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\nimport * as Pipeable from 'effect/Pipeable';\nimport * as Rpc from 'effect/rpc/Rpc';\nimport * as RpcGroup from 'effect/rpc/RpcGroup';\nimport * as Schema from 'effect/Schema';\nimport * as Schema$ from 'effect/Schema';\nimport * as Scope from 'effect/Scope';\nimport * as Struct from 'effect/Struct';\nimport type * as Types from 'effect/Types';\n\nimport { Annotation, DXN, JsonSchema, type Key, Migration, Obj, Ref, Type } from '@dxos/echo';\nimport { BaseError } from '@dxos/errors';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport type { URI } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { type NoHandlerError, RunAgainError } from './errors.ts';\nimport type { Operation } from './index.ts';\nimport type * as Process from './Process.ts';\nimport type * as StorageService from './StorageService.ts';\nimport type * as Trace from './Trace.ts';\nimport type * as Script from './types/Script.ts';\n\n/**\n * Schema type that accepts any Encoded form but requires no Context.\n * This allows ECHO object schemas where Type !== Encoded due to [KindId] symbol.\n */\ntype Schema<T> = Schema$.Codec<T, any, never, never>;\n\nexport const DefinitionTypeId = '~@dxos/operation/OperationDefinition' as const;\nexport type DefinitionTypeId = typeof DefinitionTypeId;\n\n/**\n * Serializable definition of an Operation.\n * Contains schema and metadata, but no runtime logic.\n */\nexport interface Definition<I, O, S = any> extends Pipeable.Pipeable, Definition.Variance<I, O, S> {\n /**\n * Input schema for the operation.\n */\n readonly input: Schema<I>;\n /**\n * Output schema for the operation.\n */\n readonly output: Schema<O>;\n\n readonly meta: {\n readonly key: DXN.DXN;\n readonly name?: string;\n readonly version?: string;\n readonly description?: string;\n /**\n * Phosphor icon identifier in `ph--<name>--<variant>` format (e.g. `ph--file-text--regular`).\n */\n readonly icon?: string;\n /**\n * Deployment ID for remote invocation.\n * Assigned by the EDGE function service when deployed.\n */\n readonly deployedId?: string;\n\n /**\n * Dictionary of annotations for the operation.\n */\n // TODO(dmaretskyi): Make required, but this complicates `make` to fill in defaults.\n readonly annotations?: Annotation.Dictionary;\n\n /**\n * When true, this operation is not serialized into the hypergraph registry.\n * Use for UI-only operations that should not be discoverable by the AI agent.\n */\n readonly skipRegistry?: boolean;\n };\n\n /**\n * Execution mode for the operation.\n * - 'sync': Operation completes synchronously (fast, UI-blocking acceptable).\n * - 'async': Operation may take time (should not block UI).\n */\n readonly executionMode: 'sync' | 'async';\n\n /**\n * ECHO types the operation uses.\n * Ensures types are available when the operation is executed remotely.\n */\n readonly types: readonly Type.AnyEntity[];\n\n /**\n * Effect services required by this operation.\n * These services will be automatically provided to the handler at invocation time.\n */\n readonly services: readonly Context.Key<S, unknown>[];\n}\n\n/**\n * Namespace for OperationDefinition helper types.\n */\nexport declare namespace Definition {\n export interface Variance<I, O, S> {\n [DefinitionTypeId]: {\n readonly _Input: Types.Contravariant<I>;\n readonly _Output: Types.Covariant<O>;\n readonly _Services: Types.Covariant<S>;\n };\n }\n\n /**\n * Any operation definition, regardless of input/output types.\n */\n export type Any = Definition<any, any, any>;\n\n /**\n * Extract the input type from an operation definition.\n */\n export type Input<T extends Any> = T extends Variance<infer I, infer _O, infer _S> ? I : never;\n\n /**\n * Extract the output type from an operation definition.\n */\n export type Output<T extends Any> = T extends Variance<infer _I, infer O, infer _S> ? O : never;\n\n /**\n * Extract the service identifier types from an operation's services array.\n * Returns `never` if the operation has no services declared.\n */\n export type Services<T extends Any> = T extends Variance<infer _I, infer _O, infer S> ? S : never;\n\n export type HandlerType<T extends Any> =\n T extends Variance<infer I, infer O, infer S> ? Handler<I, O, any, S> : never;\n}\n\n/**\n * Runtime handler for an Operation.\n */\nexport type Handler<I, O, E = Error, R = never> = (input: I) => Effect.Effect<O, E, R>;\n\nexport type WithHandler<T extends Definition.Any> = T & {\n handler: Definition.HandlerType<T>;\n};\n\nexport const LazyHandlerTypeId = '~@dxos/operation/LazyHandler' as const;\nexport type LazyHandlerTypeId = typeof LazyHandlerTypeId;\n\n/**\n * A definition paired with the module that implements it. The pairing is TYPED — the loaded\n * module's default must be `WithHandler<Def>` for the same `Def` — so a definition can no longer be\n * wired to another operation's handler and fail only at dispatch.\n */\nexport interface LazyHandler<Def extends Definition.Any = Definition.Any> {\n readonly [LazyHandlerTypeId]: LazyHandlerTypeId;\n readonly definition: Def;\n readonly load: () => Promise<{ default: WithHandler<Def> }>;\n}\n\n/** Whether a value is a {@link LazyHandler}. */\nexport const isLazyHandler = (value: unknown): value is LazyHandler =>\n typeof value === 'object' && value !== null && LazyHandlerTypeId in value;\n\n/**\n * Pairs a definition with a lazily-imported handler module, keeping the handler body out of the\n * static graph while checking that it implements THIS definition.\n *\n * @example\n * ```ts\n * GetBlueskyTargets.pipe(Operation.lazyHandler(() => import('./get-bluesky-targets')))\n * ```\n */\nexport const lazyHandler: {\n <Def extends Definition<any, any>>(load: () => Promise<{ default: WithHandler<Def> }>): (op: Def) => LazyHandler<Def>;\n <Def extends Definition<any, any>>(op: Def, load: () => Promise<{ default: WithHandler<Def> }>): LazyHandler<Def>;\n} = (<Def extends Definition<any, any>>(\n opOrLoad: Def | (() => Promise<{ default: WithHandler<Def> }>),\n load?: () => Promise<{ default: WithHandler<Def> }>,\n) => {\n const make = (op: Def, loader: () => Promise<{ default: WithHandler<Def> }>): LazyHandler<Def> => ({\n [LazyHandlerTypeId]: LazyHandlerTypeId,\n definition: op,\n load: loader,\n });\n return load === undefined\n ? (op: Def) => make(op, opOrLoad as () => Promise<{ default: WithHandler<Def> }>)\n : make(opOrLoad as Def, load);\n}) as any;\n\n/**\n * Checks if a value is an operation definition.\n */\nexport const isOperationDefinition = (value: unknown): value is Definition.Any => {\n return typeof value === 'object' && value !== null && DefinitionTypeId in value;\n};\n\n/**\n * Checks if a value is an operation with a handler.\n */\nexport const isOperationWithHandler = (value: unknown): value is WithHandler<Definition.Any> => {\n return isOperationDefinition(value) && 'handler' in value;\n};\n\n/**\n * Props for creating an Operation definition.\n * Derived from OperationDefinition with executionMode made optional (defaults to 'async').\n */\nexport type Props<I, O> = Omit<Definition<I, O>, DefinitionTypeId | 'pipe' | 'executionMode' | 'types' | 'services'> & {\n readonly executionMode?: 'sync' | 'async';\n readonly types?: Definition<I, O>['types'];\n readonly services?: Definition<I, O>['services'];\n};\n\n/**\n * Creates a new Operation definition.\n * Applies default executionMode of 'async' if not specified.\n * The returned type preserves the literal types of props (including services).\n */\nexport const make = <const P extends Types.NoExcessProperties<Props<any, any>, P>>(\n props: P,\n): Definition<\n Schema$.Schema.Type<P['input']>,\n Schema$.Schema.Type<P['output']>,\n Context.Service.Identifier<NonNullable<P['services']>[number]>\n> => {\n return {\n [DefinitionTypeId]: {},\n ...props,\n executionMode: props.executionMode ?? 'async',\n types: props.types ?? [],\n services: props.services ?? [],\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n },\n } as any;\n};\n\n/**\n * Attaches a handler to an Operation definition.\n * The handler may use any services declared in the operation, plus Operation.Service (always available).\n * Dual API: can be called directly or used in a pipe.\n *\n * @example\n * ```ts\n * const MyOp = Operation.make({\n * input: Schema.Void,\n * output: Schema.Void,\n * meta: { key: 'my-op' },\n * services: [DatabaseService],\n * });\n *\n * // Direct call - handler can use DatabaseService\n * const op = Operation.withHandler(MyOp, (input) =>\n * Effect.gen(function* () {\n * const db = yield* DatabaseService;\n * return {};\n * }),\n * );\n *\n * // Piped call\n * const op = MyOp.pipe(Operation.withHandler((input) => Effect.succeed({})));\n * ```\n */\nexport const withHandler: {\n <Def extends Definition<any, any>, E = never>(\n handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n ): (op: Def) => WithHandler<Def>;\n <Def extends Definition<any, any>, E = never>(\n op: Def,\n handler: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n ): WithHandler<Def>;\n} = <Def extends Definition<any, any>, E = never>(\n opOrHandler: Def | Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n handler?: Handler<Definition.Input<Def>, Definition.Output<Def>, E, Definition.Services<Def> | Service>,\n): WithHandler<Def> => {\n // If called with just handler (piped usage).\n if (handler === undefined) {\n const handlerFn = opOrHandler as Handler<\n Definition.Input<Def>,\n Definition.Output<Def>,\n E,\n Definition.Services<Def> | Service\n >;\n return ((op: Def) => ({\n ...op,\n handler: handlerFn,\n })) as any;\n }\n\n // If called with both op and handler (direct usage).\n const op = opOrHandler as Def;\n return {\n ...op,\n handler,\n } as any;\n};\n\n/**\n * Helper to make the handler type opaque.\n * Workaround for TypeScript's inability to infer the handler type from the operation definition:\n * ```\n * error TS2742: The inferred type of 'default' cannot be named without a reference.\n * ```\n *\n * Most of the time the exact handler type is not needed.\n *\n * @example\n * ```ts\n * const MyOp = Operation.make({\n * input: Schema.Void,\n * output: Schema.Void,\n * meta: { key: 'my-op' },\n * services: [DatabaseService],\n * });\n *\n * export default MyOp.pipe(\n * Operation.withHandler(\n * Effect.fn(function* (input) {\n * return { result: 'ok' };\n * }),\n * ),\n * Operation.opaqueHandler,\n * );\n * ```\n */\nexport const opaqueHandler = <T extends Operation.Definition.Any>(\n handler: Operation.WithHandler<T>,\n): Operation.WithHandler<Operation.Definition.Any> => handler;\n\n//\n// Durable operations.\n//\n\n/**\n * Handler of a durable operation: the callbacks of one running process instance.\n *\n * Process lifecycle: Initial -> Running <-> Suspended -> Terminated.\n *\n * - onSpawn -> called once when the process is spawned.\n * - onInput -> called for every input submitted to the process.\n * - onAlarm -> called for processes scheduling alarms.\n * - onChildEvent -> called when child process produces output or exits.\n */\nexport interface DurableHandler<_Input, _Output, _Requirements, _Rpcs extends Rpc.Any> {\n /**\n * Called when the process is spawned.\n * Not called for processes that are resumed from a previously suspended state.\n *\n * @returns A signal indicating to the runtime whether the process is finished, or should be resumed later.\n * @throws Throwing in the handler will terminate the process with an error.\n *\n * Note: This function should aim to complete in under 5 seconds to avoid exceeding limits in serverless environments.\n */\n onSpawn(): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Called when there's input available to process.\n *\n * The function can be called in parallel.\n *\n * @returns A signal indicating to the runtime whether the process is finished, or should be resumed later.\n * @throws Throwing in the handler will terminate the process with an error.\n *\n * Note: This function should aim to complete in under 5 seconds to avoid exceeding limits in serverless environments.\n */\n onInput(input: _Input): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Called when the process's alarm is triggered.\n *\n * @throws Throwing in the handler will terminate the process with an error.\n */\n onAlarm(): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Called when the process's child process produces output or exits.\n *\n * This allows the parent process to hibernate while a long-running child process is running.\n */\n onChildEvent(event: ChildEvent<unknown>): Effect.Effect<void, never, _Requirements | BaseServices>;\n\n /**\n * Handlers for the RPCs provided by the process.\n */\n rpcHandlers: Context.Context<Rpc.ToHandler<_Rpcs>>;\n}\n\n/**\n * Services that are always available to all processes.\n * Provided unconditionally by the runtime, so handlers may use them without declaring them\n * in {@link DurableProps.services}.\n */\nexport type BaseServices = Trace.TraceService | StorageService.StorageService;\n\nexport type ChildEvent<T> =\n | {\n readonly _tag: 'output';\n readonly pid: Process.ID;\n readonly data: T;\n }\n | {\n readonly _tag: 'exited';\n readonly pid: Process.ID;\n readonly result: Exit.Exit<void>;\n };\n\n/**\n * Runtime context handed to a durable operation's `create`.\n */\nexport interface DurableContext<I, O> {\n readonly id: Process.ID;\n\n /**\n * Parameters assigned during process creation.\n */\n readonly params: Process.Params;\n\n /**\n * Complete this process with sucessful result.\n * No additional events will be pushed to the process.\n */\n succeed(): void;\n\n /**\n * Complete this process with an error.\n * No additional events will be pushed to the process.\n */\n fail(error: Error): void;\n\n /**\n * Submit output of the process.\n */\n submitOutput(output: O): void;\n\n /**\n * Set an alarm for the process to be woken up later. `onAlarm` runs with the process's own\n * context, not the caller's: an alarm scheduled from inside a handler does not nest under it.\n *\n * @param timeout - Optional timeout in milliseconds. If not provided, the process is woken up as soon as possible.\n */\n setAlarm(timeout?: number): Effect.Effect<void>;\n}\n\nexport const DurableDefinitionTypeId = '~@dxos/operation/DurableDefinition' as const;\nexport type DurableDefinitionTypeId = typeof DurableDefinitionTypeId;\n\n/**\n * Declaration of a durable operation, without its handler.\n * Created by {@link makeDurable}; {@link withDurableHandler} attaches the handler factory to produce a {@link Durable}.\n */\nexport interface DurableDefinition<_Input, _Output, _Requirements = never, _Rpcs extends Rpc.Any = never>\n extends Pipeable.Pipeable, DurableDefinition.Variance<_Input, _Output, _Requirements, _Rpcs> {\n /**\n * Unique identifier for the executable in the reverse DNS format.\n */\n readonly key: string;\n\n /**\n * Human-readable label, when provided.\n */\n readonly name?: string;\n\n readonly services: readonly Context.Key<any, any>[];\n\n /** See {@link DurableProps.optionalServices}. */\n readonly optionalServices?: readonly Context.Key<any, any>[];\n\n /**\n * Codecs for the process's inputs and outputs, from {@link DurableProps}. Exposed on the\n * interface so a caller that moves a value across a boundary (a remote runtime) can encode it\n * with the definition's own schema rather than assuming the value is already JSON.\n */\n readonly input: Schema.Codec<_Input, any>;\n readonly output: Schema.Codec<_Output, any>;\n\n /** Schemas to register with the process's database; see {@link DurableProps.types}. */\n readonly types?: readonly Type.AnyEntity[];\n\n /** See {@link DurableProps.resumable}. */\n readonly resumable?: boolean;\n\n // Runtime RPC group, stored as `any`. `RpcGroup`/`RpcClient` are invariant in their type\n // argument (and `DurableHandler.rpcHandlers` is contravariant in it), so referencing `_Rpcs` in the\n // structural fields would block `Durable<…, never>` from being assignable to `Durable.Any`.\n // The precise group is carried by the covariant `Variance` phantom and recovered at `spawn`.\n // See design spec §4.4.\n readonly rpcs: RpcGroup.RpcGroup<any>;\n}\n\nexport declare namespace DurableDefinition {\n export interface Variance<_Input, _Output, _Requirements, _Rpcs> {\n readonly [DurableDefinitionTypeId]: {\n readonly _Input: Types.Contravariant<_Input>;\n readonly _Output: Types.Covariant<_Output>;\n readonly _Requirements: Types.Covariant<_Requirements>;\n\n // Phantom-covariant: lets `never`-RPC processes stay assignable to `Durable.Any` while\n // `spawn` still recovers the precise group from this slot. See design spec §4.4.\n readonly _Rpcs: Types.Covariant<_Rpcs>;\n };\n }\n\n export type Any = DurableDefinition<any, any, any, any>;\n\n export type Input<T extends Any> = T extends Variance<infer I, infer _O, infer _R, infer _P> ? I : never;\n export type Output<T extends Any> = T extends Variance<infer _I, infer O, infer _R, infer _P> ? O : never;\n export type Requirements<T extends Any> = T extends Variance<infer _I, infer _O, infer R, infer _P> ? R : never;\n export type Rpcs<T extends Any> =\n T extends Variance<infer _I, infer _O, infer _R, infer P extends Rpc.Any> ? P : never;\n\n /**\n * The handler factory {@link withDurableHandler} accepts for a definition: callbacks may be omitted and default to no-ops.\n */\n export type Create<T extends Any> = (\n ctx: DurableContext<Input<T>, Output<T>>,\n ) => Effect.Effect<\n Partial<DurableHandler<Input<T>, Output<T>, Requirements<T>, Rpcs<T>>>,\n never,\n Requirements<T> | BaseServices | Scope.Scope\n >;\n\n /**\n * The durable operation produced by attaching a handler to a definition.\n */\n export type WithHandler<T extends Any> = Durable<Input<T>, Output<T>, Requirements<T>, Rpcs<T>>;\n}\n\nexport const DurableTypeId = '~@dxos/operation/Durable' as const;\nexport type DurableTypeId = typeof DurableTypeId;\n\n/**\n * A durable operation: declaration plus a handler factory, run by a process runtime.\n * Can be instantiated multiple times to produce new process instances with separate state and handlers.\n * `create` is used to instantiate a new process.\n * Can store runtime state in scope of `create` function.\n */\nexport interface Durable<_Input, _Output, _Requirements = never, _Rpcs extends Rpc.Any = never>\n extends\n DurableDefinition<_Input, _Output, _Requirements, _Rpcs>,\n Durable.Variance<_Input, _Output, _Requirements, _Rpcs> {\n /**\n * Create a new instance of the process.\n */\n create(\n ctx: DurableContext<_Input, _Output>,\n ): Effect.Effect<\n DurableHandler<_Input, _Output, _Requirements, any>,\n never,\n _Requirements | BaseServices | Scope.Scope\n >;\n}\n\nexport const isDurableDefinition = (value: unknown): value is DurableDefinition.Any =>\n typeof value === 'object' && value !== null && DurableDefinitionTypeId in value;\n\nexport const isDurable = (executable: unknown): executable is Durable.Any =>\n typeof executable === 'object' && executable !== null && DurableTypeId in executable;\n\nexport namespace Durable {\n export interface Variance<_Input, _Output, _Requirements, _Rpcs> {\n readonly [DurableTypeId]: {\n readonly _Input: Types.Contravariant<_Input>;\n readonly _Output: Types.Covariant<_Output>;\n readonly _Requirements: Types.Covariant<_Requirements>;\n readonly _Rpcs: Types.Covariant<_Rpcs>;\n };\n }\n\n export type Any = Durable<any, any, any, any>;\n}\n\nexport interface DurableProps {\n /**\n * Unique identifier for the process in the reverse DNS format.\n */\n readonly key: string;\n\n /**\n * Human-readable label; `Process.spawn` names the process after it.\n */\n readonly name?: string;\n\n readonly input: Schema.Codec<any, any>;\n readonly output: Schema.Codec<any, any>;\n readonly services: readonly Context.Key<any, any>[];\n\n /**\n * Services the process uses when the runtime has them: it gets each one that resolves and runs without the rest,\n * so the handler reads them with `Effect.serviceOption`.\n */\n readonly optionalServices?: readonly Context.Key<any, any>[];\n readonly rpcs?: RpcGroup.RpcGroup<any>;\n\n /**\n * Schemas the process's own data model needs, registered with its database at spawn.\n *\n * Declared here beside `services` because a host cannot know them: it resolves a process by key\n * and has no view of the types that process queries. Unregistered, a TYPED query silently matches\n * nothing — a queue append succeeds and the read back returns empty, which reads as a lost write\n * rather than a missing schema.\n */\n readonly types?: readonly Type.AnyEntity[];\n\n /**\n * False when a process interrupted by a restart could only fail on resuming. Such a process is kept in\n * memory rather than persisted, unless a persisted parent waits on it. Defaults to true.\n */\n readonly resumable?: boolean;\n}\n\n/**\n * Declares a durable operation; attach its handler factory with {@link withDurableHandler}.\n *\n * @example\n * ```ts\n * const Counter = Operation.makeDurable({ key: 'example.counter', input: Schema.Number, output: Schema.Number, services: [] }).pipe(\n * Operation.withDurableHandler((ctx) =>\n * Effect.succeed({ onInput: (input) => Effect.sync(() => ctx.submitOutput(input + 1)) }),\n * ),\n * );\n * ```\n */\nexport const makeDurable = <const Opts extends Types.NoExcessProperties<DurableProps, Opts>>(\n opts: Opts,\n): DurableDefinition<\n Schema.Schema.Type<Opts['input']>,\n Schema.Schema.Type<Opts['output']>,\n Context.Service.Identifier<NonNullable<Opts['services']>[number]>,\n RpcGroup.Rpcs<Opts['rpcs']>\n> => {\n assertArgument(/^[a-z0-9]([a-z0-9.\\-/]*[a-z0-9])?$/i.test(opts.key), 'key', 'Invalid key');\n return {\n [DurableDefinitionTypeId]: {} as any,\n ...opts,\n rpcs: opts.rpcs ?? RpcGroup.make(),\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n },\n };\n};\n\n/**\n * Attaches the handler factory to a durable operation definition.\n * Dual API: can be called directly or used in a pipe.\n */\nexport const withDurableHandler: {\n <Def extends DurableDefinition.Any>(\n create: DurableDefinition.Create<Def>,\n ): (def: Def) => DurableDefinition.WithHandler<Def>;\n <Def extends DurableDefinition.Any>(\n def: Def,\n create: DurableDefinition.Create<Def>,\n ): DurableDefinition.WithHandler<Def>;\n} = Function.dual(2, <Def extends DurableDefinition.Any>(def: Def, create: DurableDefinition.Create<Def>) =>\n attachDurableHandler(def, create),\n);\n\nconst attachDurableHandler = <Def extends DurableDefinition.Any>(\n def: Def,\n create: DurableDefinition.Create<Def>,\n): DurableDefinition.WithHandler<Def> => ({\n ...def,\n [DurableTypeId]: {} as any,\n create: (ctx) =>\n create(ctx).pipe(\n Effect.map((partial) => ({\n onSpawn: () => Effect.void,\n onInput: () => Effect.void,\n onAlarm: () => Effect.void,\n onChildEvent: () => Effect.void,\n ...partial,\n rpcHandlers: sanitizeRpcs(def.rpcs, partial.rpcHandlers),\n })),\n ),\n});\n\n// Returns `Context.Context<any>`: the runtime handler bag is stored untyped because\n// `DurableHandler.rpcHandlers` is contravariant in `_Rpcs` (see design spec §4.4); the precise\n// handler contract is enforced by `withDurableHandler`'s `create` parameter, not by this internal helper.\nconst sanitizeRpcs = <Rpcs extends Rpc.Any>(\n defined: RpcGroup.RpcGroup<Rpcs> | undefined,\n provided: Context.Context<Rpc.ToHandler<Rpcs>> | undefined,\n): Context.Context<any> => {\n // Handlers are required only when a non-empty RPC group is declared.\n const needsRpcs = defined !== undefined && defined.requests.size > 0;\n if (!needsRpcs) {\n // `Context.empty()` is `Context<never>`; `Context`'s requirement parameter is contravariant,\n // so the empty (no-handler) context needs widening to the untyped bag.\n return provided ?? (Context.empty() as Context.Context<any>);\n }\n if (!provided) {\n throw new TypeError('Durable operation declared RPCs but did not provide any handlers');\n }\n return provided;\n};\n\n//\n// Script operations.\n//\n\n/**\n * Language an inline script snippet is written in.\n *\n * Carried by the snippet rather than by the runtime, because one runtime serves several: a code-mode\n * turn writes `plain` or `effect` against the same host that runs a `typescript` module.\n */\nexport const ScriptDialect = Schema$.Literals(['plain', 'effect', 'javascript', 'typescript']);\nexport type ScriptDialect = Schema$.Schema.Type<typeof ScriptDialect>;\n\n/** Named {@link ScriptDialect} values, so a caller names one without spelling the literal. */\nexport const ScriptDialects = {\n /** Code-mode's plain dialect: `await`-style bindings over the workspace. */\n Plain: 'plain',\n /** Code-mode's Effect dialect: the body of an `Effect.gen` generator. */\n Effect: 'effect',\n JavaScript: 'javascript',\n TypeScript: 'typescript',\n} as const satisfies Record<string, ScriptDialect>;\n\n/**\n * A snippet carried by the operation itself, in the dialect it is written in.\n *\n * Declared as a type here and as a schema in `@dxos/compute-runtime/script-runner`, because the schema of a {@link ScriptRef}\n * needs the `Script` object type, whose module reaches the whole `@dxos/schema` barrel: the kind is on\n * every app's boot path through this module, and the schema is not.\n */\nexport type InlineScript = {\n readonly _tag: 'inline';\n readonly code: string;\n readonly dialect: ScriptDialect;\n};\n\n/**\n * A script stored in ECHO as a `Script` object.\n *\n * The dialect is the object's own (its editor compiles TypeScript), so unlike {@link InlineScript} it\n * is not restated here — a snippet has no object to ask.\n */\nexport type ScriptRef = {\n readonly _tag: 'object';\n readonly script: Ref.Ref<Script.Script>;\n};\n\n/** Where a script operation's code comes from: a snippet it carries, or an ECHO object it points at. */\nexport type ScriptSource = InlineScript | ScriptRef;\n\n/** Options {@link inlineScript} takes. */\nexport type InlineScriptOptions = {\n /** The language the snippet is written in; TypeScript when unsaid. */\n readonly dialect?: ScriptDialect;\n};\n\n/** A snippet source. */\nexport const inlineScript = (code: string, options?: InlineScriptOptions): InlineScript => ({\n _tag: 'inline',\n code,\n dialect: options?.dialect ?? ScriptDialects.TypeScript,\n});\n\n/** A source pointing at a `Script` object. */\nexport const scriptRef = (script: Ref.Ref<Script.Script>): ScriptRef => ({ _tag: 'object', script });\n\nexport const isInlineScript = (source: ScriptSource): source is InlineScript => source._tag === 'inline';\nexport const isScriptRef = (source: ScriptSource): source is ScriptRef => source._tag === 'object';\n\n/**\n * A script that could not be run: an unsupported dialect, a source that would not resolve, or a\n * runtime with no way to run scripts at all.\n *\n * A failure the SCRIPT raised is not one of these — that is a {@link ScriptResult} carrying `error`,\n * since the caller (a model writing code, a person at `dx eval`) is meant to read it and write\n * different code rather than see the call fail.\n */\nexport class ScriptError extends BaseError.extend('ScriptError', 'Script could not be run') {}\n\n/** The host calls one run made: how many, and the wall time spent waiting on them. */\nexport const ScriptStats = Schema$.Struct({\n calls: Schema$.Number,\n callMs: Schema$.Number,\n});\nexport type ScriptStats = Schema$.Schema.Type<typeof ScriptStats>;\n\n/**\n * One run, as a runtime's script backend receives it.\n *\n * Every field but the source is a scalar, so the same request runs in this process, on a worker, or\n * on EDGE without being rebuilt (its schema is `ScriptRunner.Request` in `@dxos/compute-runtime`). What a request cannot carry\n * is the workspace: the bindings the code runs against are the backend's, built wherever it lives.\n */\nexport type ScriptRequest = {\n readonly source: ScriptSource;\n /**\n * Input handed to the script, bound under `input` by a backend whose dialect can carry it. A\n * backend that evaluates out of process builds its bindings on the far side and may not, so a\n * script that must have its input should read it from the database instead.\n */\n readonly input?: unknown;\n /** Space the script's calls default to; absent runs against the backend's own default. */\n readonly spaceId?: string;\n /** Wall-clock bound on the run, in milliseconds. */\n readonly timeoutMs?: number;\n /** Characters of printed output returned before truncation. */\n readonly maxOutput?: number;\n /** Skill tokens the caller already holds, which the script's `invoke` presents for it. */\n readonly skillTokens?: readonly string[];\n};\n\n/**\n * What a run produced: what the script printed, why it failed when it did, and the calls it made.\n *\n * This is a script operation's default `output`, so `Operation.invoke` on one answers with it.\n */\nexport const ScriptResult = Schema$.Struct({\n output: Schema$.String,\n /** Present exactly when the script itself failed; `output` then holds what it printed first. */\n error: Schema$.optional(Schema$.String),\n stats: Schema$.optional(ScriptStats),\n});\nexport type ScriptResult = Schema$.Schema.Type<typeof ScriptResult>;\n\n/**\n * What a script's body may reach: the operation invoker and the process manager of the process the\n * script is running as.\n *\n * The running script's own, not the caller's, which is what makes a script's calls and the processes\n * it spawns belong to the script's process — a script delegates work the way a handler does.\n */\nexport type ScriptRequirements = Service | Process.ManagerService;\n\n/**\n * The process a script is running as, as its backend sees it.\n *\n * Passed rather than required, so a backend that evaluates code against the workspace can hand the\n * script its own process (`program.pipe(Effect.provide(runtime.context))`) while one that answers\n * through its own host — an MCP server, a remote isolate — declares `run(request)` alone and stays\n * requirement-free.\n */\nexport interface ScriptRuntime {\n readonly context: Context.Context<ScriptRequirements>;\n}\n\n/**\n * Runs scripts for a runtime.\n *\n * Not a client-facing API: a caller invokes a script operation like any other operation, and the\n * runtime it runs on reaches for this. Several backends implement it — in-process evaluation, a\n * worker thread that can be terminated, a workerd isolate that contains the code — which is why the\n * runtime takes it as a dependency rather than embedding one.\n */\nexport interface ScriptRunner {\n readonly run: (request: ScriptRequest, runtime?: ScriptRuntime) => Effect.Effect<ScriptResult, ScriptError>;\n}\n\n/**\n * The dialect a source is written in. A {@link ScriptRef} is TypeScript: a `Script` object is what the\n * script editor writes, and it compiles TypeScript.\n */\nexport const scriptDialectOf = (source: ScriptSource): ScriptDialect =>\n isInlineScript(source) ? source.dialect : ScriptDialects.TypeScript;\n\n/** The request that runs `operation` on `input`. */\nexport const scriptRequest = (\n operation: ScriptDefinition.Any,\n input?: unknown,\n options?: Omit<ScriptRequest, 'source' | 'input' | 'timeoutMs'>,\n): ScriptRequest => ({\n ...options,\n source: operation.source,\n ...(input !== undefined ? { input } : {}),\n ...(operation.timeout !== undefined ? { timeoutMs: operation.timeout } : {}),\n});\n\nexport const ScriptDefinitionTypeId = '~@dxos/operation/ScriptDefinition' as const;\nexport type ScriptDefinitionTypeId = typeof ScriptDefinitionTypeId;\n\n/**\n * The third kind of operation, beside a non-durable {@link Definition} with a handler and a\n * {@link Durable} one: an operation whose body is a script.\n *\n * It IS a {@link Definition} — `Operation.invoke(script, input, { on })` is the whole client API —\n * and carries no handler at all. The code is data, so the definition crosses a boundary whole and the\n * runtime that runs it is picked at call time; a runtime that cannot run scripts says so when asked,\n * rather than the caller needing a different verb.\n */\nexport interface ScriptDefinition<I, O> extends Definition<I, O> {\n readonly [ScriptDefinitionTypeId]: {\n readonly _Script: Types.Covariant<ScriptSource>;\n };\n\n readonly source: ScriptSource;\n\n /** Wall-clock bound on one run, in milliseconds; absent leaves the bound to the runtime. */\n readonly timeout?: number;\n}\n\nexport declare namespace ScriptDefinition {\n export type Any = ScriptDefinition<any, any>;\n\n export type Input<T extends Any> = Definition.Input<T>;\n export type Output<T extends Any> = Definition.Output<T>;\n}\n\n/**\n * Props {@link makeScript} takes. `input` defaults to `Unknown` and `output` to {@link ScriptResult},\n * since a script answers with what it printed and no dialect returns a typed value yet.\n */\nexport type ScriptProps = {\n readonly meta: Definition<any, any>['meta'];\n readonly source: ScriptSource;\n readonly timeout?: number;\n readonly input?: Schema$.Codec<any, any, never, never>;\n readonly output?: Schema$.Codec<any, any, never, never>;\n};\n\n/**\n * Creates a script operation, which is invoked like any other operation.\n *\n * @example\n * ```ts\n * const result = yield* Operation.invoke(\n * Operation.makeScript({\n * meta: { key: DXN.make('example.hello') },\n * source: Operation.inlineScript('yield* print(\"hi\")', { dialect: Operation.ScriptDialects.Effect }),\n * }),\n * undefined,\n * { on: 'local' },\n * );\n * ```\n */\nexport const makeScript = <const P extends Types.NoExcessProperties<ScriptProps, P>>(\n props: P,\n): ScriptDefinition<\n P['input'] extends Schema$.Codec<any, any, any, any> ? Schema$.Schema.Type<P['input']> : unknown,\n P['output'] extends Schema$.Codec<any, any, any, any> ? Schema$.Schema.Type<P['output']> : ScriptResult\n> =>\n ({\n [DefinitionTypeId]: {},\n [ScriptDefinitionTypeId]: {},\n ...props,\n input: props.input ?? Schema$.Unknown,\n output: props.output ?? ScriptResult,\n executionMode: 'async',\n types: [],\n services: [],\n pipe() {\n // eslint-disable-next-line prefer-rest-params\n return Pipeable.pipeArguments(this, arguments);\n },\n }) as any;\n\n/**\n * Whether an operation is the script kind, which a runtime runs rather than looking up a handler for.\n *\n * Narrows a typed definition to the script kind WITH its own input and output types, so a runtime\n * that branches on it keeps the operation's codecs — without them the branch could only be reconciled\n * with a cast.\n */\nexport const isScript: {\n <I, O>(op: Definition<I, O>): op is ScriptDefinition<I, O>;\n <I, O, R, Rpcs extends Rpc.Any>(op: Durable<I, O, R, Rpcs> | ScriptDefinition<I, O>): op is ScriptDefinition<I, O>;\n (value: unknown): value is ScriptDefinition.Any;\n} = (value: unknown): value is ScriptDefinition.Any =>\n typeof value === 'object' && value !== null && ScriptDefinitionTypeId in value;\n\n/** Whether `value` names a known {@link ScriptDialect}. */\nexport const isScriptDialect = (value: unknown): value is ScriptDialect =>\n typeof value === 'string' && (ScriptDialect.literals as readonly string[]).includes(value);\n\n//\n// Tool projection\n//\n\n/**\n * Constant namespace prefix elided from tool names; keys outside it (examples, third-party) keep every segment.\n */\nconst TOOL_NAME_KEY_PREFIX = 'org.dxos.operation.';\n\n/**\n * Derives the model-facing tool name for an operation from its DXN key — never from `meta.name`,\n * which is display copy and must stay freely editable without renaming the tool the model calls.\n * The key's namespace segment prefixes the name, which is what removes the cross-skill collisions\n * that a bare verb produced (three skills each claimed `create`).\n *\n * The mapping is not injective: kebab-casing makes a camelCase segment and an already-hyphenated one\n * converge, so `webSearch` and `web-search` both yield `web-search`, and hyphenated segments are in\n * live keys (`plugin-crm`, `web-search`). Registry-key uniqueness therefore does not by itself\n * guarantee tool-name uniqueness. Two such keys are an authoring error, caught in the two places both\n * keys are visible at once: {@link findToolNameCollisions} over a whole set, and the tool resolver.\n *\n * @example `org.dxos.operation.markdown.create` → `markdown-create`\n * @example `org.dxos.operation.assistantToolkit.addArtifact` → `assistant-toolkit-add-artifact`\n */\nexport const toolName = (op: Definition.Any): string => toolNameFromKey(op.meta.key);\n\n/**\n * {@link toolName} for a raw registry key (a DXN or bare NSID), e.g. a persisted record's meta key.\n */\nexport const toolNameFromKey = (key: string): string => {\n const name = deriveToolName(key);\n invariant(TOOL_NAME_REGEXP.test(name), `Invalid tool name: ${name}`);\n return name;\n};\n\n/** Shape every derived tool name must have — the model-facing identifier contract. */\nconst TOOL_NAME_REGEXP = /^[a-z][a-z0-9-_]*$/;\n\nconst deriveToolName = (key: string): string => {\n const nsid = DXN.isDXN(key) ? DXN.getName(key) : key;\n const stripped = nsid.startsWith(TOOL_NAME_KEY_PREFIX) ? nsid.slice(TOOL_NAME_KEY_PREFIX.length) : nsid;\n return stripped.split('.').map(kebabCase).join('-');\n};\n\nconst kebabCase = (segment: string): string => segment.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n\n/**\n * {@link toolNameFromKey} for a key that is not known to be well-formed — a record off the wire, whose\n * `@meta.key` is untrusted JSON. Returns undefined instead of failing, so one malformed entry costs its\n * own tool rather than every tool in the projection.\n */\nexport const tryToolNameFromKey = (key: string): string | undefined => {\n const name = deriveToolName(key);\n return TOOL_NAME_REGEXP.test(name) ? name : undefined;\n};\n\n/**\n * Groups a set of operations by derived tool name, returning only the names claimed more than once.\n *\n * {@link toolName} is not injective (see its note), so a set of registry-unique keys can still\n * collide. Call this wherever a complete operation set is assembled — the resolver sees keys one at a\n * time and can only catch a collision once a colliding name is actually requested.\n */\nexport const findToolNameCollisions = (operations: readonly Definition.Any[]): Map<string, readonly DXN.DXN[]> => {\n // Keyed by key, not by occurrence: one operation bound by two skills is the same tool, not a clash.\n const byName = new Map<string, Set<DXN.DXN>>();\n for (const op of operations) {\n const name = toolName(op);\n byName.set(name, (byName.get(name) ?? new Set()).add(op.meta.key));\n }\n return new Map([...byName].filter(([, keys]) => keys.size > 1).map(([name, keys]) => [name, [...keys]]));\n};\n\n//\n// Invocation Interfaces\n//\n\n/**\n * Local invocation of an operation.\n */\nexport type Invoke = <I, O, E>(op: Definition<I, O>, input: I) => Effect.Effect<O, E>;\n\n/**\n * Remote invocation of an operation.\n */\nexport type InvokeRemote = <I, O, E>(\n op: Definition<I, O>,\n input: I,\n options?: { timeout?: number },\n) => Effect.Effect<O, E>;\n\n/**\n * Database record of an operation.\n * The registry `key` and `version` live in the object meta — access via\n * `Obj.getMeta(record).key` and `Obj.getMeta(record).version`.\n */\n// TODO(dmaretskyi): Keep typename as 'org.dxos.type.function' (not 'operation') to maintain\n// backward compatibility with existing data and avoid requiring data migration.\nexport class PersistentOperation extends Type.makeObject<PersistentOperation>(\n DXN.make('org.dxos.type.function', '0.2.0'),\n)(\n Schema$.Struct({\n name: Schema$.NonEmptyString,\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(Ref.Ref(Obj.Unknown)),\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 services the operation handler declares.\n */\n services: Schema$.optional(Schema$.Array(Schema$.String)),\n\n // Local binding to a function name.\n // TODO(dmaretskyi): Add this field to Operation.Definition.\n binding: Schema$.optional(Schema$.String),\n\n /**\n * Phosphor icon identifier in `ph--<name>--<variant>` format (e.g. `ph--file-text--regular`).\n */\n icon: Schema$.optional(Schema$.String),\n }).pipe(\n Annotation.LabelAnnotation.set(['name']),\n Annotation.IconAnnotation.set({ icon: 'ph--function--regular', hue: 'blue' }),\n ),\n) {}\n\nconst FUNCTION_META_KEY = 'org.dxos.service.function';\n\n/**\n * Get the registry key for a persistent operation record (from the object meta).\n */\nexport const getKey = (record: PersistentOperation): string | undefined => Obj.getMeta(record).key;\n\n/**\n * Get the registry version for a persistent operation record (from the object meta).\n */\nexport const getVersion = (record: PersistentOperation): string | undefined => Obj.getMeta(record).version;\n\n/**\n * Serialize an operation definition to a persistent operation record.\n */\nexport const serialize = (operation: Definition.Any, options?: Obj.MakeOptions): PersistentOperation => {\n return Obj.make(\n PersistentOperation,\n {\n [Obj.Meta]: {\n key: operation.meta.key,\n version: operation.meta.version ?? '0.0.0',\n keys: operation.meta.deployedId ? [{ source: FUNCTION_META_KEY, id: operation.meta.deployedId }] : [],\n annotations: operation.meta.annotations,\n },\n name: operation.meta.name ?? '',\n description: operation.meta.description,\n icon: operation.meta.icon,\n updated: undefined,\n source: undefined,\n inputSchema: JsonSchema.toJsonSchema(operation.input),\n outputSchema: JsonSchema.toJsonSchema(operation.output),\n services: operation.services.map((service) => service.key),\n },\n options,\n );\n};\n\n/**\n * Serializes each definition, dropping any whose schema cannot render as JSON Schema, so one\n * unserializable operation (e.g. `space.importSpace`) does not fail registry population for every\n * other.\n */\nexport const serializable = (operations: readonly Definition.Any[]): PersistentOperation[] =>\n operations.flatMap((operation) => {\n try {\n return [serialize(operation)];\n } catch (error) {\n log.verbose('operation is not serializable; excluded from the registry', {\n key: String(operation.meta.key),\n error: String(error),\n });\n return [];\n }\n });\n\n/**\n * Deserialize a persistent operation record to an operation definition.\n */\nexport const deserialize = (record: PersistentOperation): Definition.Any => {\n const meta = Obj.getMeta(record);\n // Extract deployed function ID from ECHO meta keys (matches FUNCTIONS_META_KEY in @dxos/functions).\n const deployedId = meta.keys.find((key) => key.source === FUNCTION_META_KEY)?.id;\n return make({\n input: record.inputSchema ? JsonSchema.toEffectSchema(record.inputSchema) : Schema$.Unknown,\n output: record.outputSchema ? JsonSchema.toEffectSchema(record.outputSchema) : Schema$.Unknown,\n services: record.services?.map((service) => Context.Service(service)) ?? [],\n executionMode: 'async',\n types: [],\n meta: {\n key: DXN.tryMake(meta.key ?? record.name) ?? DXN.make(meta.key ?? record.name),\n name: record.name,\n version: meta.version ?? '0.0.0',\n description: record.description,\n icon: record.icon,\n deployedId,\n annotations: meta.annotations ?? {},\n },\n });\n};\n\n/**\n * Update properties on the target operation record from the source operation record.\n */\nexport const setFrom = (target: PersistentOperation, source: PersistentOperation) => {\n Obj.update(target, (target) => {\n target.name = source.name ?? target.name;\n target.description = source.description;\n target.icon = source.icon;\n target.updated = source.updated;\n // TODO(dmaretskyi): A workaround for an ECHO bug.\n target.inputSchema = source.inputSchema ? JSON.parse(JSON.stringify(source.inputSchema)) : undefined;\n target.outputSchema = source.outputSchema ? JSON.parse(JSON.stringify(source.outputSchema)) : undefined;\n const sourceMeta = Obj.getMeta(source);\n const targetMeta = Obj.getMeta(target);\n targetMeta.key = sourceMeta.key ?? targetMeta.key;\n targetMeta.version = sourceMeta.version;\n // Only overwrite foreign keys when the source actually carries them; otherwise we'd wipe\n // bindings (e.g. the deployedId set by `deserialize`) on records produced by `serialize`.\n if (sourceMeta.keys.length > 0) {\n targetMeta.keys = JSON.parse(JSON.stringify(sourceMeta.keys));\n }\n targetMeta.annotations = sourceMeta.annotations ?? targetMeta.annotations;\n });\n};\n\n/**\n * Translatable label — a plain string or an i18next-style `[key, options]` tuple.\n * Defined locally to avoid a core dependency on UI translation packages; structurally compatible with\n * the app-level `Label` type so values flow into UI toasts unchanged.\n */\nexport const Label = Schema.Union([\n Schema.String,\n // `Schema.mutable` mirrors the app-level `Label` (whose tuple is mutable), so decoded values are\n // assignable to UI toast `title`/`label` slots without a readonly-vs-mutable tuple mismatch.\n Schema.mutable(\n Schema.Tuple([\n Schema.String,\n Schema.Struct({\n ns: Schema.String,\n count: Schema.optional(Schema.Number),\n defaultValue: Schema.optional(Schema.String),\n }).mapFields(Struct.map(Schema.mutableKey)),\n ]),\n ),\n]);\nexport type Label = Schema.Schema.Type<typeof Label>;\n\n/**\n * Per-phase user notification messages for an invocation.\n * A phase is notified to the user iff its message is provided; messages are translatable {@link Label}s.\n */\nexport const NotifyOptions = Schema.Struct({\n /** Shown when the invocation starts. */\n start: Schema.optional(Label),\n /** Shown when the invocation succeeds. */\n success: Schema.optional(Label),\n /** Shown when the invocation fails. */\n error: Schema.optional(Label),\n});\nexport type NotifyOptions = Schema.Schema.Type<typeof NotifyOptions>;\n\n/**\n * Annotation that configures the process to notify the user at the given invocation phases.\n */\nexport const NotifyOptionsAnnotation = Annotation.make({\n id: 'org.dxos.operation.notify-options',\n schema: NotifyOptions,\n});\n\n/**\n * A serializable reference to an operation invocation — the target operation's key plus its input.\n * Describes a deferred/late-bound invocation that must survive a serialization boundary (e.g. riding\n * on a process-failure error, or persisted) where a live {@link Definition} cannot. Resolve the key\n * with `OperationHandlerSet.getHandlerByKey` and hand the result to the invoker. Carries no functions,\n * so `input` must itself be serializable.\n */\nexport interface SerializedInvocation {\n /** Target operation key as a URI (a DXN, e.g. `dxn:org.dxos.plugin.deck.operation.open`). */\n readonly operation: URI.URI;\n /** Input passed to the operation; must be serializable. */\n readonly input?: unknown;\n}\n\n/**\n * Builds a {@link SerializedInvocation} from a live {@link Definition} and its input — the serializable\n * counterpart to a direct `invoke`, for describing an invocation that must cross a serialization\n * boundary (e.g. a deferred toast action). Resolve it later with `OperationHandlerSet.getHandlerByKey`.\n */\nexport const prepare = <I, O>(operation: Definition<I, O>, input: I): SerializedInvocation => ({\n operation: operation.meta.key,\n input,\n});\n\n/**\n * Options for operation invocation.\n */\nexport interface InvokeOptions {\n /**\n * Space ID to provide database context for the handler.\n */\n spaceId?: Key.SpaceId;\n /**\n * Request user-facing notifications at the given invocation phases.\n */\n notify?: NotifyOptions;\n /**\n * URI of the conversation feed (queue) — today always an EID, but typed as\n * `URI.URI` to accommodate future entity-kind extensions. Narrow with `EID.parse`\n * at the point of use.\n * Passed to the process environment so nested operations can resolve HarnessService and related services.\n */\n conversation?: URI.URI;\n /**\n * Tracing metadata stamped on the process that runs the invocation.\n */\n tracing?: Trace.Meta;\n\n /**\n * Specifies the runtime environment for the operation.\n * By default, the operation is executed on the local runtime.\n */\n on?: 'edge' | 'local';\n}\n\n/**\n * Annotation that marks an operation as idempotent — safe to retry even if a previous execution\n * was interrupted mid-handler. When absent the operation is treated as non-idempotent, and the\n * process runtime will fail (rather than re-run) any handler that was interrupted.\n */\nexport const IdempotentAnnotation = Annotation.make({\n id: 'org.dxos.operation.idempotent',\n schema: Schema$.Boolean,\n});\n\n/**\n * Returns true when the operation is explicitly annotated as idempotent.\n */\nexport const isIdempotent = (op: Definition.Any): boolean =>\n op.meta.annotations\n ? Option.getOrElse(Annotation.getDictionary(op.meta.annotations, IdempotentAnnotation), () => false)\n : false;\n\n/**\n * Attaches an annotation to an operation definition, returning a new definition.\n * Combinators never mutate their input — operation definitions are module-level singletons\n * shared across handler sets, skills, and the registry, so a fresh value keeps the\n * annotated definition distinct from any other reference to the original.\n *\n * Type-preserving: an annotation does not change the operation's input/output/service types, so the\n * returned definition keeps `Def` (preserving `withHandler` inference and downstream usage).\n */\nexport const annotate =\n <T>(annotation: Annotation.Annotation<T>, value: T) =>\n <Def extends Definition.Any>(op: Def): Def => {\n const annotations = { ...(op.meta.annotations ?? {}) };\n Annotation.setDictionary(annotations, annotation, value);\n // The spread reconstructs the same shape with only `meta.annotations` changed; the checker can't\n // track the branded variance symbol through the untyped dictionary mutation, so reassert `Def`.\n return { ...op, meta: { ...op.meta, annotations } } as Def;\n };\n\n/**\n * Marks an operation as visible on user-facing operation surfaces (trigger/automation pickers,\n * manual invocation). Absent ⇒ internal: invoked programmatically by plugins and hidden from pickers.\n *\n * Same polarity as the schema-level `Annotation.UserType`: operations are hidden by default, since most\n * are internal plugin machinery and only a minority are user-facing.\n */\nexport const VisibleAnnotation = Annotation.make({\n id: 'org.dxos.operation.visible',\n schema: Schema$.Boolean,\n});\n\n/**\n * The operation's effect on state: `none` is side-effect free, `write` mutates but is not\n * irreversible, `destructive` deletes or otherwise cannot be undone. Absent ⇒ unclassified, which\n * consumers treat conservatively (an MCP client badges the tool as possibly destructive).\n */\nexport const MutationAnnotation = Annotation.make({\n id: 'org.dxos.operation.mutation',\n schema: Schema$.Literals(['none', 'write', 'destructive']),\n});\n\nexport type Mutation = Schema$.Schema.Type<typeof MutationAnnotation.schema>;\n\n/**\n * Pipeable combinator classifying the operation's effect on state — see {@link MutationAnnotation}.\n * Apply at the definition site: `Operation.make({ ... }).pipe(Operation.mutation('none'))`.\n */\nexport const mutation = (value: Mutation) => annotate(MutationAnnotation, value);\n\n/** The operation's mutation class, or undefined when unclassified. Reads from the persisted record. */\nexport const getMutation = (op: PersistentOperation): Mutation | undefined =>\n Option.getOrUndefined(Annotation.get(op, MutationAnnotation));\n\n/**\n * Pipeable combinator that marks an operation visible. Apply at the definition site:\n * `Operation.make({ ... }).pipe(Operation.visible)`.\n */\nexport const visible = annotate(VisibleAnnotation, true);\n\n/**\n * Returns true when an operation is annotated as visible on user-facing surfaces (trigger/automation\n * pickers, manual invocation). Reads from the persisted operation — the form every consumer holds.\n */\nexport const isVisible = (op: PersistentOperation): boolean =>\n Option.getOrElse(Annotation.get(op, VisibleAnnotation), () => false);\n\n/**\n * Pipeable combinator that marks an operation idempotent — see {@link IdempotentAnnotation}. Apply at\n * the definition site: `Operation.make({ ... }).pipe(Operation.idempotent)`.\n */\nexport const idempotent = annotate(IdempotentAnnotation, true);\n\n/**\n * What an operation requires of the process that invokes it, in the vocabulary of the permission\n * system that interprets it (`@dxos/permission` requirements). Present ⇒ the runtime refuses the\n * call unless the invoking process holds a guard that admits it; absent ⇒ the operation is never\n * checked, which is what keeps permissions opt-in.\n */\nexport const RequiresAnnotation = Annotation.make({\n id: 'org.dxos.operation.requires',\n schema: Schema$.Array(Schema$.Unknown),\n});\n\n/** The operation's declared requirements; empty when it declares none. */\nexport const getRequirements = (op: Definition.Any): readonly unknown[] =>\n op.meta.annotations\n ? Option.getOrElse(Annotation.getDictionary(op.meta.annotations, RequiresAnnotation), (): readonly unknown[] => [])\n : [];\n\n/**\n * The input field a consent prompt shows before the person allows the call (the body of an email it\n * would send), so they approve what is sent and not only that something is.\n */\nexport const ConsentPreviewAnnotation = Annotation.make({\n id: 'org.dxos.operation.consentPreview',\n schema: Schema$.Struct({ field: Schema$.String, label: Schema$.String }),\n});\n\n/** The text a consent prompt previews for this call, when the operation names a string field to show. */\nexport const getConsentPreview = (\n op: Definition.Any,\n input: unknown,\n): { readonly label: string; readonly text: string } | undefined => {\n const preview = op.meta.annotations\n ? Annotation.getDictionary(op.meta.annotations, ConsentPreviewAnnotation)\n : Option.none();\n if (Option.isNone(preview) || input === null || typeof input !== 'object') {\n return undefined;\n }\n const text: unknown = Reflect.get(input, preview.value.field);\n return typeof text === 'string' && text.trim().length > 0 ? { label: preview.value.label, text } : undefined;\n};\n\n/**\n * Operation service interface - provides unified access to operation invocation and scheduling.\n * This service is automatically provided to operation handlers.\n */\nexport interface OperationService {\n /**\n * Invoke an operation as an Effect.\n * Returns an Effect that resolves to the operation output.\n */\n invoke: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Effect.Effect<O, NoHandlerError>;\n\n /**\n * Schedule an operation to run as a followup.\n * The followup is tracked and won't be cancelled when the parent operation completes.\n * Returns an Effect that completes immediately after scheduling.\n */\n schedule: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Effect.Effect<void>;\n\n /**\n * Invoke an operation and return a Promise.\n * Useful for async contexts where Effect is not available.\n */\n invokePromise: <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n ) => Promise<{ data?: O; error?: Error }>;\n}\n\n/**\n * Context tag for the Operation service.\n * Operation handlers can yield this to invoke other operations or schedule followups.\n *\n * @example\n * ```ts\n * const handler = (input) => Effect.gen(function* () {\n * // Schedule a followup (fire and forget)\n * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });\n *\n * // Invoke another operation\n * return yield* Operation.invoke(OtherOperation, { data: input.data });\n * });\n * ```\n */\n// TODO(dmaretskyi): Rename Operation.Invoker\nexport class Service extends Context.Service<Service, OperationService>()('@dxos/operation/Service') {}\n\n//\n// Namespace functions - ergonomic access to Operation.Service methods.\n//\n\n/**\n * Invoke an operation as an Effect.\n * Yields the Operation.Service internally.\n *\n * @example\n * ```ts\n * yield* Operation.invoke(MyOperation, { data: 'test' });\n * ```\n */\nexport const invoke = <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n): Effect.Effect<O, NoHandlerError, Service> =>\n Effect.flatMap(Service, (ops) => ops.invoke(op, ...(args as [I, InvokeOptions?]))).pipe(\n Effect.withSpan('Operation.invoke'),\n );\n\n/**\n * Schedule an operation to run as a followup.\n * Yields the Operation.Service internally.\n *\n * @example\n * ```ts\n * yield* Operation.schedule(AnalyticsOperation, { event: 'completed' });\n * yield* Operation.schedule(VoidOperation); // input optional when void\n * ```\n */\nexport const schedule = <I, O>(\n op: Operation.Definition<I, O>,\n ...args: void extends I ? [input?: I, options?: InvokeOptions] : [input: I, options?: InvokeOptions]\n): Effect.Effect<void, never, Service> =>\n Effect.flatMap(Service, (ops) => ops.schedule(op, ...(args as [I, InvokeOptions?]))).pipe(\n Effect.withSpan('Operation.schedule'),\n );\n\n/**\n * Call inside an operation to stop the current invocation and have the system re-run it (e.g. a capped\n * sync run with more work left). Surfaces as a {@link RunAgainError} defect; the trigger dispatcher\n * re-queues the same event FIFO to continue. A caller invoking via `Operation.invoke` directly gets the\n * defect and does not auto-continue.\n */\nexport const runAgain = (): Effect.Effect<never, void> => Effect.failCauseSync(() => Cause.die(new RunAgainError()));\n\n/**\n * Provides additional invocation options to all invocations.\n */\nexport const withInvocationOptions = (options: InvokeOptions): Layer.Layer<Service, never, Service> =>\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const service = yield* Service;\n return Service.of({\n invoke: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.invoke(op, input, { ...options, ...invocationOptions })) as any,\n invokePromise: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.invokePromise(op, input, { ...options, ...invocationOptions })) as any,\n schedule: ((op: Operation.Definition.Any, input: any, invocationOptions: InvokeOptions) =>\n service.schedule(op, input, { ...options, ...invocationOptions })) as any,\n });\n }),\n );\n\n//\n// Legacy schemas and migrations.\n//\n\n/**\n * Persistent operation schema v0.1.0 — `key` and `version` are stored as data properties.\n * @deprecated Use {@link PersistentOperation} (v0.2.0) instead; the `key` and `version` now live in the object meta.\n */\nexport class PersistentOperation_v0_1_0 extends Type.makeObject<PersistentOperation_v0_1_0>(\n DXN.make('org.dxos.type.function', '0.1.0'),\n)(\n Schema$.Struct({\n key: Schema$.optional(Schema$.String),\n name: Schema$.NonEmptyString,\n version: Schema$.String,\n description: Schema$.optional(Schema$.String),\n updated: Schema$.optional(Schema$.String),\n source: Schema$.optional(Ref.Ref(Obj.Unknown)),\n inputSchema: Schema$.optional(JsonSchema.JsonSchema),\n outputSchema: Schema$.optional(JsonSchema.JsonSchema),\n services: Schema$.optional(Schema$.Array(Schema$.String)),\n binding: Schema$.optional(Schema$.String),\n }),\n) {}\n\n/**\n * Migration from {@link PersistentOperation_v0_1_0} (v0.1.0) to {@link PersistentOperation} (v0.2.0).\n * Moves `key` and `version` from the data section into the object meta.\n */\nconst _migration = Migration.define({\n from: PersistentOperation_v0_1_0,\n to: PersistentOperation,\n transform: async (from) => ({\n [Obj.Meta]: { key: from.key, version: from.version },\n name: from.name,\n description: from.description,\n updated: from.updated,\n source: from.source,\n inputSchema: from.inputSchema,\n outputSchema: from.outputSchema,\n services: from.services,\n binding: from.binding,\n }),\n});\n\n/**\n * Schema migrations exported by this module.\n * Exported as an array for extensibility — append future versions here.\n */\nexport const migrations = [_migration];\n\nexport {\n FunctionError,\n FunctionNotFoundError,\n InvalidOperationInputError,\n InvalidOperationOutputError,\n InvokerNotInitializedError,\n NoHandlerError,\n OperationDeniedError,\n} from './errors.ts';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,mBAAmB;AA+GhC,IAAa,oBAAoB;;AAejC,IAAa,iBAAiB,UAC5B,OAAO,UAAU,YAAY,UAAU,QAAA,kCAA6B;;;;;;;;;;AAWtE,IAAa,gBAIX,UACA,SACG;CACH,MAAM,QAAQ,IAAS,YAA4E;GAChG,oBAAoB;EACrB,YAAY;EACZ,MAAM;CACR;CACA,OAAO,SAAS,KAAA,KACX,OAAY,KAAK,IAAI,QAAwD,IAC9E,KAAK,UAAiB,IAAI;AAChC;;;;AAKA,IAAa,yBAAyB,UAA4C;CAChF,OAAO,OAAO,UAAU,YAAY,UAAU,QAAA,0CAA4B;AAC5E;;;;AAKA,IAAa,0BAA0B,UAAyD;CAC9F,OAAO,sBAAsB,KAAK,KAAK,aAAa;AACtD;;;;;;AAiBA,IAAa,QACX,UAKG;CACH,OAAO;GACJ,mBAAmB,CAAC;EACrB,GAAG;EACH,eAAe,MAAM,iBAAiB;EACtC,OAAO,MAAM,SAAS,CAAC;EACvB,UAAU,MAAM,YAAY,CAAC;EAC7B,OAAO;GAEL,OAAO,SAAS,cAAc,MAAM,SAAS;EAC/C;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,eASX,aACA,YACqB;CAErB,IAAI,YAAY,KAAA,GAAW;EACzB,MAAM,YAAY;EAMlB,SAAS,QAAa;GACpB,GAAG;GACH,SAAS;EACX;CACF;CAIA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;CACpC,MAAMA,OAAQ;CACd,SAASA,OAAQ;CACjB,aAAaA,OAAQ,SAASA,OAAQ,MAAM;CAC5C,SAASA,OAAQ,SAASA,OAAQ,MAAM;CACxC,QAAQA,OAAQ,SAAS,IAAI,IAAI,IAAI,OAAO,CAAC;CAC7C,aAAaA,OAAQ,SAAS,WAAW,UAAU;CACnD,cAAcA,OAAQ,SAAS,WAAW,UAAU;CACpD,UAAUA,OAAQ,SAASA,OAAQ,MAAMA,OAAQ,MAAM,CAAC;CACxD,SAASA,OAAQ,SAASA,OAAQ,MAAM;AAC1C,CAAC,CACH,CAAC,CAAC,CAAC;;;;;AA0BH,IAAa,aAAa,CApBP,UAAU,OAAO;CAClC,MAAM;CACN,IAAI;CACJ,WAAW,OAAO,UAAU;GACzB,IAAI,OAAO;GAAE,KAAK,KAAK;GAAK,SAAS,KAAK;EAAQ;EACnD,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,SAAS,KAAK;EACd,QAAQ,KAAK;EACb,aAAa,KAAK;EAClB,cAAc,KAAK;EACnB,UAAU,KAAK;EACf,SAAS,KAAK;CAChB;AACF,CAM2B,CAAU"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
2
|
import { NoHandlerError } from "./errors.mjs";
|
|
3
|
+
import { DXN } from "@dxos/keys";
|
|
3
4
|
import * as Effect from "effect/Effect";
|
|
4
5
|
import * as Context from "effect/Context";
|
|
5
6
|
import { pipe } from "effect/Function";
|
|
6
7
|
import * as Layer from "effect/Layer";
|
|
7
8
|
import { assertArgument } from "@dxos/invariant";
|
|
8
9
|
import * as EffectEx from "@dxos/effect/EffectEx";
|
|
9
|
-
import { DXN } from "@dxos/keys";
|
|
10
10
|
//#region src/OperationHandlerSet.ts
|
|
11
11
|
var OperationHandlerSet_exports = /* @__PURE__ */ __exportAll({
|
|
12
12
|
OperationHandlerProvider: () => OperationHandlerProvider,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { f as PersistentOperation, w as deserialize } from "./chunk-Operation.mjs";
|
|
3
3
|
import { s as getHandlerByKey, t as OperationHandlerProvider } from "./chunk-OperationHandlerSet.mjs";
|
|
4
4
|
import { Database, Filter, Query } from "@dxos/echo";
|
|
5
5
|
import * as Effect from "effect/Effect";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-OperationRegistry.mjs","names":["OperationHandlerSet.OperationHandlerProvider","Operation.PersistentOperation","Operation.deserialize","OperationHandlerSet.getHandlerByKey"],"sources":["../../src/OperationRegistry.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { Database, Filter, Query } from '@dxos/echo';\n\nimport * as Operation from './Operation.ts';\nimport * as OperationHandlerSet from './OperationHandlerSet.ts';\n\nexport interface OperationRegistry {\n /**\n * Resolve an operation by key.\n */\n resolve(key: string): Effect.Effect<Option.Option<Operation.Definition.Any>>;\n}\n\nexport class Service extends Context.Service<Service, OperationRegistry>()('@dxos/operation/OperationRegistry') {}\n\n/**\n * Resolve an operation by key.\n */\nexport const resolve: (key: string) => Effect.Effect<Option.Option<Operation.Definition.Any>, never, Service> = (\n ...args: Parameters<Context.Service.Shape<typeof Service>['resolve']>\n) => Service.use((service) => service.resolve(...args));\n\nexport const layer: Layer.Layer<Service, never, Database.Service | OperationHandlerSet.OperationHandlerProvider> =\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const database = yield* Database.Service;\n const handlerSet = yield* OperationHandlerSet.OperationHandlerProvider;\n return {\n resolve: (key: string) =>\n Database.query(Query.select(Filter.and(Filter.type(Operation.PersistentOperation), Filter.key(key))))\n .first.pipe(\n Effect.flatMap((result) => Effect.fromOption(result)),\n Effect.map(Operation.deserialize),\n Effect.catchTag('NoSuchElementError', () => OperationHandlerSet.getHandlerByKey(handlerSet, key)),\n Effect.option,\n )\n .pipe(Effect.provideService(Database.Service, database)),\n };\n }),\n );\n"],"mappings":";;;;;;;;;;;;;AAuBA,IAAa,UAAb,cAA6B,QAAQ,QAAoC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC;;;;AAKjH,IAAa,WACX,GAAG,SACA,QAAQ,KAAK,YAAY,QAAQ,QAAQ,GAAG,IAAI,CAAC;AAEtD,IAAa,QACX,MAAM,OACJ,SACA,OAAO,IAAI,aAAa;CACtB,MAAM,WAAW,OAAO,SAAS;CACjC,MAAM,aAAa,OAAOA;CAC1B,OAAO,EACL,UAAU,QACR,SAAS,MAAM,MAAM,OAAO,OAAO,IAAI,OAAO,KAAKC,mBAA6B,GAAG,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"chunk-OperationRegistry.mjs","names":["OperationHandlerSet.OperationHandlerProvider","Operation.PersistentOperation","Operation.deserialize","OperationHandlerSet.getHandlerByKey"],"sources":["../../src/OperationRegistry.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as Option from 'effect/Option';\n\nimport { Database, Filter, Query } from '@dxos/echo';\n\nimport * as Operation from './Operation.ts';\nimport * as OperationHandlerSet from './OperationHandlerSet.ts';\n\nexport interface OperationRegistry {\n /**\n * Resolve an operation by key.\n */\n resolve(key: string): Effect.Effect<Option.Option<Operation.Definition.Any>>;\n}\n\nexport class Service extends Context.Service<Service, OperationRegistry>()('@dxos/operation/OperationRegistry') {}\n\n/**\n * Resolve an operation by key.\n */\nexport const resolve: (key: string) => Effect.Effect<Option.Option<Operation.Definition.Any>, never, Service> = (\n ...args: Parameters<Context.Service.Shape<typeof Service>['resolve']>\n) => Service.use((service) => service.resolve(...args));\n\nexport const layer: Layer.Layer<Service, never, Database.Service | OperationHandlerSet.OperationHandlerProvider> =\n Layer.effect(\n Service,\n Effect.gen(function* () {\n const database = yield* Database.Service;\n const handlerSet = yield* OperationHandlerSet.OperationHandlerProvider;\n return {\n resolve: (key: string) =>\n Database.query(Query.select(Filter.and(Filter.type(Operation.PersistentOperation), Filter.key(key))))\n .first.pipe(\n Effect.flatMap((result) => Effect.fromOption(result)),\n Effect.map(Operation.deserialize),\n Effect.catchTag('NoSuchElementError', () => OperationHandlerSet.getHandlerByKey(handlerSet, key)),\n Effect.option,\n )\n .pipe(Effect.provideService(Database.Service, database)),\n };\n }),\n );\n"],"mappings":";;;;;;;;;;;;;AAuBA,IAAa,UAAb,cAA6B,QAAQ,QAAoC,CAAC,CAAC,mCAAmC,CAAC,CAAC,CAAC;;;;AAKjH,IAAa,WACX,GAAG,SACA,QAAQ,KAAK,YAAY,QAAQ,QAAQ,GAAG,IAAI,CAAC;AAEtD,IAAa,QACX,MAAM,OACJ,SACA,OAAO,IAAI,aAAa;CACtB,MAAM,WAAW,OAAO,SAAS;CACjC,MAAM,aAAa,OAAOA;CAC1B,OAAO,EACL,UAAU,QACR,SAAS,MAAM,MAAM,OAAO,OAAO,IAAI,OAAO,KAAKC,mBAA6B,GAAG,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAClG,MAAM,KACL,OAAO,SAAS,WAAW,OAAO,WAAW,MAAM,CAAC,GACpD,OAAO,IAAIC,WAAqB,GAChC,OAAO,SAAS,4BAA4BC,gBAAoC,YAAY,GAAG,CAAC,GAChG,OAAO,MACT,CAAC,CACA,KAAK,OAAO,eAAe,SAAS,SAAS,QAAQ,CAAC,EAC7D;AACF,CAAC,CACH"}
|
|
@@ -1,20 +1,21 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
2
2
|
import { RUN_AGAIN_ERROR_CODE, RUN_AGAIN_MESSAGE, RunAgainError } from "./errors.mjs";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { V as isScript, l as NotifyOptions } from "./chunk-Operation.mjs";
|
|
4
|
+
import { u as EventType } from "./chunk-Trace.mjs";
|
|
5
|
+
import * as Option from "effect/Option";
|
|
5
6
|
import * as Schema from "effect/Schema";
|
|
6
7
|
import { Annotation } from "@dxos/echo";
|
|
8
|
+
import { URI as URI$1 } from "@dxos/keys";
|
|
7
9
|
import * as Effect from "effect/Effect";
|
|
8
|
-
import * as Option from "effect/Option";
|
|
9
10
|
import * as Cause from "effect/Cause";
|
|
10
11
|
import * as Context from "effect/Context";
|
|
11
|
-
import { URI as URI$1 } from "@dxos/keys";
|
|
12
12
|
import * as Exit from "effect/Exit";
|
|
13
13
|
import * as Stream from "effect/Stream";
|
|
14
14
|
//#region src/Process.ts
|
|
15
15
|
var Process_exports = /* @__PURE__ */ __exportAll({
|
|
16
16
|
EnvironmentService: () => EnvironmentService,
|
|
17
17
|
ExitedEvent: () => ExitedEvent,
|
|
18
|
+
GuardService: () => GuardService,
|
|
18
19
|
HarnessHostAnnotation: () => HarnessHostAnnotation,
|
|
19
20
|
ID: () => ID,
|
|
20
21
|
ManagerService: () => ManagerService,
|
|
@@ -26,6 +27,7 @@ var Process_exports = /* @__PURE__ */ __exportAll({
|
|
|
26
27
|
State: () => State,
|
|
27
28
|
TargetAnnotation: () => TargetAnnotation,
|
|
28
29
|
awaitOutput: () => awaitOutput,
|
|
30
|
+
bothGuards: () => bothGuards,
|
|
29
31
|
currentEnvironment: () => currentEnvironment,
|
|
30
32
|
isExited: () => isExited,
|
|
31
33
|
isHarnessHost: () => isHarnessHost,
|
|
@@ -106,6 +108,10 @@ var matchesFilter = (info, filter = {}) => {
|
|
|
106
108
|
};
|
|
107
109
|
/** {@link Manager.list} over a tree read, so a manager implements it by supplying only that read. */
|
|
108
110
|
var listFromTree = (processTree) => (filter) => Effect.map(processTree, (tree) => tree.filter((info) => matchesFilter(info, filter)));
|
|
111
|
+
/** The guard of the running process; absent when it was spawned without one. */
|
|
112
|
+
var GuardService = class extends Context.Service()("@dxos/compute/Process.GuardService") {};
|
|
113
|
+
/** A guard that admits only what both admit, so a child spawned with its own guard never widens its parent's. */
|
|
114
|
+
var bothGuards = (first, second) => ({ check: (op, input) => first.check(op, input).pipe(Effect.andThen(second.check(op, input))) });
|
|
109
115
|
/**
|
|
110
116
|
* The first output of a single-output process (e.g. one running an operation), failing with the
|
|
111
117
|
* process's own cause when it fails without one.
|
|
@@ -123,12 +129,14 @@ var awaitOutput = (handle) => handle.subscribeOutputs().pipe(Stream.runHead, Eff
|
|
|
123
129
|
})));
|
|
124
130
|
var ManagerService = class extends Context.Service()("@dxos/compute/Process.ManagerService") {};
|
|
125
131
|
/**
|
|
126
|
-
* Spawns `
|
|
127
|
-
* {@link awaitOutput}.
|
|
132
|
+
* Spawns `definition` — a durable operation or a script operation — through the ambient
|
|
133
|
+
* {@link ManagerService} and submits `input`; read its result with {@link awaitOutput}.
|
|
128
134
|
*/
|
|
129
|
-
var spawn = (
|
|
130
|
-
const
|
|
131
|
-
|
|
135
|
+
var spawn = (definition, input, options) => Effect.gen(function* () {
|
|
136
|
+
const manager = yield* ManagerService;
|
|
137
|
+
const name = isScript(definition) ? definition.meta.name : definition.name;
|
|
138
|
+
const handle = yield* manager.spawn(definition, {
|
|
139
|
+
...name !== void 0 ? { name } : {},
|
|
132
140
|
...options
|
|
133
141
|
});
|
|
134
142
|
yield* handle.submitInput(input);
|
|
@@ -199,6 +207,6 @@ var prettyProcessTree = (tree) => {
|
|
|
199
207
|
return lines.join("\n");
|
|
200
208
|
};
|
|
201
209
|
//#endregion
|
|
202
|
-
export {
|
|
210
|
+
export { isTerminal as _, ID as a, prettyProcessTree as b, Process_exports as c, TargetAnnotation as d, awaitOutput as f, isHarnessHost as g, isExited as h, HarnessHostAnnotation as i, SpawnedEvent as l, currentEnvironment as m, ExitedEvent as n, ManagerService as o, bothGuards as p, GuardService as r, NotifyAnnotation as s, EnvironmentService as t, State as u, listFromTree as v, spawn as x, matchesFilter as y };
|
|
203
211
|
|
|
204
212
|
//# sourceMappingURL=chunk-Process.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-Process.mjs","names":["URI","Operation.NotifyOptions","Trace.EventType"],"sources":["../../src/Process.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Cause from 'effect/Cause';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Option from 'effect/Option';\nimport type * as Atom from 'effect/reactivity/Atom';\nimport type * as Rpc from 'effect/rpc/Rpc';\nimport type * as RpcClient from 'effect/rpc/RpcClient';\nimport * as Schema from 'effect/Schema';\nimport * as Stream from 'effect/Stream';\n\nimport { Annotation, type Database } from '@dxos/echo';\nimport { type SpaceId, URI } from '@dxos/keys';\nimport type { SerializedError } from '@dxos/protocols';\n\nimport * as Operation from './Operation.ts';\nimport * as Trace from './Trace.ts';\n\nexport { RUN_AGAIN_ERROR_CODE, RUN_AGAIN_MESSAGE, RunAgainError } from './errors.ts';\n\n//\n// Process.\n//\n\n/** Opaque process id (arbitrary string). */\nexport const ID = Schema.String.pipe(Schema.brand('ProcessId'));\nexport type ID = Schema.Schema.Type<typeof ID>;\n\n/**\n * Generic parameters for a all processes.\n */\nexport interface Params {\n /**\n * Process name for debugging purposes.\n */\n readonly name: string | null;\n\n /**\n * User-defined annotations for the process.\n * Can only be set when the process is spawned.\n */\n readonly annotations: Annotation.Dictionary;\n}\n\n/**\n * What the process is running on behalf of, fixed at spawn and inherited by child processes.\n *\n * Determines which services the runtime can provide (a space-scoped database, a conversation's harness).\n */\nexport interface Environment {\n /** Space the process is scoped to; absent for app-level work. */\n readonly space?: SpaceId;\n\n /** URI of the conversation feed (queue) the process is serving; absent outside a conversation. */\n readonly conversation?: URI.URI;\n}\n\n/**\n * The environment the running process was spawned with, for a handler that hands its work to another\n * runtime (e.g. EDGE dispatching an operation to its operation worker), which must carry the conversation along.\n */\nexport class EnvironmentService extends Context.Service<EnvironmentService, Environment>()(\n '@dxos/compute/Process.EnvironmentService',\n) {}\n\n/** The running process's environment; empty outside a process, so a handler can read it wherever it runs. */\nexport const currentEnvironment: Effect.Effect<Environment> = Effect.serviceOption(EnvironmentService).pipe(\n Effect.map(Option.getOrElse((): Environment => ({}))),\n);\n\n/**\n * Attaches the process to a target object.\n */\nexport const TargetAnnotation = Annotation.make({\n id: 'org.dxos.process.target',\n schema: URI.Schema,\n});\n\n/**\n * Notification descriptor for surfacing process lifecycle events to the user.\n */\nexport const NotifyAnnotation = Annotation.make({\n id: 'org.dxos.process.notify',\n schema: Operation.NotifyOptions,\n});\n\n/**\n * Marks a process as the harness host for its conversation (discovery substrate).\n */\nexport const HarnessHostAnnotation = Annotation.make({\n id: 'org.dxos.process.harnessHost',\n schema: Schema.Boolean,\n});\n\n/** Whether `info` is a conversation's agent process (stamped {@link HarnessHostAnnotation} at spawn). */\nexport const isHarnessHost = (info: Pick<Process, 'params'>): boolean =>\n Option.getOrElse(Annotation.getDictionary(info.params.annotations, HarnessHostAnnotation), () => false);\n\n/**\n * Runtime state of a process.\n */\nexport enum State {\n // Command to spawn the process has been accepted locally but the runtime hosting it has not yet\n // acknowledged it. Only ever reported by a client queueing commands for a remote runtime\n // (`RemoteCommandQueue`); a process the local runtime owns is never in this state.\n STARTING = 'STARTING',\n\n // Process is actively running.\n RUNNING = 'RUNNING',\n\n // Process is waiting for a child process to complete or an alarm to trigger.\n HYBERNATING = 'HYBERNATING',\n\n // Process is waiting for input. It will only resume when input is submitted.\n IDLE = 'IDLE',\n\n // Process is terminating and will transition to TERMINATED state.\n // TODO(dmaretskyi): Consider removing.\n TERMINATING = 'TERMINATING',\n\n // Process has been externally terminated.\n TERMINATED = 'TERMINATED',\n\n // Process has completed successfully.\n SUCCEEDED = 'SUCCEEDED',\n\n // Process has failed.\n FAILED = 'FAILED',\n}\n\n/**\n * Whether a process in `state` has exited: SUCCEEDED, FAILED or TERMINATED. A runtime never moves a\n * process out of these states, which is what makes them final for a host.\n */\nexport const isExited = (state: State): boolean =>\n state === State.SUCCEEDED || state === State.FAILED || state === State.TERMINATED;\n\n/**\n * Whether a process in `state` will never run another turn: {@link isExited}, or TERMINATING.\n * TERMINATING counts because the handle is already finished, so a caller adopting it would submit\n * input that is dropped and wait on a process that will never run again.\n */\nexport const isTerminal = (state: State): boolean => isExited(state) || state === State.TERMINATING;\n\n/** Filters for {@link Manager.list}; an absent field matches everything. */\nexport interface Filter {\n readonly key?: string;\n /** Target object the process was spawned against ({@link TargetAnnotation}). */\n readonly target?: URI.URI;\n readonly state?: State;\n /** Space from the process's {@link Environment}; a process with no space matches no space filter. */\n readonly space?: SpaceId;\n readonly parentPid?: ID | null;\n}\n\n/**\n * Whether `info` satisfies `filter`. Exported so every {@link Manager} filters identically rather\n * than each implementation growing its own notion of a match.\n */\nexport const matchesFilter = (info: Data, filter: Filter = {}): boolean => {\n if (filter.key !== undefined && info.key !== filter.key) {\n return false;\n }\n if (filter.state !== undefined && info.state !== filter.state) {\n return false;\n }\n if (filter.space !== undefined && info.environment.space !== filter.space) {\n return false;\n }\n if (filter.parentPid !== undefined && info.parentPid !== filter.parentPid) {\n return false;\n }\n if (\n filter.target !== undefined &&\n Option.getOrUndefined(Annotation.getDictionary(info.params.annotations, TargetAnnotation)) !== filter.target\n ) {\n return false;\n }\n return true;\n};\n\n/** {@link Manager.list} over a tree read, so a manager implements it by supplying only that read. */\nexport const listFromTree =\n (processTree: Effect.Effect<readonly Process[]>) =>\n (filter?: Filter): Effect.Effect<readonly Process[]> =>\n Effect.map(processTree, (tree) => tree.filter((info) => matchesFilter(info, filter)));\n\nexport interface SubscribeEphemeralOptions {\n /**\n * Replay the buffered events before streaming new ones (the default), so a reader attaching mid-turn\n * sees the turn so far. A reader that subscribes BEFORE causing the work it wants to follow passes\n * `false`: the buffer then holds only earlier turns, which would read as the new one.\n */\n readonly replay?: boolean;\n}\n\n/**\n * The plain fields of a {@link Process}: what a process tree holds, what crosses the wire, and what\n * {@link make} turns back into a process.\n */\nexport interface Data {\n readonly pid: ID;\n readonly parentPid: ID | null;\n\n /**\n * Key of the process.\n *\n * NOTE: There might be multiple running processes with the same key.\n */\n readonly key: string;\n\n /**\n * Parameters of the process.\n */\n readonly params: Params;\n\n /**\n * What the process is running on behalf of. See {@link Environment}.\n */\n readonly environment: Environment;\n\n /**\n * State of the process.\n */\n readonly state: State;\n\n /**\n * How the process failed as a serializable {@link SerializedError} (its `context` carries any\n * structured detail, e.g. a notify override), or `null` unless it is in FAILED state.\n */\n readonly error: SerializedError | null;\n\n /**\n * UNIX timestamp in milliseconds.\n */\n readonly startedAt: number;\n\n /**\n * UNIX timestamp in milliseconds.\n */\n readonly completedAt: Option.Option<number>;\n\n readonly metrics: {\n /**\n * Total wall time of all handler invocations of the process in milliseconds.\n */\n readonly wallTime: number;\n\n /**\n * Total number of inputs submitted to the process.\n */\n readonly inputCount: number;\n\n /**\n * Total number of outputs submitted to the process.\n */\n readonly outputCount: number;\n };\n}\n\nexport interface Status {\n readonly state: State;\n readonly exit: Option.Option<Exit.Exit<void>>;\n\n readonly startedAt: Date;\n readonly completedAt: Option.Option<Date>;\n}\n\n/**\n * A process: one running (or finished) instance of a durable operation, wherever its runtime runs.\n *\n * Its {@link Data} fields are plain values; the rest are live members that talk to the runtime.\n * A process read from a tree or list is a cheap snapshot that reaches its runtime only once a\n * live member is used (see {@link make}).\n */\nexport interface Process<_Input = any, _Output = any, _Rpcs extends Rpc.Any = any> extends Data {\n submitInput(input: _Input): Effect.Effect<void>;\n subscribeOutputs(): Stream.Stream<_Output>;\n\n /**\n * Subscribe to ephemeral trace messages for this process.\n * Replays buffered events, then streams new ones as they arrive.\n * The stream completes when the process reaches a terminal state.\n *\n * When consuming this stream from a short-lived parent effect (e.g. React\n * `useEffect` that `runPromise(Effect.forEach(subscribe))` and returns), fork\n * the collector with {@link Effect.forkDetach}, not {@link Effect.forkChild} — the\n * parent scope closes as soon as `forEach` finishes and interrupts scoped forks\n * before live `pushEphemeral` events arrive. Interrupt the daemon fiber explicitly\n * on dispose.\n */\n subscribeEphemeral(options?: SubscribeEphemeralOptions): Stream.Stream<Trace.Message>;\n\n terminate(): Effect.Effect<void>;\n readonly status: Status;\n\n /**\n * Absolute due-time (epoch ms) of the process's pending alarm, or `null` when none is scheduled.\n * A host that suspends the process between turns (a Durable Object) mirrors this onto its own\n * scheduler, since the runtime's alarm is an in-memory timer.\n */\n readonly alarmDueAt: number | null;\n statusAtom: Atom.Atom<Status>;\n\n /**\n * Resolves when the process reaches {@link State.IDLE} (nothing in-flight; waiting for input),\n * or a terminal state ({@link State.SUCCEEDED}, {@link State.TERMINATED}, {@link State.FAILED}).\n *\n * Does not resolve while the process is {@link State.HYBERNATING} (e.g. alarm pending or non-terminal child).\n * The effect keeps waiting until that external work finishes and the process becomes idle or terminal.\n *\n * If the process fails, this effect throws a defect.\n */\n runToCompletion(): Effect.Effect<void>;\n\n /**\n * Resolves when the process settles its current foreground turn: {@link State.IDLE} or\n * {@link State.SUCCEEDED}, or {@link State.HYBERNATING} with no pending alarm\n * (i.e. only background children remain in flight).\n *\n * Unlike {@link runToCompletion}, this does NOT wait for background children (e.g. delegated\n * sub-agents) to finish — so a supervisor's chat turn returns as soon as its reply is complete,\n * while sub-agents continue running and report back out of band. Still waits through\n * alarm-pending hybernation (more queued turn work). Defects on {@link State.FAILED}.\n */\n runUntilSettled(): Effect.Effect<void>;\n\n /**\n * Submits each input in order, then streams outputs until the process reaches {@link State.IDLE}\n * or {@link State.SUCCEEDED}. While {@link State.HYBERNATING}, keeps waiting for outputs\n * or a terminal state. The stream fails with a defect if the process reaches {@link State.FAILED}\n * or {@link State.TERMINATED}.\n */\n runAndExit(options: { readonly inputs: readonly _Input[] }): Stream.Stream<_Output>;\n\n /**\n * Hydrates a dormant persisted process using the supplied definition.\n * No-op when the handle is already live (returns self).\n */\n hydrate(definition: Operation.Durable<_Input, _Output, any, any>): Effect.Effect<Process<_Input, _Output, _Rpcs>>;\n\n readonly rpc: RpcClient.RpcClient<_Rpcs>;\n}\n\n// `any` Rpcs keeps every process assignable regardless of its concrete RPC group (variance, see design spec §4.4).\nexport type Any = Process<any, any, any>;\n\n/**\n * Options for spawning a process.\n */\nexport interface SpawnOptions {\n /**\n * Parent process ID — child inherits the parent's trace context.\n * Inside a process, its {@link ManagerService} defaults this to that process; pass `undefined`\n * explicitly to spawn a detached process.\n */\n readonly parentProcessId?: ID;\n\n /**\n * Process name for debugging purposes.\n */\n readonly name?: string;\n\n /**\n * Target object that this process is assigned to.\n * Ergonomic shorthand folded into {@link TargetAnnotation} on the process annotations.\n */\n // TODO(dmaretskyi): Consider opaques metadata instead of opinionated `target` field.\n readonly target?: URI.URI;\n\n /**\n * Tracing metadata for this invocation.\n */\n readonly traceMeta?: Trace.Meta;\n\n readonly environment?: Environment;\n\n /**\n * Who the process's database writes are attributed to (see `Database.Origin`); also the origin of every process it\n * invokes. Persisted with the process, so a restored process keeps it.\n */\n readonly origin?: Database.Origin;\n\n /**\n * User-facing notifications requested for this process's lifecycle phases.\n * Ergonomic shorthand folded into {@link NotifyAnnotation} on the process annotations.\n */\n readonly notify?: Operation.NotifyOptions;\n\n /**\n * User-defined annotations to attach to the process.\n * Caller-supplied entries are merged over the {@link target}/{@link notify} shorthands.\n */\n readonly annotations?: Annotation.Dictionary;\n}\n\nexport interface ListOptions {\n /**\n * Filter processes by process definition key.\n */\n readonly key?: string;\n\n /**\n * Filter processes by parent process ID.\n */\n readonly parentProcessId?: ID;\n\n /**\n * Filter processes by state.\n */\n readonly state?: State;\n\n /**\n * Filter processes by target object ID.\n */\n readonly target?: URI.URI;\n}\n\n//\n// Manager.\n//\n\n/** Where a process runs: this runtime, or the remote (EDGE) runtime hosting `space`. */\nexport type Location = { readonly kind: 'local' } | { readonly kind: 'edge'; readonly space: SpaceId };\n\nexport interface LocationOptions {\n /** Defaults to local. */\n readonly location?: Location;\n}\n\n/**\n * Every process this client can see or run, local and remote, behind one surface.\n *\n * The reads span both runtimes, so they answer \"is my process running, wherever it runs\" — which is\n * what a UI renders and what a caller holding no handle can ask. The control verbs take a\n * {@link Location}: a remote process is not a local one, so the caller still names where it runs,\n * but no longer has to hold both managers to do so.\n */\nexport interface Manager {\n /** Current state of the process tree. */\n readonly processTree: Effect.Effect<readonly Process[]>;\n\n /** Atom for the process tree. */\n readonly processTreeAtom: Atom.Atom<readonly Process[]>;\n\n /**\n * The process tree narrowed by {@link Filter}. A filter naming a space re-reads that space from\n * the remote runtime first, so it is the authoritative read where the atom is the cheap one.\n */\n list(filter?: Filter): Effect.Effect<readonly Process[]>;\n\n /**\n * Stream ephemeral trace messages matching `filter` (DX-1125), sourced from local in-process\n * runtimes and remote runtimes broadcasting over the space swarm. Used to drive live progress UI.\n */\n subscribeToTraceMessages(filter: Trace.Filter): Stream.Stream<Trace.Message>;\n\n /**\n * Spawn a process at `options.location`. A remote host is sent only the definition's key; the\n * definition stays local, supplying the codecs and RPC group the handle is typed by.\n *\n * Dies when the location is a remote runtime that offers no process control.\n */\n spawn<I, O, Rpcs extends Rpc.Any = never>(\n definition: Operation.Durable<I, O, any, Rpcs>,\n options?: SpawnOptions & LocationOptions,\n ): Effect.Effect<Process<I, O, Rpcs>>;\n\n /**\n * Live processes at `options.location` matching `options`. Dormant entries require\n * {@link Process.hydrate} before inputs can be submitted.\n *\n * Dies when the location is a remote runtime that offers no process control.\n */\n handles(options?: ListOptions & LocationOptions): Effect.Effect<readonly Any[]>;\n\n /**\n * The live process `pid` at `options.location`. A process that has already exited\n * replays its outputs, so its result stays readable after the exit.\n *\n * Dies when no such process is known, or when the location is a remote runtime that offers no\n * process control.\n */\n attach<I, O, Rpcs extends Rpc.Any = never>(pid: ID, options?: LocationOptions): Effect.Effect<Process<I, O, Rpcs>>;\n}\n\n/**\n * The first output of a single-output process (e.g. one running an operation), failing with the\n * process's own cause when it fails without one.\n */\nexport const awaitOutput = <O>(handle: Process<any, O, any>): Effect.Effect<O> =>\n handle.subscribeOutputs().pipe(\n Stream.runHead,\n Effect.flatMap(\n Option.match({\n onSome: Effect.succeed,\n onNone: () => {\n switch (handle.status.state) {\n case State.FAILED:\n return Effect.failCause(\n handle.status.exit.pipe(\n Option.flatMap(Exit.getCause),\n Option.getOrElse(() => Cause.die('Operation failed with unknown error')),\n ),\n );\n case State.TERMINATED:\n return Effect.die('Operation was terminated');\n case State.SUCCEEDED:\n return Effect.die('Process produced no output');\n default:\n // Outputs close on a live process only when its manager suspends it (app shutdown): the\n // wait was cut short rather than answered.\n return Effect.interrupt;\n }\n },\n }),\n ),\n );\n\nexport class ManagerService extends Context.Service<ManagerService, Manager>()(\n '@dxos/compute/Process.ManagerService',\n) {}\n\n/**\n * Spawns `durable` through the ambient {@link ManagerService} and submits `input`; read its result with\n * {@link awaitOutput}.\n */\nexport const spawn = <I, O, Rpcs extends Rpc.Any = never>(\n durable: Operation.Durable<I, O, any, Rpcs>,\n input: I,\n options?: SpawnOptions & LocationOptions,\n): Effect.Effect<Process<I, O, Rpcs>, never, ManagerService> =>\n Effect.gen(function* () {\n const manager = yield* ManagerService;\n const handle = yield* manager.spawn(durable, {\n ...(durable.name !== undefined ? { name: durable.name } : {}),\n ...options,\n });\n yield* handle.submitInput(input);\n return handle;\n });\n\n/**\n * New process is spawned.\n */\nexport const SpawnedEvent = Trace.EventType('process.spawned', {\n schema: Schema.Void,\n isEphemeral: false,\n});\n\n/**\n * Process has reached a terminal state.\n */\nexport const ExitedEvent = Trace.EventType('process.exited', {\n schema: Schema.Struct({\n outcome: Schema.Literals(['succeeded', 'failed', 'terminated']),\n }),\n isEphemeral: false,\n});\n\n/**\n * Renders spawned processes as a forest: top-level rows use \"- \", nested rows use ├── / └── / │.\n */\nexport const prettyProcessTree = (tree: readonly Process[]): string => {\n if (tree.length === 0) {\n return '';\n }\n\n const pidSet = new Set(tree.map((node) => node.pid));\n const childrenByParent = new Map<string, Process[]>();\n const roots: Process[] = [];\n\n for (const node of tree) {\n const parent = node.parentPid;\n if (parent === null || !pidSet.has(parent)) {\n roots.push(node);\n continue;\n }\n const key = String(parent);\n const siblings = childrenByParent.get(key) ?? [];\n siblings.push(node);\n childrenByParent.set(key, siblings);\n }\n\n const byPid = (a: Process, b: Process) => String(a.pid).localeCompare(String(b.pid));\n roots.sort(byPid);\n for (const siblings of childrenByParent.values()) {\n siblings.sort(byPid);\n }\n\n const formatLabel = (node: Process): string => {\n const idShort = String(node.pid).slice(0, 6);\n const parts = [idShort, node.state];\n if (node.params.name != null && node.params.name !== '') {\n parts.push(node.params.name);\n }\n if (node.error != null) {\n parts.push(`(${node.error.message ?? node.error.name ?? 'error'})`);\n }\n const { inputCount, outputCount, wallTime } = node.metrics;\n parts.push(`[in:${inputCount} out:${outputCount} wall:${Math.round(wallTime)}ms]`);\n return parts.join(' ');\n };\n\n const lines: string[] = [];\n\n const walk = (node: Process, prefix: string, isLast: boolean, isRoot: boolean): void => {\n if (isRoot) {\n lines.push(`- ${formatLabel(node)}`);\n } else {\n const branch = isLast ? '└── ' : '├── ';\n lines.push(`${prefix}${branch}${formatLabel(node)}`);\n }\n\n const children = childrenByParent.get(String(node.pid)) ?? [];\n const nextPrefix = isRoot ? ' ' : `${prefix}${isLast ? ' ' : '│ '}`;\n children.forEach((child, index) => {\n walk(child, nextPrefix, index === children.length - 1, false);\n });\n };\n\n for (const root of roots) {\n walk(root, '', true, true);\n }\n\n return lines.join('\\n');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,KAAK,OAAO,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;;;;;AAoC9D,IAAa,qBAAb,cAAwC,QAAQ,QAAyC,CAAC,CACxF,0CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,qBAAiD,OAAO,cAAc,kBAAkB,CAAC,CAAC,KACrG,OAAO,IAAI,OAAO,iBAA8B,CAAC,EAAE,CAAC,CACtD;;;;AAKA,IAAa,m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SAAS,SAAS,OAAO,UAAU;GACjC,KAAK,OAAO,YAAY,UAAU,SAAS,SAAS,GAAG,KAAK;EAC9D,CAAC;CACH;CAEA,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,IAAI,MAAM,IAAI;CAG3B,OAAO,MAAM,KAAK,IAAI;AACxB"}
|
|
1
|
+
{"version":3,"file":"chunk-Process.mjs","names":["URI","Operation.NotifyOptions","Operation.isScript","Trace.EventType"],"sources":["../../src/Process.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\n// @import-as-namespace\n\nimport * as Cause from 'effect/Cause';\nimport * as Context from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Option from 'effect/Option';\nimport type * as Atom from 'effect/reactivity/Atom';\nimport type * as Rpc from 'effect/rpc/Rpc';\nimport type * as RpcClient from 'effect/rpc/RpcClient';\nimport * as Schema from 'effect/Schema';\nimport * as Stream from 'effect/Stream';\n\nimport { Annotation, type Database } from '@dxos/echo';\nimport { type SpaceId, URI } from '@dxos/keys';\nimport type { SerializedError } from '@dxos/protocols';\n\nimport * as Operation from './Operation.ts';\nimport * as Trace from './Trace.ts';\n\nexport { RUN_AGAIN_ERROR_CODE, RUN_AGAIN_MESSAGE, RunAgainError } from './errors.ts';\n\n//\n// Process.\n//\n\n/** Opaque process id (arbitrary string). */\nexport const ID = Schema.String.pipe(Schema.brand('ProcessId'));\nexport type ID = Schema.Schema.Type<typeof ID>;\n\n/**\n * Generic parameters for a all processes.\n */\nexport interface Params {\n /**\n * Process name for debugging purposes.\n */\n readonly name: string | null;\n\n /**\n * User-defined annotations for the process.\n * Can only be set when the process is spawned.\n */\n readonly annotations: Annotation.Dictionary;\n}\n\n/**\n * What the process is running on behalf of, fixed at spawn and inherited by child processes.\n *\n * Determines which services the runtime can provide (a space-scoped database, a conversation's harness).\n */\nexport interface Environment {\n /** Space the process is scoped to; absent for app-level work. */\n readonly space?: SpaceId;\n\n /** URI of the conversation feed (queue) the process is serving; absent outside a conversation. */\n readonly conversation?: URI.URI;\n}\n\n/**\n * The environment the running process was spawned with, for a handler that hands its work to another\n * runtime (e.g. EDGE dispatching an operation to its operation worker), which must carry the conversation along.\n */\nexport class EnvironmentService extends Context.Service<EnvironmentService, Environment>()(\n '@dxos/compute/Process.EnvironmentService',\n) {}\n\n/** The running process's environment; empty outside a process, so a handler can read it wherever it runs. */\nexport const currentEnvironment: Effect.Effect<Environment> = Effect.serviceOption(EnvironmentService).pipe(\n Effect.map(Option.getOrElse((): Environment => ({}))),\n);\n\n/**\n * Attaches the process to a target object.\n */\nexport const TargetAnnotation = Annotation.make({\n id: 'org.dxos.process.target',\n schema: URI.Schema,\n});\n\n/**\n * Notification descriptor for surfacing process lifecycle events to the user.\n */\nexport const NotifyAnnotation = Annotation.make({\n id: 'org.dxos.process.notify',\n schema: Operation.NotifyOptions,\n});\n\n/**\n * Marks a process as the harness host for its conversation (discovery substrate).\n */\nexport const HarnessHostAnnotation = Annotation.make({\n id: 'org.dxos.process.harnessHost',\n schema: Schema.Boolean,\n});\n\n/** Whether `info` is a conversation's agent process (stamped {@link HarnessHostAnnotation} at spawn). */\nexport const isHarnessHost = (info: Pick<Process, 'params'>): boolean =>\n Option.getOrElse(Annotation.getDictionary(info.params.annotations, HarnessHostAnnotation), () => false);\n\n/**\n * Runtime state of a process.\n */\nexport enum State {\n // Command to spawn the process has been accepted locally but the runtime hosting it has not yet\n // acknowledged it. Only ever reported by a client queueing commands for a remote runtime\n // (`RemoteCommandQueue`); a process the local runtime owns is never in this state.\n STARTING = 'STARTING',\n\n // Process is actively running.\n RUNNING = 'RUNNING',\n\n // Process is waiting for a child process to complete or an alarm to trigger.\n HYBERNATING = 'HYBERNATING',\n\n // Process is waiting for input. It will only resume when input is submitted.\n IDLE = 'IDLE',\n\n // Process is terminating and will transition to TERMINATED state.\n // TODO(dmaretskyi): Consider removing.\n TERMINATING = 'TERMINATING',\n\n // Process has been externally terminated.\n TERMINATED = 'TERMINATED',\n\n // Process has completed successfully.\n SUCCEEDED = 'SUCCEEDED',\n\n // Process has failed.\n FAILED = 'FAILED',\n}\n\n/**\n * Whether a process in `state` has exited: SUCCEEDED, FAILED or TERMINATED. A runtime never moves a\n * process out of these states, which is what makes them final for a host.\n */\nexport const isExited = (state: State): boolean =>\n state === State.SUCCEEDED || state === State.FAILED || state === State.TERMINATED;\n\n/**\n * Whether a process in `state` will never run another turn: {@link isExited}, or TERMINATING.\n * TERMINATING counts because the handle is already finished, so a caller adopting it would submit\n * input that is dropped and wait on a process that will never run again.\n */\nexport const isTerminal = (state: State): boolean => isExited(state) || state === State.TERMINATING;\n\n/** Filters for {@link Manager.list}; an absent field matches everything. */\nexport interface Filter {\n readonly key?: string;\n /** Target object the process was spawned against ({@link TargetAnnotation}). */\n readonly target?: URI.URI;\n readonly state?: State;\n /** Space from the process's {@link Environment}; a process with no space matches no space filter. */\n readonly space?: SpaceId;\n readonly parentPid?: ID | null;\n}\n\n/**\n * Whether `info` satisfies `filter`. Exported so every {@link Manager} filters identically rather\n * than each implementation growing its own notion of a match.\n */\nexport const matchesFilter = (info: Data, filter: Filter = {}): boolean => {\n if (filter.key !== undefined && info.key !== filter.key) {\n return false;\n }\n if (filter.state !== undefined && info.state !== filter.state) {\n return false;\n }\n if (filter.space !== undefined && info.environment.space !== filter.space) {\n return false;\n }\n if (filter.parentPid !== undefined && info.parentPid !== filter.parentPid) {\n return false;\n }\n if (\n filter.target !== undefined &&\n Option.getOrUndefined(Annotation.getDictionary(info.params.annotations, TargetAnnotation)) !== filter.target\n ) {\n return false;\n }\n return true;\n};\n\n/** {@link Manager.list} over a tree read, so a manager implements it by supplying only that read. */\nexport const listFromTree =\n (processTree: Effect.Effect<readonly Process[]>) =>\n (filter?: Filter): Effect.Effect<readonly Process[]> =>\n Effect.map(processTree, (tree) => tree.filter((info) => matchesFilter(info, filter)));\n\nexport interface SubscribeEphemeralOptions {\n /**\n * Replay the buffered events before streaming new ones (the default), so a reader attaching mid-turn\n * sees the turn so far. A reader that subscribes BEFORE causing the work it wants to follow passes\n * `false`: the buffer then holds only earlier turns, which would read as the new one.\n */\n readonly replay?: boolean;\n}\n\n/**\n * The plain fields of a {@link Process}: what a process tree holds, what crosses the wire, and what\n * {@link make} turns back into a process.\n */\nexport interface Data {\n readonly pid: ID;\n readonly parentPid: ID | null;\n\n /**\n * Key of the process.\n *\n * NOTE: There might be multiple running processes with the same key.\n */\n readonly key: string;\n\n /**\n * Parameters of the process.\n */\n readonly params: Params;\n\n /**\n * What the process is running on behalf of. See {@link Environment}.\n */\n readonly environment: Environment;\n\n /**\n * State of the process.\n */\n readonly state: State;\n\n /**\n * How the process failed as a serializable {@link SerializedError} (its `context` carries any\n * structured detail, e.g. a notify override), or `null` unless it is in FAILED state.\n */\n readonly error: SerializedError | null;\n\n /**\n * UNIX timestamp in milliseconds.\n */\n readonly startedAt: number;\n\n /**\n * UNIX timestamp in milliseconds.\n */\n readonly completedAt: Option.Option<number>;\n\n readonly metrics: {\n /**\n * Total wall time of all handler invocations of the process in milliseconds.\n */\n readonly wallTime: number;\n\n /**\n * Total number of inputs submitted to the process.\n */\n readonly inputCount: number;\n\n /**\n * Total number of outputs submitted to the process.\n */\n readonly outputCount: number;\n };\n}\n\nexport interface Status {\n readonly state: State;\n readonly exit: Option.Option<Exit.Exit<void>>;\n\n readonly startedAt: Date;\n readonly completedAt: Option.Option<Date>;\n}\n\n/**\n * A process: one running (or finished) instance of a durable operation, wherever its runtime runs.\n *\n * Its {@link Data} fields are plain values; the rest are live members that talk to the runtime.\n * A process read from a tree or list is a cheap snapshot that reaches its runtime only once a\n * live member is used (see {@link make}).\n */\nexport interface Process<_Input = any, _Output = any, _Rpcs extends Rpc.Any = any> extends Data {\n submitInput(input: _Input): Effect.Effect<void>;\n subscribeOutputs(): Stream.Stream<_Output>;\n\n /**\n * Subscribe to ephemeral trace messages for this process.\n * Replays buffered events, then streams new ones as they arrive.\n * The stream completes when the process reaches a terminal state.\n *\n * When consuming this stream from a short-lived parent effect (e.g. React\n * `useEffect` that `runPromise(Effect.forEach(subscribe))` and returns), fork\n * the collector with {@link Effect.forkDetach}, not {@link Effect.forkChild} — the\n * parent scope closes as soon as `forEach` finishes and interrupts scoped forks\n * before live `pushEphemeral` events arrive. Interrupt the daemon fiber explicitly\n * on dispose.\n */\n subscribeEphemeral(options?: SubscribeEphemeralOptions): Stream.Stream<Trace.Message>;\n\n terminate(): Effect.Effect<void>;\n readonly status: Status;\n\n /**\n * Absolute due-time (epoch ms) of the process's pending alarm, or `null` when none is scheduled.\n * A host that suspends the process between turns (a Durable Object) mirrors this onto its own\n * scheduler, since the runtime's alarm is an in-memory timer.\n */\n readonly alarmDueAt: number | null;\n statusAtom: Atom.Atom<Status>;\n\n /**\n * Resolves when the process reaches {@link State.IDLE} (nothing in-flight; waiting for input),\n * or a terminal state ({@link State.SUCCEEDED}, {@link State.TERMINATED}, {@link State.FAILED}).\n *\n * Does not resolve while the process is {@link State.HYBERNATING} (e.g. alarm pending or non-terminal child).\n * The effect keeps waiting until that external work finishes and the process becomes idle or terminal.\n *\n * If the process fails, this effect throws a defect.\n */\n runToCompletion(): Effect.Effect<void>;\n\n /**\n * Resolves when the process settles its current foreground turn: {@link State.IDLE} or\n * {@link State.SUCCEEDED}, or {@link State.HYBERNATING} with no pending alarm\n * (i.e. only background children remain in flight).\n *\n * Unlike {@link runToCompletion}, this does NOT wait for background children (e.g. delegated\n * sub-agents) to finish — so a supervisor's chat turn returns as soon as its reply is complete,\n * while sub-agents continue running and report back out of band. Still waits through\n * alarm-pending hybernation (more queued turn work). Defects on {@link State.FAILED}.\n */\n runUntilSettled(): Effect.Effect<void>;\n\n /**\n * Submits each input in order, then streams outputs until the process reaches {@link State.IDLE}\n * or {@link State.SUCCEEDED}. While {@link State.HYBERNATING}, keeps waiting for outputs\n * or a terminal state. The stream fails with a defect if the process reaches {@link State.FAILED}\n * or {@link State.TERMINATED}.\n */\n runAndExit(options: { readonly inputs: readonly _Input[] }): Stream.Stream<_Output>;\n\n /**\n * Hydrates a dormant persisted process using the supplied definition.\n * No-op when the handle is already live (returns self).\n */\n hydrate(definition: Operation.Durable<_Input, _Output, any, any>): Effect.Effect<Process<_Input, _Output, _Rpcs>>;\n\n readonly rpc: RpcClient.RpcClient<_Rpcs>;\n}\n\n// `any` Rpcs keeps every process assignable regardless of its concrete RPC group (variance, see design spec §4.4).\nexport type Any = Process<any, any, any>;\n\n/**\n * Admits or refuses an operation a process invokes, for operations that declare requirements\n * (`Operation.RequiresAnnotation`). Refuses by dying with `Operation.OperationDeniedError`.\n */\nexport interface Guard {\n readonly check: (op: Operation.Definition.Any, input: unknown) => Effect.Effect<void>;\n}\n\n/** The guard of the running process; absent when it was spawned without one. */\nexport class GuardService extends Context.Service<GuardService, Guard>()('@dxos/compute/Process.GuardService') {}\n\n/** A guard that admits only what both admit, so a child spawned with its own guard never widens its parent's. */\nexport const bothGuards = (first: Guard, second: Guard): Guard => ({\n check: (op, input) => first.check(op, input).pipe(Effect.andThen(second.check(op, input))),\n});\n\n/**\n * Options for spawning a process.\n */\nexport interface SpawnOptions {\n /**\n * Parent process ID — child inherits the parent's trace context.\n * Inside a process, its {@link ManagerService} defaults this to that process; pass `undefined`\n * explicitly to spawn a detached process.\n */\n readonly parentProcessId?: ID;\n\n /**\n * Process name for debugging purposes.\n */\n readonly name?: string;\n\n /**\n * Target object that this process is assigned to.\n * Ergonomic shorthand folded into {@link TargetAnnotation} on the process annotations.\n */\n // TODO(dmaretskyi): Consider opaques metadata instead of opinionated `target` field.\n readonly target?: URI.URI;\n\n /**\n * Tracing metadata for this invocation.\n */\n readonly traceMeta?: Trace.Meta;\n\n readonly environment?: Environment;\n\n /**\n * Admits the operations this process invokes that declare requirements. Inherited by children;\n * a child's own guard is combined with its parent's, never replaces it. Not persisted, so a\n * rehydrated process holds none and refuses operations that declare requirements.\n */\n readonly guard?: Guard;\n\n /**\n * Who the process's database writes are attributed to (see `Database.Origin`); also the origin of every process it\n * invokes. Persisted with the process, so a restored process keeps it.\n */\n readonly origin?: Database.Origin;\n\n /**\n * User-facing notifications requested for this process's lifecycle phases.\n * Ergonomic shorthand folded into {@link NotifyAnnotation} on the process annotations.\n */\n readonly notify?: Operation.NotifyOptions;\n\n /**\n * User-defined annotations to attach to the process.\n * Caller-supplied entries are merged over the {@link target}/{@link notify} shorthands.\n */\n readonly annotations?: Annotation.Dictionary;\n}\n\nexport interface ListOptions {\n /**\n * Filter processes by process definition key.\n */\n readonly key?: string;\n\n /**\n * Filter processes by parent process ID.\n */\n readonly parentProcessId?: ID;\n\n /**\n * Filter processes by state.\n */\n readonly state?: State;\n\n /**\n * Filter processes by target object ID.\n */\n readonly target?: URI.URI;\n}\n\n//\n// Manager.\n//\n\n/** Where a process runs: this runtime, or the remote (EDGE) runtime hosting `space`. */\nexport type Location = { readonly kind: 'local' } | { readonly kind: 'edge'; readonly space: SpaceId };\n\nexport interface LocationOptions {\n /** Defaults to local. */\n readonly location?: Location;\n}\n\n/**\n * Every process this client can see or run, local and remote, behind one surface.\n *\n * The reads span both runtimes, so they answer \"is my process running, wherever it runs\" — which is\n * what a UI renders and what a caller holding no handle can ask. The control verbs take a\n * {@link Location}: a remote process is not a local one, so the caller still names where it runs,\n * but no longer has to hold both managers to do so.\n */\nexport interface Manager {\n /** Current state of the process tree. */\n readonly processTree: Effect.Effect<readonly Process[]>;\n\n /** Atom for the process tree. */\n readonly processTreeAtom: Atom.Atom<readonly Process[]>;\n\n /**\n * The process tree narrowed by {@link Filter}. A filter naming a space re-reads that space from\n * the remote runtime first, so it is the authoritative read where the atom is the cheap one.\n */\n list(filter?: Filter): Effect.Effect<readonly Process[]>;\n\n /**\n * Stream ephemeral trace messages matching `filter` (DX-1125), sourced from local in-process\n * runtimes and remote runtimes broadcasting over the space swarm. Used to drive live progress UI.\n */\n subscribeToTraceMessages(filter: Trace.Filter): Stream.Stream<Trace.Message>;\n\n /**\n * Spawn a process at `options.location`. A remote host is sent only the definition's key; the\n * definition stays local, supplying the codecs and RPC group the handle is typed by.\n *\n * A script operation spawns like a durable one: the runtime runs its code itself, so the run is a\n * process like any other — a pid, a parent, its guard, children of its own.\n *\n * Dies when the location is a remote runtime that offers no process control.\n */\n spawn<I, O, Rpcs extends Rpc.Any = never>(\n definition: Operation.Durable<I, O, any, Rpcs> | Operation.ScriptDefinition<I, O>,\n options?: SpawnOptions & LocationOptions,\n ): Effect.Effect<Process<I, O, Rpcs>>;\n\n /**\n * Live processes at `options.location` matching `options`. Dormant entries require\n * {@link Process.hydrate} before inputs can be submitted.\n *\n * Dies when the location is a remote runtime that offers no process control.\n */\n handles(options?: ListOptions & LocationOptions): Effect.Effect<readonly Any[]>;\n\n /**\n * The live process `pid` at `options.location`. A process that has already exited\n * replays its outputs, so its result stays readable after the exit.\n *\n * Dies when no such process is known, or when the location is a remote runtime that offers no\n * process control.\n */\n attach<I, O, Rpcs extends Rpc.Any = never>(pid: ID, options?: LocationOptions): Effect.Effect<Process<I, O, Rpcs>>;\n}\n\n/**\n * The first output of a single-output process (e.g. one running an operation), failing with the\n * process's own cause when it fails without one.\n */\nexport const awaitOutput = <O>(handle: Process<any, O, any>): Effect.Effect<O> =>\n handle.subscribeOutputs().pipe(\n Stream.runHead,\n Effect.flatMap(\n Option.match({\n onSome: Effect.succeed,\n onNone: () => {\n switch (handle.status.state) {\n case State.FAILED:\n return Effect.failCause(\n handle.status.exit.pipe(\n Option.flatMap(Exit.getCause),\n Option.getOrElse(() => Cause.die('Operation failed with unknown error')),\n ),\n );\n case State.TERMINATED:\n return Effect.die('Operation was terminated');\n case State.SUCCEEDED:\n return Effect.die('Process produced no output');\n default:\n // Outputs close on a live process only when its manager suspends it (app shutdown): the\n // wait was cut short rather than answered.\n return Effect.interrupt;\n }\n },\n }),\n ),\n );\n\nexport class ManagerService extends Context.Service<ManagerService, Manager>()(\n '@dxos/compute/Process.ManagerService',\n) {}\n\n/**\n * Spawns `definition` — a durable operation or a script operation — through the ambient\n * {@link ManagerService} and submits `input`; read its result with {@link awaitOutput}.\n */\nexport const spawn = <I, O, Rpcs extends Rpc.Any = never>(\n definition: Operation.Durable<I, O, any, Rpcs> | Operation.ScriptDefinition<I, O>,\n input: I,\n options?: SpawnOptions & LocationOptions,\n): Effect.Effect<Process<I, O, Rpcs>, never, ManagerService> =>\n Effect.gen(function* () {\n const manager = yield* ManagerService;\n const name = Operation.isScript(definition) ? definition.meta.name : definition.name;\n const handle = yield* manager.spawn(definition, {\n ...(name !== undefined ? { name } : {}),\n ...options,\n });\n yield* handle.submitInput(input);\n return handle;\n });\n\n/**\n * New process is spawned.\n */\nexport const SpawnedEvent = Trace.EventType('process.spawned', {\n schema: Schema.Void,\n isEphemeral: false,\n});\n\n/**\n * Process has reached a terminal state.\n */\nexport const ExitedEvent = Trace.EventType('process.exited', {\n schema: Schema.Struct({\n outcome: Schema.Literals(['succeeded', 'failed', 'terminated']),\n }),\n isEphemeral: false,\n});\n\n/**\n * Renders spawned processes as a forest: top-level rows use \"- \", nested rows use ├── / └── / │.\n */\nexport const prettyProcessTree = (tree: readonly Process[]): string => {\n if (tree.length === 0) {\n return '';\n }\n\n const pidSet = new Set(tree.map((node) => node.pid));\n const childrenByParent = new Map<string, Process[]>();\n const roots: Process[] = [];\n\n for (const node of tree) {\n const parent = node.parentPid;\n if (parent === null || !pidSet.has(parent)) {\n roots.push(node);\n continue;\n }\n const key = String(parent);\n const siblings = childrenByParent.get(key) ?? [];\n siblings.push(node);\n childrenByParent.set(key, siblings);\n }\n\n const byPid = (a: Process, b: Process) => String(a.pid).localeCompare(String(b.pid));\n roots.sort(byPid);\n for (const siblings of childrenByParent.values()) {\n siblings.sort(byPid);\n }\n\n const formatLabel = (node: Process): string => {\n const idShort = String(node.pid).slice(0, 6);\n const parts = [idShort, node.state];\n if (node.params.name != null && node.params.name !== '') {\n parts.push(node.params.name);\n }\n if (node.error != null) {\n parts.push(`(${node.error.message ?? node.error.name ?? 'error'})`);\n }\n const { inputCount, outputCount, wallTime } = node.metrics;\n parts.push(`[in:${inputCount} out:${outputCount} wall:${Math.round(wallTime)}ms]`);\n return parts.join(' ');\n };\n\n const lines: string[] = [];\n\n const walk = (node: Process, prefix: string, isLast: boolean, isRoot: boolean): void => {\n if (isRoot) {\n lines.push(`- ${formatLabel(node)}`);\n } else {\n const branch = isLast ? '└── ' : '├── ';\n lines.push(`${prefix}${branch}${formatLabel(node)}`);\n }\n\n const children = childrenByParent.get(String(node.pid)) ?? [];\n const nextPrefix = isRoot ? ' ' : `${prefix}${isLast ? ' ' : '│ '}`;\n children.forEach((child, index) => {\n walk(child, nextPrefix, index === children.length - 1, false);\n });\n };\n\n for (const root of roots) {\n walk(root, '', true, true);\n }\n\n return lines.join('\\n');\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAa,KAAK,OAAO,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;;;;;AAoC9D,IAAa,qBAAb,cAAwC,QAAQ,QAAyC,CAAC,CACxF,0CACF,CAAC,CAAC,CAAC;;AAGH,IAAa,qBAAiD,OAAO,cAAc,kBAAkB,CAAC,CAAC,KACrG,OAAO,IAAI,OAAO,iBAA8B,CAAC,EAAE,CAAC,CACtD;;;;AAKA,IAAa,mBAAmB,WAAW,KAAK;CAC9C,IAAI;CACJ,QAAQA,MAAI;AACd,CAAC;;;;AAKD,IAAa,mBAAmB,WAAW,KAAK;CAC9C,IAAI;CACJ,QAAQC;AACV,CAAC;;;;AAKD,IAAa,wBAAwB,WAAW,KAAK;CACnD,IAAI;CACJ,QAAQ,OAAO;AACjB,CAAC;;AAGD,IAAa,iBAAiB,SAC5B,OAAO,UAAU,WAAW,cAAc,KAAK,OAAO,aAAa,qBAAqB,SAAS,KAAK;;;;AAKxG,IAAY,QAAL,yBAAA,OAAA;CAIL,MAAA,cAAA;CAGA,MAAA,aAAA;CAGA,MAAA,iBAAA;CAGA,MAAA,UAAA;CAIA,MAAA,iBAAA;CAGA,MAAA,gBAAA;CAGA,MAAA,e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