@dxos/compute 0.13.0 → 0.14.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/AgentService.mjs.map +1 -1
- package/dist/lib/Operation.mjs +41 -14
- package/dist/lib/Operation.mjs.map +1 -1
- package/dist/lib/OperationHandlerSet.mjs +1 -1
- package/dist/lib/Process.mjs +34 -2
- package/dist/lib/Process.mjs.map +1 -1
- package/dist/lib/ShellService.mjs +24 -0
- package/dist/lib/ShellService.mjs.map +1 -0
- package/dist/lib/chunk-SqlService.mjs +2 -2
- package/dist/lib/errors.mjs +7 -1
- package/dist/lib/errors.mjs.map +1 -1
- package/dist/lib/index.mjs +2 -1
- package/dist/lib/types/Project.mjs +8 -0
- package/dist/lib/types/Project.mjs.map +1 -1
- package/dist/lib/types/Skill.mjs +7 -1
- package/dist/lib/types/Skill.mjs.map +1 -1
- package/dist/lib/types/Trigger.mjs +6 -5
- package/dist/lib/types/Trigger.mjs.map +1 -1
- package/dist/types/src/AgentService.d.ts +2 -1
- package/dist/types/src/AgentService.d.ts.map +1 -1
- package/dist/types/src/Operation.d.ts +64 -11
- package/dist/types/src/Operation.d.ts.map +1 -1
- package/dist/types/src/Process.d.ts +53 -31
- package/dist/types/src/Process.d.ts.map +1 -1
- package/dist/types/src/ShellService.d.ts +85 -0
- package/dist/types/src/ShellService.d.ts.map +1 -0
- package/dist/types/src/errors.d.ts +31 -0
- package/dist/types/src/errors.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -0
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/types/Project.d.ts +2 -0
- package/dist/types/src/types/Project.d.ts.map +1 -1
- package/dist/types/src/types/Skill.d.ts +8 -0
- package/dist/types/src/types/Skill.d.ts.map +1 -1
- package/dist/types/src/types/Trigger.d.ts +11 -9
- package/dist/types/src/types/Trigger.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +20 -15
- package/src/AgentService.ts +2 -1
- package/src/DurableOperation.tst.ts +155 -0
- package/src/Operation.ts +121 -46
- package/src/Process.ts +99 -41
- package/src/ShellService.ts +71 -0
- package/src/errors.ts +7 -0
- package/src/index.ts +1 -0
- package/src/types/Project.ts +11 -0
- package/src/types/Skill.ts +9 -0
- package/src/types/Trigger.ts +9 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentService.mjs","names":[],"sources":["../../src/AgentService.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 type * as Atom from 'effect/reactivity/Atom';\nimport type * as Stream from 'effect/Stream';\n\nimport type { SessionConfig } from '@dxos/ai';\nimport type { Database, Feed, Obj, Ref } from '@dxos/echo';\nimport { DXN } from '@dxos/keys';\nimport type { ContentBlock } from '@dxos/types';\n\nimport type * as Trace from './Trace.ts';\nimport { Instructions } from './types/index.ts';\n\n/**\n * Structural view of the `Chat` object (`@dxos/assistant/Chat`): the durable conversation an agent\n * runs on, carrying its message feed and the instructions steering it. Declared structurally\n * because `@dxos/assistant` sits above this package.\n */\nexport interface Conversation extends Obj.Unknown {\n readonly feed: Ref.Ref<Feed.Feed>;\n readonly instructions?: Ref.Ref<Instructions.Instructions>;\n /** How the conversation runs (its model); an unset model runs the agent's default. */\n readonly session?: SessionConfig.SessionConfig;\n}\n\n/**\n * Service interface for the agent session manager.\n * Implementation lives in @dxos/functions-runtime.\n */\nexport interface Service {\n /**\n * Gets or creates a session for a chat. The agent process is bound to the chat (its spawn\n * target), reading the feed, the steering instructions and the model from it.\n */\n getSession: (chat: Conversation, options?: GetSessionOptions) => Effect.Effect<Session, never, Database.Service>;\n\n /**\n * Hydrates agent processes persisted by a previous session.\n * Each record is rehydrated with a fresh process built from the layer options.\n */\n hydrate: () => Effect.Effect<void>;\n}\n\nexport class AgentService extends Context.Service<AgentService, Service>()('@dxos/functions-runtime/AgentService') {}\n\n/** Re-exported so callers importing this module as a namespace avoid `AgentService.AgentService.key`. */\nexport const key = AgentService.key;\n\n/**\n * Who a prompt is from, when it is not the session's own reader: the plain-data subset of `Actor`,\n * because the prompt crosses a JSON boundary (a remote process) where a `Ref` cannot be supplied.\n */\nexport type PromptSender = {\n readonly name?: string;\n readonly identityDid?: string;\n readonly email?: string;\n};\n\nexport type SubmitPromptOptions = {\n /** Recorded on the appended user message; a named sender is shown to the model as the speaker. */\n readonly sender?: PromptSender;\n};\n\n/**\n * Handle to an agent session.\n */\nexport interface Session {\n /**\n * The chat that the session is associated with.\n */\n readonly chat: Conversation;\n\n /**\n * The feed carrying the chat's messages.\n */\n readonly feed: Feed.Feed;\n\n /**\n * Gets the context objects from the agent.\n */\n getContext: () => Effect.Effect<Ref.Ref<Obj.Unknown>[], never, Database.Service>;\n\n /**\n * Adds context objects to the agent.\n */\n addContext: (context: Ref.Ref<Obj.Unknown>[]) => Effect.Effect<void, never, Database.Service>;\n\n /**\n * Submit a turn: a plain user prompt, or pre-built content blocks (e.g. synthetic context + prompt).\n */\n submitPrompt: (prompt: string | ContentBlock.Any[], options?: SubmitPromptOptions) => Effect.Effect<void>;\n\n /**\n * True while the agent is working on a turn (running, or waiting on a tool call or alarm); false\n * when it is idle awaiting input, or terminal.\n */\n readonly running: Atom.Atom<boolean>;\n\n /**\n * Wait until agent has completed its work.\n */\n waitForCompletion: () => Effect.Effect<void>;\n\n /**\n * Terminates the agent process and clears its durable storage.\n */\n terminate: () => Effect.Effect<void>;\n\n /**\n * Subscribe to ephemeral trace events (e.g., streaming partial messages).\n * Replays buffered events, then streams new ones until the process ends.\n *\n * When forking a collector from a short-lived parent (e.g. `useEffect` +\n * `runPromise(Effect.forEach(subscribe))`), use {@link Effect.forkDetach} so the\n * stream survives after the parent scope closes; interrupt it on dispose.\n */\n subscribeEphemeral: () => Stream.Stream<Trace.Message>;\n}\n\nexport const getSession = (...args: Parameters<Context.Service.Shape<typeof AgentService>['getSession']>) =>\n AgentService.use((service) => service.getSession(...args));\n\nexport const hydrate = (...args: Parameters<Context.Service.Shape<typeof AgentService>['hydrate']>) =>\n AgentService.use((service) => service.hydrate(...args));\n\nexport interface GetSessionOptions {\n // The model is read off the chat (see `Conversation.session`), but the catalog's shared model ids are\n // served by several providers, so the provider must still accompany it into the agent process —\n // the id alone does not identify a resolver.\n readonly provider?: DXN.DXN;\n readonly systemPrompt?: string;\n /**\n * Where the agent runs. `local` executes it in this runtime; `edge` spawns it on the remote host\n * reached through `RemoteProcessManager.Service`, so the conversation continues with the client\n * closed. Read at spawn only, like `model` — moving a live conversation between runtimes would\n * mean handing one process's durable state to another.\n *\n * @default 'local'\n */\n readonly location?: AgentLocation;\n}\n\nexport type AgentLocation = 'local' | 'edge';\n"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"AgentService.mjs","names":[],"sources":["../../src/AgentService.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 type * as Atom from 'effect/reactivity/Atom';\nimport type * as Stream from 'effect/Stream';\n\nimport type { SessionConfig } from '@dxos/ai';\nimport type { Database, Feed, Obj, Ref } from '@dxos/echo';\nimport { DXN } from '@dxos/keys';\nimport type { ContentBlock } from '@dxos/types';\n\nimport type * as Process from './Process.ts';\nimport type * as Trace from './Trace.ts';\nimport { Instructions } from './types/index.ts';\n\n/**\n * Structural view of the `Chat` object (`@dxos/assistant/Chat`): the durable conversation an agent\n * runs on, carrying its message feed and the instructions steering it. Declared structurally\n * because `@dxos/assistant` sits above this package.\n */\nexport interface Conversation extends Obj.Unknown {\n readonly feed: Ref.Ref<Feed.Feed>;\n readonly instructions?: Ref.Ref<Instructions.Instructions>;\n /** How the conversation runs (its model); an unset model runs the agent's default. */\n readonly session?: SessionConfig.SessionConfig;\n}\n\n/**\n * Service interface for the agent session manager.\n * Implementation lives in @dxos/functions-runtime.\n */\nexport interface Service {\n /**\n * Gets or creates a session for a chat. The agent process is bound to the chat (its spawn\n * target), reading the feed, the steering instructions and the model from it.\n */\n getSession: (chat: Conversation, options?: GetSessionOptions) => Effect.Effect<Session, never, Database.Service>;\n\n /**\n * Hydrates agent processes persisted by a previous session.\n * Each record is rehydrated with a fresh process built from the layer options.\n */\n hydrate: () => Effect.Effect<void>;\n}\n\nexport class AgentService extends Context.Service<AgentService, Service>()('@dxos/functions-runtime/AgentService') {}\n\n/** Re-exported so callers importing this module as a namespace avoid `AgentService.AgentService.key`. */\nexport const key = AgentService.key;\n\n/**\n * Who a prompt is from, when it is not the session's own reader: the plain-data subset of `Actor`,\n * because the prompt crosses a JSON boundary (a remote process) where a `Ref` cannot be supplied.\n */\nexport type PromptSender = {\n readonly name?: string;\n readonly identityDid?: string;\n readonly email?: string;\n};\n\nexport type SubmitPromptOptions = {\n /** Recorded on the appended user message; a named sender is shown to the model as the speaker. */\n readonly sender?: PromptSender;\n};\n\n/**\n * Handle to an agent session.\n */\nexport interface Session {\n /**\n * The chat that the session is associated with.\n */\n readonly chat: Conversation;\n\n /**\n * The feed carrying the chat's messages.\n */\n readonly feed: Feed.Feed;\n\n /**\n * Gets the context objects from the agent.\n */\n getContext: () => Effect.Effect<Ref.Ref<Obj.Unknown>[], never, Database.Service>;\n\n /**\n * Adds context objects to the agent.\n */\n addContext: (context: Ref.Ref<Obj.Unknown>[]) => Effect.Effect<void, never, Database.Service>;\n\n /**\n * Submit a turn: a plain user prompt, or pre-built content blocks (e.g. synthetic context + prompt).\n */\n submitPrompt: (prompt: string | ContentBlock.Any[], options?: SubmitPromptOptions) => Effect.Effect<void>;\n\n /**\n * True while the agent is working on a turn (running, or waiting on a tool call or alarm); false\n * when it is idle awaiting input, or terminal.\n */\n readonly running: Atom.Atom<boolean>;\n\n /**\n * Wait until agent has completed its work.\n */\n waitForCompletion: () => Effect.Effect<void>;\n\n /**\n * Terminates the agent process and clears its durable storage.\n */\n terminate: () => Effect.Effect<void>;\n\n /**\n * Subscribe to ephemeral trace events (e.g., streaming partial messages).\n * Replays buffered events, then streams new ones until the process ends.\n *\n * When forking a collector from a short-lived parent (e.g. `useEffect` +\n * `runPromise(Effect.forEach(subscribe))`), use {@link Effect.forkDetach} so the\n * stream survives after the parent scope closes; interrupt it on dispose.\n */\n subscribeEphemeral: (options?: Process.SubscribeEphemeralOptions) => Stream.Stream<Trace.Message>;\n}\n\nexport const getSession = (...args: Parameters<Context.Service.Shape<typeof AgentService>['getSession']>) =>\n AgentService.use((service) => service.getSession(...args));\n\nexport const hydrate = (...args: Parameters<Context.Service.Shape<typeof AgentService>['hydrate']>) =>\n AgentService.use((service) => service.hydrate(...args));\n\nexport interface GetSessionOptions {\n // The model is read off the chat (see `Conversation.session`), but the catalog's shared model ids are\n // served by several providers, so the provider must still accompany it into the agent process —\n // the id alone does not identify a resolver.\n readonly provider?: DXN.DXN;\n readonly systemPrompt?: string;\n /**\n * Where the agent runs. `local` executes it in this runtime; `edge` spawns it on the remote host\n * reached through `RemoteProcessManager.Service`, so the conversation continues with the client\n * closed. Read at spawn only, like `model` — moving a live conversation between runtimes would\n * mean handing one process's durable state to another.\n *\n * @default 'local'\n */\n readonly location?: AgentLocation;\n}\n\nexport type AgentLocation = 'local' | 'edge';\n"],"mappings":";;;;;;;;;AAkDA,IAAa,eAAb,cAAkC,QAAQ,QAA+B,CAAC,CAAC,sCAAsC,CAAC,CAAC,CAAC;;AAGpH,IAAa,MAAM,aAAa;AAyEhC,IAAa,cAAc,GAAG,SAC5B,aAAa,KAAK,YAAY,QAAQ,WAAW,GAAG,IAAI,CAAC;AAE3D,IAAa,WAAW,GAAG,SACzB,aAAa,KAAK,YAAY,QAAQ,QAAQ,GAAG,IAAI,CAAC"}
|
package/dist/lib/Operation.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import * as Effect from "effect/Effect";
|
|
|
6
6
|
import * as Option from "effect/Option";
|
|
7
7
|
import * as Cause from "effect/Cause";
|
|
8
8
|
import * as Context from "effect/Context";
|
|
9
|
+
import * as Function from "effect/Function";
|
|
9
10
|
import * as Layer from "effect/Layer";
|
|
10
11
|
import * as Pipeable from "effect/Pipeable";
|
|
11
12
|
import * as RpcGroup from "effect/rpc/RpcGroup";
|
|
@@ -15,6 +16,7 @@ import { log } from "@dxos/log";
|
|
|
15
16
|
//#region src/Operation.ts
|
|
16
17
|
var Operation_exports = /* @__PURE__ */ __exportAll({
|
|
17
18
|
DefinitionTypeId: () => DefinitionTypeId,
|
|
19
|
+
DurableDefinitionTypeId: () => DurableDefinitionTypeId,
|
|
18
20
|
DurableTypeId: () => DurableTypeId,
|
|
19
21
|
FunctionError: () => FunctionError,
|
|
20
22
|
FunctionNotFoundError: () => FunctionNotFoundError,
|
|
@@ -41,6 +43,7 @@ var Operation_exports = /* @__PURE__ */ __exportAll({
|
|
|
41
43
|
idempotent: () => idempotent,
|
|
42
44
|
invoke: () => invoke,
|
|
43
45
|
isDurable: () => isDurable,
|
|
46
|
+
isDurableDefinition: () => isDurableDefinition,
|
|
44
47
|
isIdempotent: () => isIdempotent,
|
|
45
48
|
isLazyHandler: () => isLazyHandler,
|
|
46
49
|
isOperationDefinition: () => isOperationDefinition,
|
|
@@ -62,6 +65,7 @@ var Operation_exports = /* @__PURE__ */ __exportAll({
|
|
|
62
65
|
toolNameFromKey: () => toolNameFromKey,
|
|
63
66
|
tryToolNameFromKey: () => tryToolNameFromKey,
|
|
64
67
|
visible: () => visible,
|
|
68
|
+
withDurableHandler: () => withDurableHandler,
|
|
65
69
|
withHandler: () => withHandler,
|
|
66
70
|
withInvocationOptions: () => withInvocationOptions
|
|
67
71
|
});
|
|
@@ -184,27 +188,50 @@ var withHandler = (opOrHandler, handler) => {
|
|
|
184
188
|
* ```
|
|
185
189
|
*/
|
|
186
190
|
var opaqueHandler = (handler) => handler;
|
|
191
|
+
var DurableDefinitionTypeId = "~@dxos/operation/DurableDefinition";
|
|
187
192
|
var DurableTypeId = "~@dxos/operation/Durable";
|
|
193
|
+
var isDurableDefinition = (value) => typeof value === "object" && value !== null && "~@dxos/operation/DurableDefinition" in value;
|
|
188
194
|
var isDurable = (executable) => typeof executable === "object" && executable !== null && "~@dxos/operation/Durable" in executable;
|
|
189
195
|
/**
|
|
190
|
-
*
|
|
196
|
+
* Declares a durable operation; attach its handler factory with {@link withDurableHandler}.
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```ts
|
|
200
|
+
* const Counter = Operation.makeDurable({ key: 'example.counter', input: Schema.Number, output: Schema.Number, services: [] }).pipe(
|
|
201
|
+
* Operation.withDurableHandler((ctx) =>
|
|
202
|
+
* Effect.succeed({ onInput: (input) => Effect.sync(() => ctx.submitOutput(input + 1)) }),
|
|
203
|
+
* ),
|
|
204
|
+
* );
|
|
205
|
+
* ```
|
|
191
206
|
*/
|
|
192
|
-
var makeDurable = (opts
|
|
207
|
+
var makeDurable = (opts) => {
|
|
193
208
|
assertArgument(/^[a-z0-9]([a-z0-9.\-/]*[a-z0-9])?$/i.test(opts.key), "key", "Invalid key");
|
|
194
209
|
return {
|
|
195
|
-
[
|
|
210
|
+
[DurableDefinitionTypeId]: {},
|
|
196
211
|
...opts,
|
|
197
212
|
rpcs: opts.rpcs ?? RpcGroup.make(),
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
onAlarm: () => Effect.void,
|
|
202
|
-
onChildEvent: () => Effect.void,
|
|
203
|
-
...partial,
|
|
204
|
-
rpcHandlers: sanitizeRpcs(opts.rpcs, partial.rpcHandlers)
|
|
205
|
-
})))
|
|
213
|
+
pipe() {
|
|
214
|
+
return Pipeable.pipeArguments(this, arguments);
|
|
215
|
+
}
|
|
206
216
|
};
|
|
207
217
|
};
|
|
218
|
+
/**
|
|
219
|
+
* Attaches the handler factory to a durable operation definition.
|
|
220
|
+
* Dual API: can be called directly or used in a pipe.
|
|
221
|
+
*/
|
|
222
|
+
var withDurableHandler = Function.dual(2, (def, create) => attachDurableHandler(def, create));
|
|
223
|
+
var attachDurableHandler = (def, create) => ({
|
|
224
|
+
...def,
|
|
225
|
+
[DurableTypeId]: {},
|
|
226
|
+
create: (ctx) => create(ctx).pipe(Effect.map((partial) => ({
|
|
227
|
+
onSpawn: () => Effect.void,
|
|
228
|
+
onInput: () => Effect.void,
|
|
229
|
+
onAlarm: () => Effect.void,
|
|
230
|
+
onChildEvent: () => Effect.void,
|
|
231
|
+
...partial,
|
|
232
|
+
rpcHandlers: sanitizeRpcs(def.rpcs, partial.rpcHandlers)
|
|
233
|
+
})))
|
|
234
|
+
});
|
|
208
235
|
var sanitizeRpcs = (defined, provided) => {
|
|
209
236
|
if (!(defined !== void 0 && defined.requests.size > 0)) return provided ?? Context.empty();
|
|
210
237
|
if (!provided) throw new TypeError("Durable operation declared RPCs but did not provide any handlers");
|
|
@@ -238,7 +265,7 @@ var toolNameFromKey = (key) => {
|
|
|
238
265
|
invariant(TOOL_NAME_REGEXP.test(name), `Invalid tool name: ${name}`, {
|
|
239
266
|
"~LogMeta": "~LogMeta",
|
|
240
267
|
F: __dxlog_file,
|
|
241
|
-
L:
|
|
268
|
+
L: 717,
|
|
242
269
|
S: void 0,
|
|
243
270
|
A: ["TOOL_NAME_REGEXP.test(name)", "`Invalid tool name: ${name}`"]
|
|
244
271
|
});
|
|
@@ -352,7 +379,7 @@ var serializable = (operations) => operations.flatMap((operation) => {
|
|
|
352
379
|
}, {
|
|
353
380
|
"~LogMeta": "~LogMeta",
|
|
354
381
|
F: __dxlog_file,
|
|
355
|
-
L:
|
|
382
|
+
L: 868,
|
|
356
383
|
S: void 0
|
|
357
384
|
});
|
|
358
385
|
return [];
|
|
@@ -620,6 +647,6 @@ var migrations = [Migration.define({
|
|
|
620
647
|
})
|
|
621
648
|
})];
|
|
622
649
|
//#endregion
|
|
623
|
-
export { DefinitionTypeId, DurableTypeId, FunctionError, FunctionNotFoundError, IdempotentAnnotation, InvalidOperationInputError, InvalidOperationOutputError, InvokerNotInitializedError, Label, LazyHandlerTypeId, MutationAnnotation, NoHandlerError, NotifyOptions, NotifyOptionsAnnotation, PersistentOperation, PersistentOperation_v0_1_0, Service, VisibleAnnotation, annotate, deserialize, findToolNameCollisions, getKey, getMutation, getVersion, idempotent, invoke, isDurable, isIdempotent, isLazyHandler, isOperationDefinition, isOperationWithHandler, isVisible, lazyHandler, make, makeDurable, migrations, mutation, opaqueHandler, prepare, runAgain, schedule, serializable, serialize, setFrom, Operation_exports as t, toolName, toolNameFromKey, tryToolNameFromKey, visible, withHandler, withInvocationOptions };
|
|
650
|
+
export { DefinitionTypeId, DurableDefinitionTypeId, DurableTypeId, FunctionError, FunctionNotFoundError, IdempotentAnnotation, InvalidOperationInputError, InvalidOperationOutputError, InvokerNotInitializedError, Label, LazyHandlerTypeId, MutationAnnotation, NoHandlerError, NotifyOptions, NotifyOptionsAnnotation, PersistentOperation, PersistentOperation_v0_1_0, Service, VisibleAnnotation, annotate, deserialize, findToolNameCollisions, getKey, getMutation, getVersion, idempotent, invoke, isDurable, isDurableDefinition, isIdempotent, isLazyHandler, isOperationDefinition, isOperationWithHandler, isVisible, lazyHandler, make, makeDurable, migrations, mutation, opaqueHandler, prepare, runAgain, schedule, serializable, serialize, setFrom, Operation_exports as t, toolName, toolNameFromKey, tryToolNameFromKey, visible, withDurableHandler, withHandler, withInvocationOptions };
|
|
624
651
|
|
|
625
652
|
//# sourceMappingURL=Operation.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Operation.mjs","names":[],"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 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 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<\n _Input,\n _Output,\n _Requirements = never,\n _Rpcs extends Rpc.Any = never,\n> extends Durable.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 /**\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 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\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 = 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 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 * Creates a durable operation from its declaration and a factory for its {@link DurableHandler}.\n */\nexport const makeDurable = <const Opts extends Types.NoExcessProperties<DurableProps, Opts>>(\n opts: Opts,\n create: (\n ctx: DurableContext<Schema.Schema.Type<Opts['input']>, Schema.Schema.Type<Opts['output']>>,\n ) => Effect.Effect<\n Partial<\n DurableHandler<\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 >,\n never,\n Context.Service.Identifier<NonNullable<Opts['services']>[number]> | BaseServices | Scope.Scope\n >,\n): Durable<\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 [DurableTypeId]: {} as any,\n ...opts,\n rpcs: opts.rpcs ?? RpcGroup.make(),\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(opts.rpcs, partial.rpcHandlers),\n })),\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 `makeDurable`'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): PersistentOperation => {\n return Obj.make(PersistentOperation, {\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};\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 * Optional process-runtime tracing metadata (consumed by `@dxos/functions-runtime` when wired).\n */\n tracing?: unknown;\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,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,OAAO;EACL,GAAG;EACH;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,IAAa,iBACX,YACoD;AAoHtD,IAAa,gBAAgB;AAyD7B,IAAa,aAAa,eACxB,OAAO,eAAe,YAAY,eAA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I,IAAI,IAAI,OAAO,CAAC;CAC7C,aAAa,OAAQ,SAAS,WAAW,UAAU;CACnD,cAAc,OAAQ,SAAS,WAAW,UAAU;CACpD,UAAU,OAAQ,SAAS,OAAQ,MAAM,OAAQ,MAAM,CAAC;CACxD,SAAS,OAAQ,SAAS,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
|
+
{"version":3,"file":"Operation.mjs","names":[],"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): PersistentOperation => {\n return Obj.make(PersistentOperation, {\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};\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,aACA,YACqB;CAErB,IAAI,YAAY,KAAA,GAAW;EACzB,MAAM,YAAY;EAMlB,SAAS,QAAa;GACpB,GAAG;GACH,SAAS;EACX;CACF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Q,cAAc,IAAI,OAAO;GAAE,GAAG;GAAS,GAAG;EAAkB,CAAC;EACvE,YAAY,IAA8B,OAAY,sBACpD,QAAQ,SAAS,IAAI,OAAO;GAAE,GAAG;GAAS,GAAG;EAAkB,CAAC;CACpE,CAAC;AACH,CAAC,CACH;;;;;AAUF,IAAa,6BAAb,cAAgD,KAAK,WACnD,IAAI,KAAK,0BAA0B,OAAO,CAC5C,CAAC,CACC,OAAQ,OAAO;CACb,KAAK,OAAQ,SAAS,OAAQ,MAAM;CACpC,MAAM,OAAQ;CACd,SAAS,OAAQ;CACjB,aAAa,OAAQ,SAAS,OAAQ,MAAM;CAC5C,SAAS,OAAQ,SAAS,OAAQ,MAAM;CACxC,QAAQ,OAAQ,SAAS,IAAI,IAAI,IAAI,OAAO,CAAC;CAC7C,aAAa,OAAQ,SAAS,WAAW,UAAU;CACnD,cAAc,OAAQ,SAAS,WAAW,UAAU;CACpD,UAAU,OAAQ,SAAS,OAAQ,MAAM,OAAQ,MAAM,CAAC;CACxD,SAAS,OAAQ,SAAS,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"}
|
|
@@ -2,9 +2,9 @@ import { t as __exportAll } from "./chunk-rolldown-runtime.mjs";
|
|
|
2
2
|
import { NoHandlerError } from "./errors.mjs";
|
|
3
3
|
import * as Effect from "effect/Effect";
|
|
4
4
|
import * as Context from "effect/Context";
|
|
5
|
+
import { pipe } from "effect/Function";
|
|
5
6
|
import * as Layer from "effect/Layer";
|
|
6
7
|
import { assertArgument } from "@dxos/invariant";
|
|
7
|
-
import { pipe } from "effect/Function";
|
|
8
8
|
import * as EffectEx from "@dxos/effect/EffectEx";
|
|
9
9
|
import { DXN } from "@dxos/keys";
|
|
10
10
|
//#region src/OperationHandlerSet.ts
|
package/dist/lib/Process.mjs
CHANGED
|
@@ -6,8 +6,11 @@ import * as Schema from "effect/Schema";
|
|
|
6
6
|
import { Annotation } from "@dxos/echo";
|
|
7
7
|
import * as Effect from "effect/Effect";
|
|
8
8
|
import * as Option from "effect/Option";
|
|
9
|
+
import * as Cause from "effect/Cause";
|
|
9
10
|
import * as Context from "effect/Context";
|
|
10
11
|
import { URI as URI$1 } from "@dxos/keys";
|
|
12
|
+
import * as Exit from "effect/Exit";
|
|
13
|
+
import * as Stream from "effect/Stream";
|
|
11
14
|
//#region src/Process.ts
|
|
12
15
|
var Process_exports = /* @__PURE__ */ __exportAll({
|
|
13
16
|
EnvironmentService: () => EnvironmentService,
|
|
@@ -22,13 +25,15 @@ var Process_exports = /* @__PURE__ */ __exportAll({
|
|
|
22
25
|
SpawnedEvent: () => SpawnedEvent,
|
|
23
26
|
State: () => State,
|
|
24
27
|
TargetAnnotation: () => TargetAnnotation,
|
|
28
|
+
awaitOutput: () => awaitOutput,
|
|
25
29
|
currentEnvironment: () => currentEnvironment,
|
|
26
30
|
isExited: () => isExited,
|
|
27
31
|
isHarnessHost: () => isHarnessHost,
|
|
28
32
|
isTerminal: () => isTerminal,
|
|
29
33
|
listFromTree: () => listFromTree,
|
|
30
34
|
matchesFilter: () => matchesFilter,
|
|
31
|
-
prettyProcessTree: () => prettyProcessTree
|
|
35
|
+
prettyProcessTree: () => prettyProcessTree,
|
|
36
|
+
spawn: () => spawn
|
|
32
37
|
});
|
|
33
38
|
/** Opaque process id (arbitrary string). */
|
|
34
39
|
var ID = Schema.String.pipe(Schema.brand("ProcessId"));
|
|
@@ -101,8 +106,35 @@ var matchesFilter = (info, filter = {}) => {
|
|
|
101
106
|
};
|
|
102
107
|
/** {@link Manager.list} over a tree read, so a manager implements it by supplying only that read. */
|
|
103
108
|
var listFromTree = (processTree) => (filter) => Effect.map(processTree, (tree) => tree.filter((info) => matchesFilter(info, filter)));
|
|
109
|
+
/**
|
|
110
|
+
* The first output of a single-output process (e.g. one running an operation), failing with the
|
|
111
|
+
* process's own cause when it fails without one.
|
|
112
|
+
*/
|
|
113
|
+
var awaitOutput = (handle) => handle.subscribeOutputs().pipe(Stream.runHead, Effect.flatMap(Option.match({
|
|
114
|
+
onSome: Effect.succeed,
|
|
115
|
+
onNone: () => {
|
|
116
|
+
switch (handle.status.state) {
|
|
117
|
+
case "FAILED": return Effect.failCause(handle.status.exit.pipe(Option.flatMap(Exit.getCause), Option.getOrElse(() => Cause.die("Operation failed with unknown error"))));
|
|
118
|
+
case "TERMINATED": return Effect.die("Operation was terminated");
|
|
119
|
+
case "SUCCEEDED": return Effect.die("Process produced no output");
|
|
120
|
+
default: return Effect.interrupt;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
})));
|
|
104
124
|
var ManagerService = class extends Context.Service()("@dxos/compute/Process.ManagerService") {};
|
|
105
125
|
/**
|
|
126
|
+
* Spawns `durable` through the ambient {@link ManagerService} and submits `input`; read its result with
|
|
127
|
+
* {@link awaitOutput}.
|
|
128
|
+
*/
|
|
129
|
+
var spawn = (durable, input, options) => Effect.gen(function* () {
|
|
130
|
+
const handle = yield* (yield* ManagerService).spawn(durable, {
|
|
131
|
+
...durable.name !== void 0 ? { name: durable.name } : {},
|
|
132
|
+
...options
|
|
133
|
+
});
|
|
134
|
+
yield* handle.submitInput(input);
|
|
135
|
+
return handle;
|
|
136
|
+
});
|
|
137
|
+
/**
|
|
106
138
|
* New process is spawned.
|
|
107
139
|
*/
|
|
108
140
|
var SpawnedEvent = EventType("process.spawned", {
|
|
@@ -167,6 +199,6 @@ var prettyProcessTree = (tree) => {
|
|
|
167
199
|
return lines.join("\n");
|
|
168
200
|
};
|
|
169
201
|
//#endregion
|
|
170
|
-
export { EnvironmentService, ExitedEvent, HarnessHostAnnotation, ID, ManagerService, NotifyAnnotation, RUN_AGAIN_ERROR_CODE, RUN_AGAIN_MESSAGE, RunAgainError, SpawnedEvent, State, TargetAnnotation, currentEnvironment, isExited, isHarnessHost, isTerminal, listFromTree, matchesFilter, prettyProcessTree, Process_exports as t };
|
|
202
|
+
export { EnvironmentService, ExitedEvent, HarnessHostAnnotation, ID, ManagerService, NotifyAnnotation, RUN_AGAIN_ERROR_CODE, RUN_AGAIN_MESSAGE, RunAgainError, SpawnedEvent, State, TargetAnnotation, awaitOutput, currentEnvironment, isExited, isHarnessHost, isTerminal, listFromTree, matchesFilter, prettyProcessTree, spawn, Process_exports as t };
|
|
171
203
|
|
|
172
204
|
//# sourceMappingURL=Process.mjs.map
|