@workglow/task-graph 0.3.12 → 0.3.13
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/browser.js +3368 -3321
- package/dist/browser.js.map +26 -24
- package/dist/bun.js +3368 -3321
- package/dist/bun.js.map +26 -24
- package/dist/cache/CacheJanitor.d.ts +2 -2
- package/dist/cache/RunPrivateCacheRepo.d.ts +6 -5
- package/dist/cache/RunPrivateCacheRepo.d.ts.map +1 -1
- package/dist/common.d.ts +9 -6
- package/dist/common.d.ts.map +1 -1
- package/dist/node.js +3368 -3321
- package/dist/node.js.map +26 -24
- package/dist/storage/ITaskOutputStorage.d.ts +35 -0
- package/dist/storage/ITaskOutputStorage.d.ts.map +1 -0
- package/dist/storage/TabularTaskOutputStorage.d.ts +29 -0
- package/dist/storage/TabularTaskOutputStorage.d.ts.map +1 -0
- package/dist/storage/TaskOutputStorageSchema.d.ts +31 -0
- package/dist/storage/TaskOutputStorageSchema.d.ts.map +1 -0
- package/dist/storage/TaskOutputTabularRepository.d.ts +10 -90
- package/dist/storage/TaskOutputTabularRepository.d.ts.map +1 -1
- package/dist/task/CacheCoordinator.d.ts +8 -2
- package/dist/task/CacheCoordinator.d.ts.map +1 -1
- package/dist/task/GraphAsTask.d.ts.map +1 -1
- package/dist/task/Task.d.ts +1 -1
- package/dist/task/index.d.ts +6 -6
- package/dist/task/index.d.ts.map +1 -1
- package/dist/task-graph/Conversions.d.ts +10 -0
- package/dist/task-graph/Conversions.d.ts.map +1 -1
- package/dist/task-graph/Dataflow.d.ts +1 -1
- package/dist/task-graph/Dataflow.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/EXECUTION_MODEL.md +4 -4
package/dist/node.js.map
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/task-graph/Dataflow.ts", "../src/task/TaskError.ts", "../src/task/TaskTypes.ts", "../src/task-graph/TransformRegistry.ts", "../src/task/TaskEntitlements.ts", "../src/task-graph/GraphEntitlementUtils.ts", "../src/task/InputResolver.ts", "../src/task-graph/GraphFormatScanner.ts", "../src/task-graph/GraphSchemaUtils.ts", "../src/task-graph/
|
|
3
|
+
"sources": ["../src/task-graph/Dataflow.ts", "../src/task/TaskError.ts", "../src/task/TaskTypes.ts", "../src/task-graph/TransformRegistry.ts", "../src/task/TaskEntitlements.ts", "../src/task-graph/GraphEntitlementUtils.ts", "../src/task/InputResolver.ts", "../src/task-graph/GraphFormatScanner.ts", "../src/task-graph/GraphSchemaUtils.ts", "../src/task-graph/RunContext.ts", "../src/task-graph/RunScheduler.ts", "../src/task/ConditionalTask.ts", "../src/task/ConditionUtils.ts", "../src/task/Task.ts", "../src/cache/CachePolicy.ts", "../src/task-graph/TaskGraph.ts", "../src/task-graph/Conversions.ts", "../src/task-graph/TaskGraphEvents.ts", "../src/task-graph/TaskGraphRunner.ts", "../src/cache/CacheJanitor.ts", "../src/cache/CacheRegistry.ts", "../src/storage/TaskOutputRepository.ts", "../src/cache/RunPrivateCacheRepo.ts", "../src/task/EntitlementEnforcer.ts", "../src/task/EntitlementPolicy.ts", "../src/task/EntitlementResolver.ts", "../src/task/StreamTypes.ts", "../src/task-graph/EdgeMaterializer.ts", "../src/task-graph/StreamPump.ts", "../src/task-graph/TaskGraphScheduler.ts", "../src/task/TaskRunner.ts", "../src/task/CacheCoordinator.ts", "../src/task/StreamProcessor.ts", "../src/task/TaskRunContext.ts", "../src/task-graph/Workflow.ts", "../src/task/GraphAsTask.ts", "../src/task/GraphAsTaskRunner.ts", "../src/task-graph/autoConnect.ts", "../src/task-graph/LoopBuilderContext.ts", "../src/task-graph/WorkflowBuilder.ts", "../src/task-graph/ConditionalBuilder.ts", "../src/task-graph/WorkflowPipe.ts", "../src/task-graph/WorkflowCacheAdapter.ts", "../src/task-graph/WorkflowEventBridge.ts", "../src/task-graph/WorkflowFactories.ts", "../src/task-graph/WorkflowRunContext.ts", "../src/task-graph/WorkflowTask.ts", "../src/task-graph/GraphToWorkflowCode.ts", "../src/task-graph/transforms/coalesce.ts", "../src/task-graph/transforms/date-conversions.ts", "../src/task-graph/transforms/index-access.ts", "../src/task-graph/transforms/pick.ts", "../src/task-graph/transforms/scalar-conversions.ts", "../src/task-graph/transforms/string-casts.ts", "../src/task-graph/transforms/index.ts", "../src/task/EntitlementProfile.ts", "../src/task/EntitlementProfiles.ts", "../src/task/InputCompactor.ts", "../src/task/IteratorTaskRunner.ts", "../src/task/IteratorTask.ts", "../src/task/WhileTaskRunner.ts", "../src/task/WhileTask.ts", "../src/task/iterationSchema.ts", "../src/task/JobQueueFactory.ts", "../src/task/MapTask.ts", "../src/task/ReduceTask.ts", "../src/task/TaskRegistry.ts", "../src/task/TaskJSON.ts", "../src/task/TaskQueueRegistry.ts", "../src/task/FallbackTaskRunner.ts", "../src/task/FallbackTask.ts", "../src/task/index.ts", "../src/storage/TabularTaskOutputStorage.ts", "../src/storage/TaskGraphRepository.ts", "../src/storage/TaskGraphTabularRepository.ts", "../src/storage/TaskOutputStorageSchema.ts", "../src/storage/TaskOutputTabularRepository.ts", "../src/storage/PortCodecRegistry.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { EventEmitter } from \"@workglow/util\";\nimport { areSemanticallyCompatible } from \"@workglow/util/schema\";\nimport type { StreamEvent } from \"../task/StreamTypes\";\nimport { Task } from \"../task/Task\";\nimport { TaskError } from \"../task/TaskError\";\nimport { DataflowJson } from \"../task/TaskJSON\";\nimport { TaskIdType, TaskOutput, TaskStatus } from \"../task/TaskTypes\";\nimport {\n DataflowEventListener,\n DataflowEventListeners,\n DataflowEventParameters,\n DataflowEvents,\n} from \"./DataflowEvents\";\nimport { TaskGraph } from \"./TaskGraph\";\nimport { TRANSFORM_DEFS, TransformRegistry } from \"./TransformRegistry\";\nimport type { ITransformStep } from \"./TransformTypes\";\n\nexport type DataflowIdType = `${string}[${string}] ==> ${string}[${string}]`;\n\nexport const DATAFLOW_ALL_PORTS = \"*\";\nexport const DATAFLOW_ERROR_PORT = \"[error]\";\n\n/**\n * Represents a data flow between two tasks, indicating how one task's output is used as input for another task\n */\nexport class Dataflow {\n constructor(\n public sourceTaskId: TaskIdType,\n public sourceTaskPortId: string,\n public targetTaskId: TaskIdType,\n public targetTaskPortId: string\n ) {}\n public static createId(\n sourceTaskId: TaskIdType,\n sourceTaskPortId: string,\n targetTaskId: TaskIdType,\n targetTaskPortId: string\n ): DataflowIdType {\n return `${sourceTaskId}[${sourceTaskPortId}] ==> ${targetTaskId}[${targetTaskPortId}]`;\n }\n get id(): DataflowIdType {\n return Dataflow.createId(\n this.sourceTaskId,\n this.sourceTaskPortId,\n this.targetTaskId,\n this.targetTaskPortId\n );\n }\n public value: any = undefined;\n public status: TaskStatus = TaskStatus.PENDING;\n public error: TaskError | undefined;\n\n /**\n * Active stream for this dataflow edge.\n * Set when a streaming upstream task begins producing chunks.\n * Multiple downstream consumers can each get an independent reader via tee().\n */\n public stream: ReadableStream<StreamEvent> | undefined = undefined;\n\n /**\n * Most recent per-port snapshot data observed while `stream` was active.\n * Populated by the runner's stream-tap on `snapshot` events; cleared on\n * setStream / reset, or transferred to `value` on setPortData. Distinct\n * from `value` (final materialized output) — `latestSnapshot` is the\n * live mid-stream peek.\n */\n public latestSnapshot: unknown = undefined;\n\n /**\n * Returns the current effective value of this edge, regardless of\n * streaming state:\n * 1. `value` — set by setPortData / awaitStreamValue when stream finishes.\n * 2. `latestSnapshot` — set by the runner's snapshot tap during streaming.\n * 3. `undefined` — no data yet.\n *\n * Use this in any read path that wants \"current edge value, regardless of\n * streaming state.\" `getPortData()` retains its strict semantics\n * (only `value`) for callers that explicitly need that.\n */\n public getCurrentValue(): unknown {\n if (this.value !== undefined) return this.value;\n return this.latestSnapshot;\n }\n\n public setStream(stream: ReadableStream<StreamEvent>): void {\n // New stream invalidates any prior peek.\n this.latestSnapshot = undefined;\n this.stream = stream;\n }\n\n public getStream(): ReadableStream<StreamEvent> | undefined {\n return this.stream;\n }\n\n /**\n * Consumes the active stream to completion and materializes the value.\n *\n * Accumulation of text-delta chunks is the responsibility of the **source\n * task** (via StreamProcessor when shouldAccumulate=true).\n * When accumulation is needed the source task emits an enriched finish event\n * that carries the fully-assembled port data. All downstream edges share that\n * enriched event through tee'd ReadableStreams, so no edge needs to\n * re-accumulate independently.\n *\n * This method therefore only reads snapshot and finish events:\n * - **snapshot**: used for replace-mode tasks that emit incremental snapshots.\n * - **finish**: the primary materialization path; carries complete data when\n * the source task accumulated, or provider-level data otherwise.\n * - text-delta / object-delta: ignored here (handled by source task).\n *\n * After consumption the stream reference is cleared. Calling this method on\n * a dataflow that has no stream is a no-op.\n */\n public async awaitStreamValue(): Promise<void> {\n if (!this.stream) return;\n\n const reader = this.stream.getReader();\n let lastSnapshotData: any = undefined;\n let finishData: any = undefined;\n let streamError: Error | undefined;\n\n try {\n while (true) {\n const { done, value: event } = await reader.read();\n if (done) break;\n\n switch (event.type) {\n case \"snapshot\":\n lastSnapshotData = event.data;\n break;\n case \"finish\":\n finishData = event.data;\n break;\n case \"error\":\n streamError = event.error;\n break;\n // text-delta, object-delta: source task handles accumulation\n }\n }\n } finally {\n reader.releaseLock();\n this.stream = undefined;\n }\n\n if (streamError) {\n this.error = streamError as TaskError;\n this.setStatus(TaskStatus.FAILED);\n throw streamError;\n }\n\n // Priority: snapshot > finish.\n // The source task enriches the finish event with accumulated text when\n // shouldAccumulate=true, so finishData carries complete port data.\n if (lastSnapshotData !== undefined) {\n this.setPortData(lastSnapshotData);\n } else if (finishData !== undefined) {\n this.setPortData(finishData);\n }\n }\n\n public reset() {\n this.latestSnapshot = undefined;\n this.status = TaskStatus.PENDING;\n this.error = undefined;\n this.value = undefined;\n this.stream = undefined;\n this._compatibilityCache = undefined;\n this.emit(\"reset\");\n this.emit(\"status\", this.status);\n }\n\n public setStatus(status: TaskStatus) {\n if (status === this.status) return;\n this.status = status;\n switch (status) {\n case TaskStatus.PROCESSING:\n this.emit(\"start\");\n break;\n case TaskStatus.STREAMING:\n this.emit(\"streaming\");\n break;\n case TaskStatus.COMPLETED:\n this.emit(\"complete\");\n break;\n case TaskStatus.ABORTING:\n this.emit(\"abort\");\n break;\n case TaskStatus.PENDING:\n this.emit(\"reset\");\n break;\n case TaskStatus.FAILED:\n this.emit(\"error\", this.error!);\n break;\n case TaskStatus.DISABLED:\n this.emit(\"disabled\");\n break;\n }\n this.emit(\"status\", this.status);\n }\n\n setPortData(entireDataBlock: any) {\n if (this.sourceTaskPortId === DATAFLOW_ALL_PORTS) {\n this.value = entireDataBlock;\n } else if (this.sourceTaskPortId === DATAFLOW_ERROR_PORT) {\n this.error = entireDataBlock;\n } else {\n this.value = entireDataBlock[this.sourceTaskPortId];\n }\n // The materialised value supersedes the mid-stream peek; clear the slot.\n this.latestSnapshot = undefined;\n }\n\n getPortData(): TaskOutput {\n let result: TaskOutput;\n if (this.targetTaskPortId === DATAFLOW_ALL_PORTS) {\n result = this.value;\n } else if (this.targetTaskPortId === DATAFLOW_ERROR_PORT) {\n result = { [DATAFLOW_ERROR_PORT]: this.error };\n } else {\n result = { [this.targetTaskPortId]: this.value };\n }\n return result;\n }\n\n toJSON(): DataflowJson {\n const base: DataflowJson = {\n sourceTaskId: this.sourceTaskId,\n sourceTaskPortId: this.sourceTaskPortId,\n targetTaskId: this.targetTaskId,\n targetTaskPortId: this.targetTaskPortId,\n };\n if (this._transforms.length > 0) {\n base.transforms = this._transforms.map((s) => ({ id: s.id, params: s.params }));\n }\n return base;\n }\n\n /**\n * Cached result of the last semantic compatibility check.\n * Invalidated by calling {@link invalidateCompatibilityCache}.\n */\n protected _compatibilityCache?: \"static\" | \"runtime\" | \"incompatible\";\n\n /**\n * Transform steps applied to data flowing through this dataflow.\n */\n private _transforms: Array<ITransformStep> = [];\n\n getTransforms(): ReadonlyArray<ITransformStep> {\n return this._transforms;\n }\n\n /**\n * Replaces the transform chain with the given steps and invalidates the compatibility cache.\n * Accepts either strict {@link ITransformStep} or steps whose `params` is omitted;\n * omitted `params` is normalised to `undefined`.\n */\n setTransforms(\n steps: ReadonlyArray<{ readonly id: string; readonly params?: Record<string, unknown> }>\n ): void {\n this._transforms = steps.map((s) => ({ id: s.id, params: s.params }));\n this.invalidateCompatibilityCache();\n }\n\n /**\n * Appends a single transform step to the chain and invalidates the compatibility cache.\n * Accepts either strict {@link ITransformStep} or a step whose `params` is omitted;\n * omitted `params` is normalised to `undefined`.\n */\n addTransform(step: { readonly id: string; readonly params?: Record<string, unknown> }): void {\n this._transforms.push({ id: step.id, params: step.params });\n this.invalidateCompatibilityCache();\n }\n\n removeTransform(index: number): void {\n this._transforms.splice(index, 1);\n this.invalidateCompatibilityCache();\n }\n\n /**\n * Fold the transform chain over `this.value`. On any throw, sets\n * `this.error` and TaskStatus.FAILED, then re-throws so the caller\n * (typically TaskGraphRunner) fails the run. Without the re-throw the\n * runner's status-push step would overwrite the FAILED edge state with\n * the source task's COMPLETED status, silently delivering corrupt data.\n */\n async applyTransforms(registry: ServiceRegistry): Promise<void> {\n if (this._transforms.length === 0) return;\n const defs = registry.get(TRANSFORM_DEFS);\n let cur: unknown = this.value;\n try {\n for (const step of this._transforms) {\n const def = defs.get(step.id);\n if (!def) {\n throw new Error(`Unknown transform: ${step.id}`);\n }\n cur = await def.apply(cur, step.params ?? {});\n }\n this.value = cur;\n } catch (e) {\n const error =\n e instanceof TaskError ? e : new TaskError(e instanceof Error ? e.message : String(e));\n if (!(e instanceof TaskError) && e instanceof Error && e.stack) {\n error.stack = e.stack;\n }\n this.error = error;\n this.setStatus(TaskStatus.FAILED);\n throw e;\n }\n }\n\n /**\n * Invalidates the cached semantic compatibility result so the next call\n * to {@link semanticallyCompatible} recomputes it. Call this when\n * either endpoint's schema changes (e.g., in response to a schemaChange event).\n */\n public invalidateCompatibilityCache(): void {\n this._compatibilityCache = undefined;\n }\n\n semanticallyCompatible(\n graph: TaskGraph,\n dataflow: Dataflow,\n registry?: ServiceRegistry\n ): \"static\" | \"runtime\" | \"incompatible\" {\n const sourceTask = graph.getTask(dataflow.sourceTaskId)!;\n const targetTask = graph.getTask(dataflow.targetTaskId)!;\n\n // Only use the cache when both endpoint tasks have stable (non-dynamic) schemas.\n // Tasks with dynamic schemas may emit `schemaChange` events, which would make\n // a cached result stale. Checking the static `hasDynamicSchemas` flag (defined\n // on Task with a default of `false`) is sufficient because tasks with stable\n // schemas never emit `schemaChange`. Unknown constructors default to no caching.\n const shouldCache =\n !((sourceTask.constructor as typeof Task).hasDynamicSchemas ?? true) &&\n !((targetTask.constructor as typeof Task).hasDynamicSchemas ?? true);\n\n if (shouldCache && this._compatibilityCache !== undefined) {\n return this._compatibilityCache;\n }\n\n const targetSchema = targetTask.inputSchema();\n const sourceSchema = sourceTask.outputSchema();\n\n if (typeof targetSchema === \"boolean\") {\n if (targetSchema === false) {\n return \"incompatible\";\n }\n return \"static\";\n }\n if (typeof sourceSchema === \"boolean\") {\n if (sourceSchema === false) {\n return \"incompatible\";\n }\n return \"runtime\";\n }\n\n let targetSchemaProperty =\n DATAFLOW_ALL_PORTS === dataflow.targetTaskPortId\n ? true // Accepts any schema (equivalent to Type.Any())\n : (targetSchema.properties as any)?.[dataflow.targetTaskPortId];\n // If the specific property doesn't exist but additionalProperties is true,\n // treat it as accepting any schema\n if (targetSchemaProperty === undefined && targetSchema.additionalProperties === true) {\n targetSchemaProperty = true;\n }\n let sourceSchemaProperty =\n DATAFLOW_ALL_PORTS === dataflow.sourceTaskPortId\n ? true // Accepts any schema (equivalent to Type.Any())\n : (sourceSchema.properties as any)?.[dataflow.sourceTaskPortId];\n // If the specific property doesn't exist but additionalProperties is true,\n // treat it as outputting any schema\n if (sourceSchemaProperty === undefined && sourceSchema.additionalProperties === true) {\n sourceSchemaProperty = true;\n }\n\n // Compose source schema through the transform chain before comparing.\n // Resolves transform defs from the same registry used by applyTransforms so\n // that custom TRANSFORM_DEFS overrides are reflected in both places.\n // When the source schema is `true` (accepts any — e.g. a boundary task\n // with `additionalProperties: true`), start the chain from `{}` so\n // transforms can still narrow the effective schema. Without this a chain\n // like `pick → unixToIsoDate` from an InputTask would short-circuit to\n // \"static\" against any target regardless of the transforms' output type.\n let effectiveSourceSchema = sourceSchemaProperty;\n if (this._transforms.length > 0) {\n const defs = registry ? registry.get(TRANSFORM_DEFS) : TransformRegistry.all;\n try {\n let cur: any = effectiveSourceSchema === true ? {} : effectiveSourceSchema;\n for (const step of this._transforms) {\n const def = defs.get(step.id);\n if (!def) {\n // Do not cache missing transform definitions because the registry\n // supports runtime registration and a later call may become compatible.\n return \"incompatible\";\n }\n cur = def.inferOutputSchema(cur, step.params ?? {});\n }\n effectiveSourceSchema = cur;\n } catch {\n if (shouldCache) this._compatibilityCache = \"incompatible\";\n return \"incompatible\";\n }\n }\n\n const result = areSemanticallyCompatible(effectiveSourceSchema, targetSchemaProperty);\n if (shouldCache) {\n this._compatibilityCache = result;\n }\n return result;\n }\n\n // ========================================================================\n // Event handling methods\n // ========================================================================\n\n public get events(): EventEmitter<DataflowEventListeners> {\n if (!this._events) {\n this._events = new EventEmitter<DataflowEventListeners>();\n }\n return this._events;\n }\n protected _events: EventEmitter<DataflowEventListeners> | undefined;\n\n public subscribe<Event extends DataflowEvents>(\n name: Event,\n fn: DataflowEventListener<Event>\n ): () => void {\n return this.events.subscribe(name, fn);\n }\n\n public on<Event extends DataflowEvents>(name: Event, fn: DataflowEventListener<Event>): void {\n this.events.on(name, fn);\n }\n\n public off<Event extends DataflowEvents>(name: Event, fn: DataflowEventListener<Event>): void {\n this.events.off(name, fn);\n }\n\n public once<Event extends DataflowEvents>(name: Event, fn: DataflowEventListener<Event>): void {\n this.events.once(name, fn);\n }\n\n /**\n * Returns a promise that resolves when the specified event is emitted\n */\n public waitOn<Event extends DataflowEvents>(\n name: Event\n ): Promise<DataflowEventParameters<Event>> {\n return this.events.waitOn(name) as Promise<DataflowEventParameters<Event>>;\n }\n\n public emit<Event extends DataflowEvents>(\n name: Event,\n ...args: DataflowEventParameters<Event>\n ): void {\n this._events?.emit(name, ...args);\n }\n}\n\n/**\n * Represents a data flow between two tasks, indicating how one task's output is used as input for another task\n *\n * This is a helper class that parses a data flow id string into a Dataflow object\n *\n * @param dataflow - The data flow string, e.g. \"sourceTaskId[sourceTaskPortId] ==> targetTaskId[targetTaskPortId]\"\n */\nexport class DataflowArrow extends Dataflow {\n constructor(dataflow: DataflowIdType) {\n const pattern =\n /^([a-zA-Z0-9-]+?)\\[([a-zA-Z0-9-]+?)\\] ==> ([a-zA-Z0-9-]+?)\\[([a-zA-Z0-9-]+?)\\]$/;\n const match = dataflow.match(pattern);\n\n if (!match) {\n throw new Error(`Invalid dataflow format: ${dataflow}`);\n }\n\n const [, sourceTaskId, sourceTaskPortId, targetTaskId, targetTaskPortId] = match;\n super(sourceTaskId, sourceTaskPortId, targetTaskId, targetTaskPortId);\n }\n}\n",
|
|
5
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { EventEmitter } from \"@workglow/util\";\nimport { areSemanticallyCompatible } from \"@workglow/util/schema\";\nimport type { StreamEvent } from \"../task/StreamTypes\";\nimport { Task } from \"../task/Task\";\nimport { TaskError } from \"../task/TaskError\";\nimport type { DataflowJson } from \"../task/TaskJSON\";\nimport { TaskIdType, TaskOutput, TaskStatus } from \"../task/TaskTypes\";\nimport {\n DataflowEventListener,\n DataflowEventListeners,\n DataflowEventParameters,\n DataflowEvents,\n} from \"./DataflowEvents\";\nimport { TaskGraph } from \"./TaskGraph\";\nimport { TRANSFORM_DEFS, TransformRegistry } from \"./TransformRegistry\";\nimport type { ITransformStep } from \"./TransformTypes\";\n\nexport type DataflowIdType = `${string}[${string}] ==> ${string}[${string}]`;\n\nexport const DATAFLOW_ALL_PORTS = \"*\";\nexport const DATAFLOW_ERROR_PORT = \"[error]\";\n\n/**\n * Represents a data flow between two tasks, indicating how one task's output is used as input for another task\n */\nexport class Dataflow {\n constructor(\n public sourceTaskId: TaskIdType,\n public sourceTaskPortId: string,\n public targetTaskId: TaskIdType,\n public targetTaskPortId: string\n ) {}\n public static createId(\n sourceTaskId: TaskIdType,\n sourceTaskPortId: string,\n targetTaskId: TaskIdType,\n targetTaskPortId: string\n ): DataflowIdType {\n return `${sourceTaskId}[${sourceTaskPortId}] ==> ${targetTaskId}[${targetTaskPortId}]`;\n }\n get id(): DataflowIdType {\n return Dataflow.createId(\n this.sourceTaskId,\n this.sourceTaskPortId,\n this.targetTaskId,\n this.targetTaskPortId\n );\n }\n public value: any = undefined;\n public status: TaskStatus = TaskStatus.PENDING;\n public error: TaskError | undefined;\n\n /**\n * Active stream for this dataflow edge.\n * Set when a streaming upstream task begins producing chunks.\n * Multiple downstream consumers can each get an independent reader via tee().\n */\n public stream: ReadableStream<StreamEvent> | undefined = undefined;\n\n /**\n * Most recent per-port snapshot data observed while `stream` was active.\n * Populated by the runner's stream-tap on `snapshot` events; cleared on\n * setStream / reset, or transferred to `value` on setPortData. Distinct\n * from `value` (final materialized output) — `latestSnapshot` is the\n * live mid-stream peek.\n */\n public latestSnapshot: unknown = undefined;\n\n /**\n * Returns the current effective value of this edge, regardless of\n * streaming state:\n * 1. `value` — set by setPortData / awaitStreamValue when stream finishes.\n * 2. `latestSnapshot` — set by the runner's snapshot tap during streaming.\n * 3. `undefined` — no data yet.\n *\n * Use this in any read path that wants \"current edge value, regardless of\n * streaming state.\" `getPortData()` retains its strict semantics\n * (only `value`) for callers that explicitly need that.\n */\n public getCurrentValue(): unknown {\n if (this.value !== undefined) return this.value;\n return this.latestSnapshot;\n }\n\n public setStream(stream: ReadableStream<StreamEvent>): void {\n // New stream invalidates any prior peek.\n this.latestSnapshot = undefined;\n this.stream = stream;\n }\n\n public getStream(): ReadableStream<StreamEvent> | undefined {\n return this.stream;\n }\n\n /**\n * Consumes the active stream to completion and materializes the value.\n *\n * Accumulation of text-delta chunks is the responsibility of the **source\n * task** (via StreamProcessor when shouldAccumulate=true).\n * When accumulation is needed the source task emits an enriched finish event\n * that carries the fully-assembled port data. All downstream edges share that\n * enriched event through tee'd ReadableStreams, so no edge needs to\n * re-accumulate independently.\n *\n * This method therefore only reads snapshot and finish events:\n * - **snapshot**: used for replace-mode tasks that emit incremental snapshots.\n * - **finish**: the primary materialization path; carries complete data when\n * the source task accumulated, or provider-level data otherwise.\n * - text-delta / object-delta: ignored here (handled by source task).\n *\n * After consumption the stream reference is cleared. Calling this method on\n * a dataflow that has no stream is a no-op.\n */\n public async awaitStreamValue(): Promise<void> {\n if (!this.stream) return;\n\n const reader = this.stream.getReader();\n let lastSnapshotData: any = undefined;\n let finishData: any = undefined;\n let streamError: Error | undefined;\n\n try {\n while (true) {\n const { done, value: event } = await reader.read();\n if (done) break;\n\n switch (event.type) {\n case \"snapshot\":\n lastSnapshotData = event.data;\n break;\n case \"finish\":\n finishData = event.data;\n break;\n case \"error\":\n streamError = event.error;\n break;\n // text-delta, object-delta: source task handles accumulation\n }\n }\n } finally {\n reader.releaseLock();\n this.stream = undefined;\n }\n\n if (streamError) {\n this.error = streamError as TaskError;\n this.setStatus(TaskStatus.FAILED);\n throw streamError;\n }\n\n // Priority: snapshot > finish.\n // The source task enriches the finish event with accumulated text when\n // shouldAccumulate=true, so finishData carries complete port data.\n if (lastSnapshotData !== undefined) {\n this.setPortData(lastSnapshotData);\n } else if (finishData !== undefined) {\n this.setPortData(finishData);\n }\n }\n\n public reset() {\n this.latestSnapshot = undefined;\n this.status = TaskStatus.PENDING;\n this.error = undefined;\n this.value = undefined;\n this.stream = undefined;\n this._compatibilityCache = undefined;\n this.emit(\"reset\");\n this.emit(\"status\", this.status);\n }\n\n public setStatus(status: TaskStatus) {\n if (status === this.status) return;\n this.status = status;\n switch (status) {\n case TaskStatus.PROCESSING:\n this.emit(\"start\");\n break;\n case TaskStatus.STREAMING:\n this.emit(\"streaming\");\n break;\n case TaskStatus.COMPLETED:\n this.emit(\"complete\");\n break;\n case TaskStatus.ABORTING:\n this.emit(\"abort\");\n break;\n case TaskStatus.PENDING:\n this.emit(\"reset\");\n break;\n case TaskStatus.FAILED:\n this.emit(\"error\", this.error!);\n break;\n case TaskStatus.DISABLED:\n this.emit(\"disabled\");\n break;\n }\n this.emit(\"status\", this.status);\n }\n\n setPortData(entireDataBlock: any) {\n if (this.sourceTaskPortId === DATAFLOW_ALL_PORTS) {\n this.value = entireDataBlock;\n } else if (this.sourceTaskPortId === DATAFLOW_ERROR_PORT) {\n this.error = entireDataBlock;\n } else {\n this.value = entireDataBlock[this.sourceTaskPortId];\n }\n // The materialised value supersedes the mid-stream peek; clear the slot.\n this.latestSnapshot = undefined;\n }\n\n getPortData(): TaskOutput {\n let result: TaskOutput;\n if (this.targetTaskPortId === DATAFLOW_ALL_PORTS) {\n result = this.value;\n } else if (this.targetTaskPortId === DATAFLOW_ERROR_PORT) {\n result = { [DATAFLOW_ERROR_PORT]: this.error };\n } else {\n result = { [this.targetTaskPortId]: this.value };\n }\n return result;\n }\n\n toJSON(): DataflowJson {\n const base: DataflowJson = {\n sourceTaskId: this.sourceTaskId,\n sourceTaskPortId: this.sourceTaskPortId,\n targetTaskId: this.targetTaskId,\n targetTaskPortId: this.targetTaskPortId,\n };\n if (this._transforms.length > 0) {\n base.transforms = this._transforms.map((s) => ({ id: s.id, params: s.params }));\n }\n return base;\n }\n\n /**\n * Cached result of the last semantic compatibility check.\n * Invalidated by calling {@link invalidateCompatibilityCache}.\n */\n protected _compatibilityCache?: \"static\" | \"runtime\" | \"incompatible\";\n\n /**\n * Transform steps applied to data flowing through this dataflow.\n */\n private _transforms: Array<ITransformStep> = [];\n\n getTransforms(): ReadonlyArray<ITransformStep> {\n return this._transforms;\n }\n\n /**\n * Replaces the transform chain with the given steps and invalidates the compatibility cache.\n * Accepts either strict {@link ITransformStep} or steps whose `params` is omitted;\n * omitted `params` is normalised to `undefined`.\n */\n setTransforms(\n steps: ReadonlyArray<{ readonly id: string; readonly params?: Record<string, unknown> }>\n ): void {\n this._transforms = steps.map((s) => ({ id: s.id, params: s.params }));\n this.invalidateCompatibilityCache();\n }\n\n /**\n * Appends a single transform step to the chain and invalidates the compatibility cache.\n * Accepts either strict {@link ITransformStep} or a step whose `params` is omitted;\n * omitted `params` is normalised to `undefined`.\n */\n addTransform(step: { readonly id: string; readonly params?: Record<string, unknown> }): void {\n this._transforms.push({ id: step.id, params: step.params });\n this.invalidateCompatibilityCache();\n }\n\n removeTransform(index: number): void {\n this._transforms.splice(index, 1);\n this.invalidateCompatibilityCache();\n }\n\n /**\n * Fold the transform chain over `this.value`. On any throw, sets\n * `this.error` and TaskStatus.FAILED, then re-throws so the caller\n * (typically TaskGraphRunner) fails the run. Without the re-throw the\n * runner's status-push step would overwrite the FAILED edge state with\n * the source task's COMPLETED status, silently delivering corrupt data.\n */\n async applyTransforms(registry: ServiceRegistry): Promise<void> {\n if (this._transforms.length === 0) return;\n const defs = registry.get(TRANSFORM_DEFS);\n let cur: unknown = this.value;\n try {\n for (const step of this._transforms) {\n const def = defs.get(step.id);\n if (!def) {\n throw new Error(`Unknown transform: ${step.id}`);\n }\n cur = await def.apply(cur, step.params ?? {});\n }\n this.value = cur;\n } catch (e) {\n const error =\n e instanceof TaskError ? e : new TaskError(e instanceof Error ? e.message : String(e));\n if (!(e instanceof TaskError) && e instanceof Error && e.stack) {\n error.stack = e.stack;\n }\n this.error = error;\n this.setStatus(TaskStatus.FAILED);\n throw e;\n }\n }\n\n /**\n * Invalidates the cached semantic compatibility result so the next call\n * to {@link semanticallyCompatible} recomputes it. Call this when\n * either endpoint's schema changes (e.g., in response to a schemaChange event).\n */\n public invalidateCompatibilityCache(): void {\n this._compatibilityCache = undefined;\n }\n\n semanticallyCompatible(\n graph: TaskGraph,\n dataflow: Dataflow,\n registry?: ServiceRegistry\n ): \"static\" | \"runtime\" | \"incompatible\" {\n const sourceTask = graph.getTask(dataflow.sourceTaskId)!;\n const targetTask = graph.getTask(dataflow.targetTaskId)!;\n\n // Only use the cache when both endpoint tasks have stable (non-dynamic) schemas.\n // Tasks with dynamic schemas may emit `schemaChange` events, which would make\n // a cached result stale. Checking the static `hasDynamicSchemas` flag (defined\n // on Task with a default of `false`) is sufficient because tasks with stable\n // schemas never emit `schemaChange`. Unknown constructors default to no caching.\n const shouldCache =\n !((sourceTask.constructor as typeof Task).hasDynamicSchemas ?? true) &&\n !((targetTask.constructor as typeof Task).hasDynamicSchemas ?? true);\n\n if (shouldCache && this._compatibilityCache !== undefined) {\n return this._compatibilityCache;\n }\n\n const targetSchema = targetTask.inputSchema();\n const sourceSchema = sourceTask.outputSchema();\n\n if (typeof targetSchema === \"boolean\") {\n if (targetSchema === false) {\n return \"incompatible\";\n }\n return \"static\";\n }\n if (typeof sourceSchema === \"boolean\") {\n if (sourceSchema === false) {\n return \"incompatible\";\n }\n return \"runtime\";\n }\n\n let targetSchemaProperty =\n DATAFLOW_ALL_PORTS === dataflow.targetTaskPortId\n ? true // Accepts any schema (equivalent to Type.Any())\n : (targetSchema.properties as any)?.[dataflow.targetTaskPortId];\n // If the specific property doesn't exist but additionalProperties is true,\n // treat it as accepting any schema\n if (targetSchemaProperty === undefined && targetSchema.additionalProperties === true) {\n targetSchemaProperty = true;\n }\n let sourceSchemaProperty =\n DATAFLOW_ALL_PORTS === dataflow.sourceTaskPortId\n ? true // Accepts any schema (equivalent to Type.Any())\n : (sourceSchema.properties as any)?.[dataflow.sourceTaskPortId];\n // If the specific property doesn't exist but additionalProperties is true,\n // treat it as outputting any schema\n if (sourceSchemaProperty === undefined && sourceSchema.additionalProperties === true) {\n sourceSchemaProperty = true;\n }\n\n // Compose source schema through the transform chain before comparing.\n // Resolves transform defs from the same registry used by applyTransforms so\n // that custom TRANSFORM_DEFS overrides are reflected in both places.\n // When the source schema is `true` (accepts any — e.g. a boundary task\n // with `additionalProperties: true`), start the chain from `{}` so\n // transforms can still narrow the effective schema. Without this a chain\n // like `pick → unixToIsoDate` from an InputTask would short-circuit to\n // \"static\" against any target regardless of the transforms' output type.\n let effectiveSourceSchema = sourceSchemaProperty;\n if (this._transforms.length > 0) {\n const defs = registry ? registry.get(TRANSFORM_DEFS) : TransformRegistry.all;\n try {\n let cur: any = effectiveSourceSchema === true ? {} : effectiveSourceSchema;\n for (const step of this._transforms) {\n const def = defs.get(step.id);\n if (!def) {\n // Do not cache missing transform definitions because the registry\n // supports runtime registration and a later call may become compatible.\n return \"incompatible\";\n }\n cur = def.inferOutputSchema(cur, step.params ?? {});\n }\n effectiveSourceSchema = cur;\n } catch {\n if (shouldCache) this._compatibilityCache = \"incompatible\";\n return \"incompatible\";\n }\n }\n\n const result = areSemanticallyCompatible(effectiveSourceSchema, targetSchemaProperty);\n if (shouldCache) {\n this._compatibilityCache = result;\n }\n return result;\n }\n\n // ========================================================================\n // Event handling methods\n // ========================================================================\n\n public get events(): EventEmitter<DataflowEventListeners> {\n if (!this._events) {\n this._events = new EventEmitter<DataflowEventListeners>();\n }\n return this._events;\n }\n protected _events: EventEmitter<DataflowEventListeners> | undefined;\n\n public subscribe<Event extends DataflowEvents>(\n name: Event,\n fn: DataflowEventListener<Event>\n ): () => void {\n return this.events.subscribe(name, fn);\n }\n\n public on<Event extends DataflowEvents>(name: Event, fn: DataflowEventListener<Event>): void {\n this.events.on(name, fn);\n }\n\n public off<Event extends DataflowEvents>(name: Event, fn: DataflowEventListener<Event>): void {\n this.events.off(name, fn);\n }\n\n public once<Event extends DataflowEvents>(name: Event, fn: DataflowEventListener<Event>): void {\n this.events.once(name, fn);\n }\n\n /**\n * Returns a promise that resolves when the specified event is emitted\n */\n public waitOn<Event extends DataflowEvents>(\n name: Event\n ): Promise<DataflowEventParameters<Event>> {\n return this.events.waitOn(name) as Promise<DataflowEventParameters<Event>>;\n }\n\n public emit<Event extends DataflowEvents>(\n name: Event,\n ...args: DataflowEventParameters<Event>\n ): void {\n this._events?.emit(name, ...args);\n }\n}\n\n/**\n * Represents a data flow between two tasks, indicating how one task's output is used as input for another task\n *\n * This is a helper class that parses a data flow id string into a Dataflow object\n *\n * @param dataflow - The data flow string, e.g. \"sourceTaskId[sourceTaskPortId] ==> targetTaskId[targetTaskPortId]\"\n */\nexport class DataflowArrow extends Dataflow {\n constructor(dataflow: DataflowIdType) {\n const pattern =\n /^([a-zA-Z0-9-]+?)\\[([a-zA-Z0-9-]+?)\\] ==> ([a-zA-Z0-9-]+?)\\[([a-zA-Z0-9-]+?)\\]$/;\n const match = dataflow.match(pattern);\n\n if (!match) {\n throw new Error(`Invalid dataflow format: ${dataflow}`);\n }\n\n const [, sourceTaskId, sourceTaskPortId, targetTaskId, targetTaskPortId] = match;\n super(sourceTaskId, sourceTaskPortId, targetTaskId, targetTaskPortId);\n }\n}\n",
|
|
6
6
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { JobError } from \"@workglow/job-queue\";\nimport { BaseError } from \"@workglow/util\";\n\nexport class TaskError extends BaseError {\n static override readonly type: string = \"TaskError\";\n /** The type of the task that produced this error, if available. */\n public taskType?: string;\n /** The ID of the task that produced this error, if available. */\n public taskId?: unknown;\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class TaskConfigurationError extends TaskError {\n static override readonly type: string = \"TaskConfigurationError\";\n constructor(message: string) {\n super(message);\n }\n}\n\nexport class WorkflowError extends TaskError {\n static override readonly type: string = \"WorkflowError\";\n constructor(message: string) {\n super(message);\n }\n}\n\n/**\n * A task error caused by a task being aborted (task.abort() or external signal).\n */\nexport class TaskAbortedError extends TaskError {\n static override readonly type: string = \"TaskAbortedError\";\n constructor(message: string = \"Task aborted\") {\n super(message);\n }\n}\n\n/**\n * A task error caused by exceeding `runConfig.timeout`.\n */\nexport class TaskTimeoutError extends TaskAbortedError {\n static override readonly type: string = \"TaskTimeoutError\";\n constructor(timeoutMs?: number) {\n super(timeoutMs ? `Task timed out after ${timeoutMs}ms` : \"Task timed out\");\n }\n}\n\n/**\n * Thrown when graph-level execution exceeds the configured `timeout` in\n * {@link TaskGraphRunConfig}. Distinct from {@link TaskTimeoutError} (which is\n * thrown for individual-task timeouts) so callers can tell whether the timeout\n * was on a single task or on the entire graph run.\n */\nexport class TaskGraphTimeoutError extends TaskTimeoutError {\n static override readonly type: string = \"TaskGraphTimeoutError\";\n constructor(timeoutMs?: number) {\n super(timeoutMs);\n // Override the message set by TaskTimeoutError to make it graph-specific.\n this.message = timeoutMs\n ? `Graph execution timed out after ${timeoutMs}ms`\n : \"Graph execution timed out\";\n }\n}\n\nexport class TaskFailedError extends TaskError {\n static override readonly type: string = \"TaskFailedError\";\n constructor(message: string = \"Task failed\") {\n super(message);\n }\n}\n\nexport class JobTaskFailedError extends TaskFailedError {\n static override readonly type: string = \"JobTaskFailedError\";\n public jobError: JobError;\n /** Machine-readable code when the underlying job error provides one (e.g. FETCH_HTTP_CLIENT_ERROR). */\n public code?: string;\n constructor(err: JobError) {\n super(String(err));\n this.jobError = err;\n if (err.code) {\n this.code = err.code;\n }\n }\n}\n\nexport class TaskJSONError extends TaskError {\n static override readonly type: string = \"TaskJSONError\";\n constructor(message: string = \"Error converting JSON to a Task\") {\n super(message);\n }\n}\n\nexport class TaskInvalidInputError extends TaskError {\n static override readonly type: string = \"TaskInvalidInputError\";\n constructor(message: string = \"Invalid input data\") {\n super(message);\n }\n}\n\nexport class TaskEntitlementError extends TaskError {\n static override readonly type: string = \"TaskEntitlementError\";\n constructor(message: string = \"Required entitlements denied\") {\n super(message);\n }\n}\n\n/**\n * Thrown when toJSON is called on a task whose config contains non-serializable\n * values (e.g. functions). Tasks should override canSerializeConfig() to declare\n * whether they support serialization.\n */\nexport class TaskSerializationError extends TaskError {\n static override readonly type: string = \"TaskSerializationError\";\n constructor(taskType: string) {\n super(\n `Task \"${taskType}\" cannot be serialized: config contains non-serializable values. ` +\n `Use a declarative config alternative or remove function-valued config properties.`\n );\n }\n}\n",
|
|
7
7
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchema, FromSchema } from \"@workglow/util/schema\";\nimport { StripJSONSchema } from \"@workglow/util/schema\";\nimport type { Task } from \"./Task\";\n\n/**\n * Enum representing the possible states of a task\n *\n * PENDING -> PROCESSING -> COMPLETED\n * PENDING -> PROCESSING -> STREAMING -> COMPLETED\n * PENDING -> PROCESSING -> ABORTING -> FAILED\n * PENDING -> PROCESSING -> FAILED\n * PENDING -> DISABLED\n */\nexport type TaskStatus =\n | \"PENDING\"\n | \"DISABLED\"\n | \"PROCESSING\"\n | \"STREAMING\"\n | \"COMPLETED\"\n | \"ABORTING\"\n | \"FAILED\";\n\nexport const TaskStatus = {\n /** Task is created but not yet started */\n PENDING: \"PENDING\",\n /** Task is disabled due to conditional logic */\n DISABLED: \"DISABLED\",\n /** Task is currently running */\n PROCESSING: \"PROCESSING\",\n /** Task has begun producing streaming output chunks */\n STREAMING: \"STREAMING\",\n /** Task has completed successfully */\n COMPLETED: \"COMPLETED\",\n /** Task is in the process of being aborted */\n ABORTING: \"ABORTING\",\n /** Task has failed */\n FAILED: \"FAILED\",\n} as const satisfies Record<TaskStatus, TaskStatus>;\n\n// ========================================================================\n// Core Task Data Types\n// ========================================================================\n\nexport interface DataPorts extends StripJSONSchema<Record<string, any>> {\n [key: string]: unknown;\n}\n\n/** Type for task input data */\nexport type TaskInput = DataPorts;\n\n/** Type for task output data */\nexport type TaskOutput = DataPorts;\n\nexport type CompoundTaskOutput =\n | {\n outputs: TaskOutput[];\n }\n | {\n [key: string]: unknown | unknown[] | undefined;\n };\n\n/** Type for task type names */\nexport type TaskTypeName = string;\n\n// ========================================================================\n// Task Configuration Schema and Types\n// ========================================================================\n\n/**\n * Base JSON Schema for task configuration.\n * Exported so subclasses can compose their own schema with:\n * `...TaskConfigSchema[\"properties\"]`\n *\n * Fields:\n * - id: unique task identifier (any type)\n * - title: human-readable name for the task instance (overrides static title)\n * - description: human-readable description (overrides static description)\n * - cacheable: design-time cache flag (runtime override goes in IRunConfig)\n * - inputSchema: dynamic input schema override (for tasks like InputTask)\n * - outputSchema: dynamic output schema override (for tasks like OutputTask)\n * - extras: arbitrary user data serialized with the task JSON\n * - timeout: max execution time in milliseconds (auto-aborts with TaskTimeoutError)\n */\nexport const TaskConfigSchema = {\n type: \"object\",\n properties: {\n id: {\n \"x-ui-hidden\": true,\n },\n title: { type: \"string\" },\n description: { type: \"string\" },\n cacheable: { type: \"boolean\" },\n timeout: { type: \"number\", description: \"Max execution time in milliseconds\" },\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: true,\n \"x-ui-hidden\": true,\n },\n outputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: true,\n \"x-ui-hidden\": true,\n },\n extras: {\n type: \"object\",\n additionalProperties: true,\n \"x-ui-hidden\": true,\n },\n defaults: {\n type: \"object\",\n additionalProperties: true,\n \"x-ui-hidden\": true,\n },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\ntype BaseFromSchema = FromSchema<typeof TaskConfigSchema>;\n\n/**\n * Base type for task configuration, derived from TaskConfigSchema.\n * Use `TaskConfigSchema` when building JSON schemas in subclasses.\n * Use this type when declaring the Config generic parameter.\n */\nexport type TaskConfig<Input extends DataPorts = DataPorts> = Omit<\n BaseFromSchema,\n \"id\" | \"inputSchema\" | \"outputSchema\"\n> & {\n /** Unique identifier for the task (uuid4 by default) */\n id?: unknown;\n /** Dynamic input schema override for the task instance */\n inputSchema?: DataPortSchema;\n /** Dynamic output schema override for the task instance */\n outputSchema?: DataPortSchema;\n /** Default input values provided at construction time */\n defaults?: NoInfer<Partial<Input>>;\n};\n\n/** Type for task ID */\nexport type TaskIdType = Task<TaskInput, TaskOutput, TaskConfig>[\"config\"][\"id\"];\n",
|
|
8
8
|
"/**\n * @license Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createServiceToken, globalServiceRegistry, ServiceRegistry } from \"@workglow/util\";\nimport type { ITransformDef } from \"./TransformTypes\";\n\nconst transformDefs = new Map<string, ITransformDef<any>>();\n\n/** Register / unregister / inspect global transforms. */\nexport const TransformRegistry = {\n all: transformDefs,\n registerTransform(def: ITransformDef<any>): void {\n transformDefs.set(def.id, def);\n },\n unregisterTransform(id: string): void {\n transformDefs.delete(id);\n },\n};\n\n/** DI token — mirrors TASK_CONSTRUCTORS pattern. */\nexport const TRANSFORM_DEFS = createServiceToken<Map<string, ITransformDef<any>>>(\"transform.defs\");\n\n/**\n * Registers the transform defs map default factory on the given registry.\n * Called by `bootstrapWorkglow` and `createOrchestrationContext`.\n */\nexport function registerTransformDefaults(registry: ServiceRegistry = globalServiceRegistry): void {\n registry.registerIfAbsent(\n TRANSFORM_DEFS,\n (): Map<string, ITransformDef<any>> => TransformRegistry.all,\n true\n );\n}\n\n// Self-register on the global registry. Idempotent.\nregisterTransformDefaults();\n",
|
|
@@ -11,34 +11,34 @@
|
|
|
11
11
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { getInputResolvers } from \"@workglow/util\";\nimport type { DataPortSchema } from \"@workglow/util/schema\";\n\nexport interface InputResolverConfig {\n readonly registry: ServiceRegistry;\n}\n\nfunction isPlainObject(value: object): boolean {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Extracts the format string from a schema, handling oneOf/anyOf wrappers.\n */\nexport function getSchemaFormat(\n schema: unknown,\n visited: WeakSet<object> = new WeakSet()\n): string | undefined {\n if (typeof schema !== \"object\" || schema === null) return undefined;\n if (visited.has(schema)) return undefined;\n visited.add(schema);\n\n const s = schema as Record<string, unknown>;\n\n // Direct format\n if (typeof s.format === \"string\") return s.format;\n\n // Check oneOf/anyOf/allOf for format\n const variants = (s.oneOf ?? s.anyOf) as unknown[] | undefined;\n if (Array.isArray(variants)) {\n for (const variant of variants) {\n if (typeof variant === \"object\" && variant !== null) {\n const v = variant as Record<string, unknown>;\n if (typeof v.format === \"string\") return v.format;\n }\n }\n }\n\n const allOf = s.allOf as unknown[] | undefined;\n if (Array.isArray(allOf)) {\n for (const sub of allOf) {\n const fmt = getSchemaFormat(sub, visited);\n if (fmt !== undefined) return fmt;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts the object-typed schema from a property schema, handling oneOf/anyOf wrappers.\n * This is needed for patterns like `oneOf: [{ type: \"string\" }, { type: \"object\", properties: {...} }]`\n * where the model can be either a string ID or an inline config object.\n */\nexport function getObjectSchema(\n schema: unknown,\n visited: WeakSet<object> = new WeakSet()\n): (Record<string, unknown> & { properties: Record<string, unknown> }) | undefined {\n if (typeof schema !== \"object\" || schema === null) return undefined;\n if (visited.has(schema)) return undefined;\n visited.add(schema);\n\n const s = schema as Record<string, unknown>;\n\n // Direct object schema with properties\n if (s.type === \"object\" && s.properties && typeof s.properties === \"object\") {\n return s as Record<string, unknown> & { properties: Record<string, unknown> };\n }\n\n // Check oneOf/anyOf for object variant\n const variants = (s.oneOf ?? s.anyOf) as unknown[] | undefined;\n if (Array.isArray(variants)) {\n for (const variant of variants) {\n if (typeof variant === \"object\" && variant !== null) {\n const v = variant as Record<string, unknown>;\n if (v.type === \"object\" && v.properties && typeof v.properties === \"object\") {\n return v as Record<string, unknown> & { properties: Record<string, unknown> };\n }\n }\n }\n }\n\n // Check allOf for object variant\n const allOf = s.allOf as unknown[] | undefined;\n if (Array.isArray(allOf)) {\n for (const sub of allOf) {\n const result = getObjectSchema(sub, visited);\n if (result !== undefined) return result;\n }\n }\n\n return undefined;\n}\n\n/**\n * Gets the format prefix from a format string.\n * For \"model:TextEmbedding\" returns \"model\"\n * For \"storage:tabular\" returns \"storage\"\n */\nexport function getFormatPrefix(format: string): string {\n const colonIndex = format.indexOf(\":\");\n return colonIndex >= 0 ? format.substring(0, colonIndex) : format;\n}\n\n/**\n * Returns true if the schema has any properties with format annotations\n * (direct or in oneOf/anyOf variants). Used as a fast-path check to skip\n * resolution when no format-annotated properties exist.\n */\nexport function schemaHasFormatAnnotations(schema: DataPortSchema): boolean {\n if (typeof schema === \"boolean\") return false;\n\n const properties = schema.properties;\n if (!properties || typeof properties !== \"object\") return false;\n\n for (const propSchema of Object.values(properties)) {\n if (getSchemaFormat(propSchema) !== undefined) return true;\n }\n return false;\n}\n\n/**\n * Resolves schema-annotated inputs by looking up string IDs from registries.\n * String values with matching format annotations are resolved to their instances.\n * Non-string values (objects/instances) are passed through unchanged.\n *\n * @param input The task input object\n * @param schema The task's input schema\n * @param config Configuration including the service registry\n * @returns The input with resolved values\n *\n * @example\n * ```typescript\n * // In TaskRunner.run()\n * const resolvedInput = await resolveSchemaInputs(\n * this.task.runInputData,\n * (this.task.constructor as typeof Task).inputSchema(),\n * { registry: this.registry }\n * );\n * ```\n */\nexport async function resolveSchemaInputs<T extends Record<string, unknown>>(\n input: T,\n schema: DataPortSchema,\n config: InputResolverConfig,\n visited: Set<object> = new Set()\n): Promise<T> {\n if (typeof schema === \"boolean\") return input;\n\n const properties = schema.properties;\n if (!properties || typeof properties !== \"object\") return input;\n\n const resolvers = getInputResolvers();\n const resolved: Record<string, unknown> = { ...input };\n\n for (const [key, propSchema] of Object.entries(properties)) {\n let value = resolved[key];\n\n // Phase 1: Resolve format-annotated string values\n const format = getSchemaFormat(propSchema);\n let phase1Transformed = false;\n if (format) {\n let resolver = resolvers.get(format);\n if (!resolver) {\n const prefix = getFormatPrefix(format);\n resolver = resolvers.get(prefix);\n }\n\n if (resolver) {\n // Handle string values\n if (typeof value === \"string\") {\n value = await resolver(value, format, config.registry);\n resolved[key] = value;\n phase1Transformed = true;\n }\n // Handle arrays - resolve string elements and pass through non-string elements unchanged\n else if (Array.isArray(value) && value.some((item) => typeof item === \"string\")) {\n const results = await Promise.all(\n value.map((item) =>\n typeof item === \"string\" ? resolver(item, format, config.registry) : item\n )\n );\n value = results.filter((result) => result !== undefined);\n resolved[key] = value;\n phase1Transformed = true;\n }\n }\n }\n\n // Phase 2: Recurse into object values if the schema defines nested properties.\n // Skip class instances (non-plain objects like GpuImage) — recursing would\n // spread them into plain records and lose prototype methods. Plain objects\n // (including those returned by Phase 1 resolvers) still recurse so nested\n // format annotations get a chance to resolve.\n // Skip recursion when a format resolver owns the property AND Phase 1 did\n // NOT transform the value — those plain objects are raw forms (e.g. ImageValue\n // for format:\"image\") that must pass through to the task as-is; spreading them\n // loses reference identity. When Phase 1 DID transform (string → object), the\n // resulting plain object still recurses so nested format annotations resolve.\n const hasFormatResolver = format\n ? !!(resolvers.get(format) ?? resolvers.get(getFormatPrefix(format)))\n : false;\n const skipPhase2 = hasFormatResolver && !phase1Transformed;\n if (\n !skipPhase2 &&\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n isPlainObject(value)\n ) {\n const objectSchema = getObjectSchema(propSchema);\n if (objectSchema && !visited.has(objectSchema)) {\n visited.add(objectSchema);\n try {\n resolved[key] = await resolveSchemaInputs(\n value as Record<string, unknown>,\n objectSchema as DataPortSchema,\n config,\n visited\n );\n } finally {\n visited.delete(objectSchema);\n }\n }\n }\n }\n\n return resolved as T;\n}\n",
|
|
12
12
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getObjectSchema, getSchemaFormat } from \"../task/InputResolver\";\nimport type { ITaskGraph } from \"./ITaskGraph\";\n\n/**\n * Result of scanning a task graph for credential format annotations.\n */\nexport interface GraphFormatScanResult {\n /** Whether any task in the graph has a `format: \"credential\"` property in its input or config schema. */\n readonly needsCredentials: boolean;\n /** The set of format strings found (e.g., `\"credential\"`). */\n readonly credentialFormats: ReadonlySet<string>;\n}\n\n/**\n * Recursively walks a JSON Schema's properties looking for any property whose\n * format annotation matches `targetFormat`. Handles nested objects and\n * `oneOf`/`anyOf` wrappers.\n */\nfunction schemaHasFormat(schema: unknown, targetFormat: string): boolean {\n if (typeof schema !== \"object\" || schema === null) return false;\n const s = schema as Record<string, unknown>;\n\n const properties = s.properties as Record<string, unknown> | undefined;\n if (properties && typeof properties === \"object\") {\n for (const propSchema of Object.values(properties)) {\n const format = getSchemaFormat(propSchema);\n if (format === targetFormat) return true;\n\n // Recurse into nested object schemas\n const objectSchema = getObjectSchema(propSchema);\n if (objectSchema && schemaHasFormat(objectSchema, targetFormat)) return true;\n }\n }\n\n return false;\n}\n\n/**\n * Scans a task graph for any task whose input or config schema contains a\n * property with the given format annotation.\n *\n * @param graph The task graph to scan\n * @param targetFormat The format string to search for (e.g., `\"credential\"`)\n * @returns `true` if at least one task has a matching format annotation\n */\nexport function scanGraphForFormat(graph: ITaskGraph, targetFormat: string): boolean {\n for (const task of graph.getTasks()) {\n const inputSchema = task.inputSchema();\n if (typeof inputSchema !== \"boolean\" && schemaHasFormat(inputSchema, targetFormat)) {\n return true;\n }\n\n const configSchema = task.configSchema();\n if (typeof configSchema !== \"boolean\" && schemaHasFormat(configSchema, targetFormat)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Scans a task graph for credential requirements.\n *\n * A task only counts as needing credentials when it has a schema property\n * annotated with `format: \"credential\"` **and** the corresponding value is\n * actually set on the task's config or input defaults (non-empty string).\n * Annotating a schema is not enough — plenty of model configs have\n * `provider_config.credential_key` available but unused (e.g. local ONNX\n * models).\n *\n * @example\n * ```ts\n * const result = scanGraphForCredentials(graph);\n * if (result.needsCredentials) {\n * await ensureCredentialStoreUnlocked();\n * }\n * ```\n */\nexport function scanGraphForCredentials(graph: ITaskGraph): GraphFormatScanResult {\n const credentialFormats = new Set<string>();\n\n for (const task of graph.getTasks()) {\n collectUsedCredentialFormats(task.inputSchema(), task.defaults ?? {}, credentialFormats);\n collectUsedCredentialFormats(\n task.configSchema(),\n (task as unknown as { config?: Record<string, unknown> }).config ?? {},\n credentialFormats\n );\n }\n\n return {\n needsCredentials: credentialFormats.size > 0,\n credentialFormats,\n };\n}\n\n/**\n * Walk schema and data in parallel. When a property is annotated with a\n * credential format AND the corresponding data value is a non-empty string,\n * record the format. Recurses into nested object schemas.\n */\nfunction collectUsedCredentialFormats(schema: unknown, data: unknown, formats: Set<string>): void {\n if (typeof schema === \"boolean\" || typeof schema !== \"object\" || schema === null) return;\n const s = schema as Record<string, unknown>;\n\n const properties = s.properties as Record<string, unknown> | undefined;\n if (!properties || typeof properties !== \"object\") return;\n\n const dataObj =\n typeof data === \"object\" && data !== null ? (data as Record<string, unknown>) : {};\n\n for (const [propName, propSchema] of Object.entries(properties)) {\n const format = getSchemaFormat(propSchema);\n const value = dataObj[propName];\n if (format === \"credential\" && typeof value === \"string\" && value.length > 0) {\n formats.add(format);\n }\n\n // Recurse into nested object schemas with the matching nested data\n const objectSchema = getObjectSchema(propSchema);\n if (objectSchema) {\n collectUsedCredentialFormats(objectSchema, value, formats);\n }\n }\n}\n",
|
|
13
13
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { uuid4 } from \"@workglow/util\";\nimport type { DataPortSchema, JsonSchema } from \"@workglow/util/schema\";\nimport type { ITask } from \"../task/ITask\";\nimport { Task } from \"../task/Task\";\nimport type {\n DataflowJson,\n JsonTaskItem,\n TaskGraphItemJson,\n TaskGraphJson,\n} from \"../task/TaskJSON\";\nimport type { TaskIdType } from \"../task/TaskTypes\";\nimport { DATAFLOW_ALL_PORTS } from \"./Dataflow\";\nimport type { TaskGraph } from \"./TaskGraph\";\n\nexport interface GraphSchemaOptions {\n /**\n * When true, annotate each property with `x-source-task-id` or `x-source-task-ids`\n * to identify which task(s) the property originates from.\n */\n readonly trackOrigins?: boolean;\n}\n\n/**\n * Calculates the depth (longest path from any starting node) for each task in the graph.\n * @returns A map of task IDs to their depths\n */\nexport function calculateNodeDepths(graph: TaskGraph): Map<TaskIdType, number> {\n const depths = new Map<TaskIdType, number>();\n const tasks = graph.getTasks();\n\n for (const task of tasks) {\n depths.set(task.id, 0);\n }\n\n const sortedTasks = graph.topologicallySortedNodes();\n\n for (const task of sortedTasks) {\n const currentDepth = depths.get(task.id) || 0;\n const targetTasks = graph.getTargetTasks(task.id);\n\n for (const targetTask of targetTasks) {\n const targetDepth = depths.get(targetTask.id) || 0;\n depths.set(targetTask.id, Math.max(targetDepth, currentDepth + 1));\n }\n }\n\n return depths;\n}\n\n/**\n * Computes the input schema for a graph by examining root tasks (no incoming edges)\n * and non-root tasks with unsatisfied required inputs.\n *\n * When `options.trackOrigins` is true, each property is annotated with\n * `x-source-task-id` (single origin) or `x-source-task-ids` (multiple origins).\n */\nexport function computeGraphInputSchema(\n graph: TaskGraph,\n options?: GraphSchemaOptions\n): DataPortSchema {\n const trackOrigins = options?.trackOrigins ?? false;\n const properties: Record<string, any> = {};\n const required: string[] = [];\n // Track which task IDs contribute each property name\n const propertyOrigins: Record<string, TaskIdType[]> = {};\n\n const tasks = graph.getTasks();\n const startingNodes = tasks.filter((task) => graph.getSourceDataflows(task.id).length === 0);\n\n // Collect all properties from root tasks\n for (const task of startingNodes) {\n const taskInputSchema = task.inputSchema();\n if (typeof taskInputSchema === \"boolean\") {\n if (taskInputSchema === false) {\n continue;\n }\n if (taskInputSchema === true) {\n properties[DATAFLOW_ALL_PORTS] = {};\n continue;\n }\n }\n const taskProperties = taskInputSchema.properties || {};\n\n for (const [inputName, inputProp] of Object.entries(taskProperties)) {\n if (!properties[inputName]) {\n properties[inputName] = inputProp;\n\n // A root task's property is only truly \"required\" from the outside if\n // the task itself marks it required AND it is not pre-populated by a\n // `defaults` value baked into the task at construction. Tasks wrapped\n // into a parent graph after being built with `{ defaults: ... }` (a\n // common pattern inside `task.execute` when assembling a subgraph)\n // would otherwise cause the wrapping graph/workflow to reject empty\n // external input even though every child input is already satisfied.\n // The non-root branch below already honors `task.defaults`; this keeps\n // root handling consistent.\n const isRequired =\n taskInputSchema.required?.includes(inputName) === true &&\n !(task.defaults && task.defaults[inputName] !== undefined);\n if (isRequired) {\n required.push(inputName);\n }\n\n if (trackOrigins) {\n propertyOrigins[inputName] = [task.id];\n }\n } else if (trackOrigins) {\n propertyOrigins[inputName].push(task.id);\n }\n }\n }\n\n // For non-root tasks, collect only REQUIRED properties not satisfied by dataflows.\n const sourceIds = new Set(startingNodes.map((t) => t.id));\n for (const task of tasks) {\n if (sourceIds.has(task.id)) continue;\n\n const taskInputSchema = task.inputSchema();\n if (typeof taskInputSchema === \"boolean\") continue;\n\n const requiredKeys = new Set<string>((taskInputSchema.required as string[] | undefined) || []);\n if (requiredKeys.size === 0) continue;\n\n const connectedPorts = new Set(\n graph.getSourceDataflows(task.id).map((df) => df.targetTaskPortId)\n );\n\n for (const key of requiredKeys) {\n if (connectedPorts.has(key)) continue;\n if (properties[key]) {\n // Property already collected — track additional origin\n if (trackOrigins) {\n propertyOrigins[key].push(task.id);\n }\n continue;\n }\n\n // Skip if the task already has a default value for this property\n if (task.defaults && task.defaults[key] !== undefined) continue;\n\n const prop = (taskInputSchema.properties || {})[key];\n if (!prop || typeof prop === \"boolean\") continue;\n\n properties[key] = prop;\n if (!required.includes(key)) {\n required.push(key);\n }\n\n if (trackOrigins) {\n propertyOrigins[key] = [task.id];\n }\n }\n }\n\n // Apply origin annotations\n if (trackOrigins) {\n for (const [propName, origins] of Object.entries(propertyOrigins)) {\n const prop = properties[propName];\n if (!prop || typeof prop === \"boolean\") continue;\n if (origins.length === 1) {\n properties[propName] = { ...prop, \"x-source-task-id\": origins[0] };\n } else {\n properties[propName] = { ...prop, \"x-source-task-ids\": origins };\n }\n }\n }\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n } as const satisfies DataPortSchema;\n}\n\n/**\n * Computes the output schema for a graph by examining leaf tasks (no outgoing edges)\n * at the maximum depth level.\n *\n * When `options.trackOrigins` is true, each property is annotated with\n * `x-source-task-id` (single origin) or `x-source-task-ids` (multiple origins).\n */\nexport function computeGraphOutputSchema(\n graph: TaskGraph,\n options?: GraphSchemaOptions\n): DataPortSchema {\n const trackOrigins = options?.trackOrigins ?? false;\n const properties: Record<string, any> = {};\n const required: string[] = [];\n // Track which task IDs contribute each property name\n const propertyOrigins: Record<string, TaskIdType[]> = {};\n\n // Find all ending nodes (nodes with no outgoing dataflows)\n const tasks = graph.getTasks();\n const endingNodes = tasks.filter((task) => graph.getTargetDataflows(task.id).length === 0);\n\n // Calculate depths for all nodes\n const depths = calculateNodeDepths(graph);\n\n // Find the maximum depth among ending nodes\n const maxDepth = Math.max(...endingNodes.map((task) => depths.get(task.id) || 0));\n\n // Filter ending nodes to only those at the maximum depth (last level)\n const lastLevelNodes = endingNodes.filter((task) => depths.get(task.id) === maxDepth);\n\n // Count how many ending nodes produce each property\n const propertyCount: Record<string, number> = {};\n const propertySchema: Record<string, any> = {};\n\n for (const task of lastLevelNodes) {\n const taskOutputSchema = task.outputSchema();\n if (typeof taskOutputSchema === \"boolean\") {\n if (taskOutputSchema === false) {\n continue;\n }\n if (taskOutputSchema === true) {\n properties[DATAFLOW_ALL_PORTS] = {};\n continue;\n }\n }\n const taskProperties = taskOutputSchema.properties || {};\n\n for (const [outputName, outputProp] of Object.entries(taskProperties)) {\n propertyCount[outputName] = (propertyCount[outputName] || 0) + 1;\n if (!propertySchema[outputName]) {\n propertySchema[outputName] = outputProp;\n }\n if (trackOrigins) {\n if (!propertyOrigins[outputName]) {\n propertyOrigins[outputName] = [task.id];\n } else {\n propertyOrigins[outputName].push(task.id);\n }\n }\n }\n }\n\n // Build the final schema: properties produced by multiple nodes become arrays\n for (const [outputName] of Object.entries(propertyCount)) {\n const outputProp = propertySchema[outputName];\n\n if (lastLevelNodes.length === 1) {\n properties[outputName] = outputProp;\n } else {\n properties[outputName] = {\n type: \"array\",\n items: outputProp as any,\n };\n }\n }\n\n // Apply origin annotations\n if (trackOrigins) {\n for (const [propName, origins] of Object.entries(propertyOrigins)) {\n const prop = properties[propName];\n if (!prop || typeof prop === \"boolean\") continue;\n if (origins.length === 1) {\n properties[propName] = { ...prop, \"x-source-task-id\": origins[0] };\n } else {\n properties[propName] = { ...prop, \"x-source-task-ids\": origins };\n }\n }\n }\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n } as DataPortSchema;\n}\n\n// ========================================================================\n// Boundary Node Injection\n// ========================================================================\n\n/**\n * Strips `x-source-task-id` and `x-source-task-ids` annotations from schema properties.\n */\nfunction stripOriginAnnotations(schema: DataPortSchema): DataPortSchema {\n if (typeof schema === \"boolean\" || !schema || typeof schema !== \"object\") return schema;\n const properties = schema.properties;\n if (!properties) return schema;\n\n const strippedProperties: Record<string, any> = {};\n for (const [key, prop] of Object.entries(properties)) {\n if (!prop || typeof prop !== \"object\") {\n strippedProperties[key] = prop;\n continue;\n }\n const {\n \"x-source-task-id\": _id,\n \"x-source-task-ids\": _ids,\n ...rest\n } = prop as Record<string, any>;\n strippedProperties[key] = rest;\n }\n\n return { ...schema, properties: strippedProperties } as DataPortSchema;\n}\n\n/**\n * Extracts origin task IDs from a schema property's `x-source-task-id` or `x-source-task-ids`.\n */\nfunction getOriginTaskIds(prop: Record<string, any>): TaskIdType[] {\n if (prop[\"x-source-task-ids\"]) {\n return prop[\"x-source-task-ids\"] as TaskIdType[];\n }\n if (prop[\"x-source-task-id\"] !== undefined) {\n return [prop[\"x-source-task-id\"] as TaskIdType];\n }\n return [];\n}\n\n/**\n * Adds synthetic InputTask and OutputTask boundary nodes to a TaskGraphJson.\n * The boundary nodes represent the graph's external interface.\n *\n * InputTask is placed first in the tasks array, OutputTask last.\n * Per-property dataflows connect them to the origin tasks using origin tracking annotations.\n */\nexport function addBoundaryNodesToGraphJson(json: TaskGraphJson, graph: TaskGraph): TaskGraphJson {\n const hasInputTask = json.tasks.some((t) => t.type === \"InputTask\");\n const hasOutputTask = json.tasks.some((t) => t.type === \"OutputTask\");\n\n // Skip entirely if both boundary tasks already exist\n if (hasInputTask && hasOutputTask) {\n return json;\n }\n\n const inputSchema = !hasInputTask\n ? computeGraphInputSchema(graph, { trackOrigins: true })\n : undefined;\n const outputSchema = !hasOutputTask\n ? computeGraphOutputSchema(graph, { trackOrigins: true })\n : undefined;\n\n const prependTasks: TaskGraphItemJson[] = [];\n const appendTasks: TaskGraphItemJson[] = [];\n const inputDataflows: DataflowJson[] = [];\n const outputDataflows: DataflowJson[] = [];\n\n if (!hasInputTask && inputSchema) {\n const inputTaskId = uuid4();\n const strippedInputSchema = stripOriginAnnotations(inputSchema);\n\n prependTasks.push({\n id: inputTaskId,\n type: \"InputTask\",\n config: {\n inputSchema: strippedInputSchema,\n outputSchema: strippedInputSchema,\n },\n });\n\n // Create per-property dataflows from InputTask to origin tasks\n if (typeof inputSchema !== \"boolean\" && inputSchema.properties) {\n for (const [propName, prop] of Object.entries(inputSchema.properties)) {\n if (!prop || typeof prop === \"boolean\") continue;\n const origins = getOriginTaskIds(prop as Record<string, any>);\n for (const originId of origins) {\n inputDataflows.push({\n sourceTaskId: inputTaskId,\n sourceTaskPortId: propName,\n targetTaskId: originId,\n targetTaskPortId: propName,\n });\n }\n }\n }\n }\n\n if (!hasOutputTask && outputSchema) {\n const outputTaskId = uuid4();\n const strippedOutputSchema = stripOriginAnnotations(outputSchema);\n\n appendTasks.push({\n id: outputTaskId,\n type: \"OutputTask\",\n config: {\n inputSchema: strippedOutputSchema,\n outputSchema: strippedOutputSchema,\n },\n });\n\n // Create per-property dataflows from origin tasks to OutputTask\n if (typeof outputSchema !== \"boolean\" && outputSchema.properties) {\n for (const [propName, prop] of Object.entries(outputSchema.properties)) {\n if (!prop || typeof prop === \"boolean\") continue;\n const origins = getOriginTaskIds(prop as Record<string, any>);\n for (const originId of origins) {\n outputDataflows.push({\n sourceTaskId: originId,\n sourceTaskPortId: propName,\n targetTaskId: outputTaskId,\n targetTaskPortId: propName,\n });\n }\n }\n }\n }\n\n return {\n tasks: [...prependTasks, ...json.tasks, ...appendTasks],\n dataflows: [...inputDataflows, ...json.dataflows, ...outputDataflows],\n };\n}\n\n/**\n * Adds synthetic InputTask and OutputTask boundary nodes to a dependency JSON items array.\n * Per-property dependencies connect them to the origin tasks using origin tracking annotations.\n */\nexport function addBoundaryNodesToDependencyJson(\n items: JsonTaskItem[],\n graph: TaskGraph\n): JsonTaskItem[] {\n const hasInputTask = items.some((t) => t.type === \"InputTask\");\n const hasOutputTask = items.some((t) => t.type === \"OutputTask\");\n\n // Skip entirely if both boundary tasks already exist\n if (hasInputTask && hasOutputTask) {\n return items;\n }\n\n const prependItems: JsonTaskItem[] = [];\n const appendItems: JsonTaskItem[] = [];\n\n if (!hasInputTask) {\n const inputSchema = computeGraphInputSchema(graph, { trackOrigins: true });\n const inputTaskId = uuid4();\n const strippedInputSchema = stripOriginAnnotations(inputSchema);\n\n prependItems.push({\n id: inputTaskId,\n type: \"InputTask\",\n config: {\n inputSchema: strippedInputSchema,\n outputSchema: strippedInputSchema,\n },\n });\n\n // Build dependencies for items that receive data from InputTask\n if (typeof inputSchema !== \"boolean\" && inputSchema.properties) {\n for (const [propName, prop] of Object.entries(inputSchema.properties)) {\n if (!prop || typeof prop === \"boolean\") continue;\n const origins = getOriginTaskIds(prop as Record<string, any>);\n for (const originId of origins) {\n const targetItem = items.find((item) => item.id === originId);\n if (!targetItem) continue;\n if (!targetItem.dependencies) {\n targetItem.dependencies = {};\n }\n const existing = targetItem.dependencies[propName];\n const dep = { id: inputTaskId, output: propName };\n if (!existing) {\n targetItem.dependencies[propName] = dep;\n } else if (Array.isArray(existing)) {\n existing.push(dep);\n } else {\n targetItem.dependencies[propName] = [existing, dep];\n }\n }\n }\n }\n }\n\n if (!hasOutputTask) {\n const outputSchema = computeGraphOutputSchema(graph, { trackOrigins: true });\n const outputTaskId = uuid4();\n const strippedOutputSchema = stripOriginAnnotations(outputSchema);\n\n // Build dependencies for OutputTask from origin tasks\n const outputDependencies: JsonTaskItem[\"dependencies\"] = {};\n if (typeof outputSchema !== \"boolean\" && outputSchema.properties) {\n for (const [propName, prop] of Object.entries(outputSchema.properties)) {\n if (!prop || typeof prop === \"boolean\") continue;\n const origins = getOriginTaskIds(prop as Record<string, any>);\n if (origins.length === 1) {\n outputDependencies[propName] = { id: origins[0], output: propName };\n } else if (origins.length > 1) {\n outputDependencies[propName] = origins.map((id) => ({ id, output: propName }));\n }\n }\n }\n\n appendItems.push({\n id: outputTaskId,\n type: \"OutputTask\",\n config: {\n inputSchema: strippedOutputSchema,\n outputSchema: strippedOutputSchema,\n },\n ...(Object.keys(outputDependencies).length > 0 ? { dependencies: outputDependencies } : {}),\n });\n }\n\n return [...prependItems, ...items, ...appendItems];\n}\n\nconst TYPED_ARRAY_FORMAT_PREFIX = \"TypedArray\";\n\n/**\n * Returns true if the given JSON schema (or any nested schema) has a format\n * string starting with \"TypedArray\" (e.g. \"TypedArray\" or \"TypedArray:Float32Array\").\n * Walks oneOf/anyOf wrappers and array items.\n */\nfunction schemaHasTypedArrayFormat(schema: JsonSchema): boolean {\n if (typeof schema === \"boolean\") return false;\n if (!schema || typeof schema !== \"object\" || Array.isArray(schema)) return false;\n\n const s = schema as Record<string, unknown>;\n if (typeof s.format === \"string\" && s.format.startsWith(TYPED_ARRAY_FORMAT_PREFIX)) {\n return true;\n }\n\n const checkUnion = (schemas: unknown): boolean => {\n if (!Array.isArray(schemas)) return false;\n return schemas.some((sub) => schemaHasTypedArrayFormat(sub as JsonSchema));\n };\n if (checkUnion(s.oneOf) || checkUnion(s.anyOf)) return true;\n\n const items = s.items;\n if (items && typeof items === \"object\" && !Array.isArray(items)) {\n if (schemaHasTypedArrayFormat(items as JsonSchema)) return true;\n }\n\n return false;\n}\n\n/**\n * Returns true if the task's output schema has any port with TypedArray format.\n * Used by adaptive workflow methods to choose scalar vs vector task variant.\n */\nexport function hasVectorOutput(task: ITask): boolean {\n const outputSchema = task.outputSchema();\n if (typeof outputSchema === \"boolean\" || !outputSchema?.properties) return false;\n return Object.values(outputSchema.properties).some((prop) =>\n schemaHasTypedArrayFormat(prop as JsonSchema)\n );\n}\n\n/**\n * Returns true if the input object looks like vector task input: has a \"vectors\"\n * property that is an array with at least one TypedArray element. Used by\n * adaptive workflow methods so that e.g. sum({ vectors: [new Float32Array(...)] })\n * chooses the vector variant even with no previous task.\n */\nexport function hasVectorLikeInput(input: unknown): boolean {\n if (!input || typeof input !== \"object\") return false;\n const v = (input as Record<string, unknown>).vectors;\n return (\n Array.isArray(v) &&\n v.length > 0 &&\n typeof v[0] === \"object\" &&\n v[0] !== null &&\n ArrayBuffer.isView(v[0])\n );\n}\n\n/**\n * Updates InputTask/OutputTask config schemas based on their connected dataflows.\n * InputTask schema reflects its outgoing dataflow targets' input schemas.\n * OutputTask schema reflects its incoming dataflow sources' output schemas.\n */\nexport function updateBoundaryTaskSchemas(graph: TaskGraph): void {\n const tasks = graph.getTasks();\n\n for (const task of tasks) {\n if (task.type === \"InputTask\") {\n // If the schema is marked as fully manual (x-ui-manual at schema level),\n // skip edge-based regeneration — the user explicitly defined this schema.\n const existingConfig = (task as ITask).config;\n const existingSchema = existingConfig?.inputSchema ?? existingConfig?.outputSchema;\n if (\n existingSchema &&\n typeof existingSchema === \"object\" &&\n (existingSchema as Record<string, unknown>)[\"x-ui-manual\"] === true\n ) {\n continue;\n }\n\n const outgoing = graph.getTargetDataflows(task.id);\n if (outgoing.length === 0) continue;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const df of outgoing) {\n const targetTask = graph.getTask(df.targetTaskId);\n if (!targetTask) continue;\n const targetSchema = targetTask.inputSchema();\n if (typeof targetSchema === \"boolean\") continue;\n const prop = (targetSchema.properties as any)?.[df.targetTaskPortId];\n if (prop && typeof prop !== \"boolean\") {\n properties[df.sourceTaskPortId] = prop;\n if (targetSchema.required?.includes(df.targetTaskPortId)) {\n if (!required.includes(df.sourceTaskPortId)) {\n required.push(df.sourceTaskPortId);\n }\n }\n }\n }\n\n const schema = {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n } as DataPortSchema;\n\n // @ts-expect-error - config is readonly\n task.config = {\n ...task.config,\n inputSchema: schema,\n outputSchema: schema,\n };\n }\n\n if (task.type === \"OutputTask\") {\n const incoming = graph.getSourceDataflows(task.id);\n if (incoming.length === 0) continue;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const df of incoming) {\n const sourceTask = graph.getTask(df.sourceTaskId);\n if (!sourceTask) continue;\n const sourceSchema = sourceTask.outputSchema();\n if (typeof sourceSchema === \"boolean\") continue;\n let prop = (sourceSchema.properties as any)?.[df.sourceTaskPortId];\n let propRequired = sourceSchema.required?.includes(df.sourceTaskPortId) ?? false;\n\n // For passthrough tasks with additionalProperties (e.g. DebugLogTask),\n // the port won't appear in the static output schema. Trace back through\n // the passthrough task's own incoming dataflows to find the actual schema.\n if (\n !prop &&\n sourceSchema.additionalProperties === true &&\n (sourceTask.constructor as typeof Task).passthroughInputsToOutputs === true\n ) {\n const upstreamDfs = graph.getSourceDataflows(sourceTask.id);\n for (const udf of upstreamDfs) {\n if (udf.targetTaskPortId !== df.sourceTaskPortId) continue;\n const upstreamTask = graph.getTask(udf.sourceTaskId);\n if (!upstreamTask) continue;\n const upstreamSchema = upstreamTask.outputSchema();\n if (typeof upstreamSchema === \"boolean\") continue;\n prop = (upstreamSchema.properties as any)?.[udf.sourceTaskPortId];\n if (prop) {\n propRequired = upstreamSchema.required?.includes(udf.sourceTaskPortId) ?? false;\n break;\n }\n }\n }\n\n if (prop && typeof prop !== \"boolean\") {\n properties[df.targetTaskPortId] = prop;\n if (propRequired && !required.includes(df.targetTaskPortId)) {\n required.push(df.targetTaskPortId);\n }\n }\n }\n\n const schema = {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties: false,\n } as DataPortSchema;\n\n // @ts-expect-error - config is readonly\n task.config = {\n ...task.config,\n inputSchema: schema,\n outputSchema: schema,\n };\n }\n }\n}\n",
|
|
14
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ISpan } from \"@workglow/util\";\nimport { uuid4 } from \"@workglow/util\";\nimport type { IEntitlementEnforcer } from \"../task/EntitlementEnforcer\";\nimport type { TaskError, TaskGraphTimeoutError } from \"../task/TaskError\";\nimport type { TaskOutput } from \"../task/TaskTypes\";\n\n/**\n * @internal\n * Per-run mutable state for a single TaskGraphRunner.runGraph() invocation.\n * Built by TaskGraphRunner.handleStart(), discarded by handleComplete/Error/Abort.\n *\n * All long-lived state (graph, schedulers, registry, resourceScope, outputCache,\n * accumulateLeafOutputs) stays on the facade. RunContext only holds state that is\n * created at the start of a run and torn down when the run terminates.\n */\nexport class RunContext {\n readonly runId: string;\n readonly abortController: AbortController;\n readonly inProgressTasks: Map<unknown, Promise<TaskOutput>> = new Map();\n readonly inProgressFunctions: Map<unknown, Promise<void>> = new Map();\n readonly failedTaskErrors: Map<unknown, TaskError> = new Map();\n\n telemetrySpan?: ISpan;\n graphTimeoutTimer?: ReturnType<typeof setTimeout>;\n pendingGraphTimeoutError?: TaskGraphTimeoutError;\n activeEnforcer?: IEntitlementEnforcer;\n\n // Removes the parentSignal abort listener, if one was registered. Set in the\n // constructor when parentSignal is provided; called from dispose().\n private parentSignalCleanup?: () => void;\n\n constructor(parentSignal?: AbortSignal) {\n this.runId = uuid4();\n this.abortController = new AbortController();\n if (parentSignal) {\n // Listen first, then check — addEventListener on an already-aborted signal\n // does not fire, so checking .aborted after ensures we never miss an abort.\n // Pattern preserved from commit 4e50c99e.\n const onParentAbort = () => this.abortController.abort();\n parentSignal.addEventListener(\"abort\", onParentAbort, { once: true });\n this.parentSignalCleanup = () => parentSignal.removeEventListener(\"abort\", onParentAbort);\n if (parentSignal.aborted) {\n this.parentSignalCleanup();\n this.parentSignalCleanup = undefined;\n this.abortController.abort();\n }\n }\n }\n\n /**\n * Releases external listeners (parentSignal abort handler). Idempotent.\n * Called by terminal handlers (handleComplete/Error/Abort) so a parent abort\n * fired after this run completes does not re-trigger our abort path and emit\n * a duplicate terminal event.\n */\n dispose(): void {\n this.parentSignalCleanup?.();\n this.parentSignalCleanup = undefined;\n }\n}\n",
|
|
15
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport { ConditionalTask } from \"../task/ConditionalTask\";\nimport type { ITask } from \"../task/ITask\";\nimport { TaskError, TaskGraphTimeoutError } from \"../task/TaskError\";\nimport type { TaskInput, TaskOutput } from \"../task/TaskTypes\";\nimport { TaskStatus } from \"../task/TaskTypes\";\nimport type { EdgeMaterializer } from \"./EdgeMaterializer\";\nimport type { RunContext } from \"./RunContext\";\nimport type { TaskGraph, TaskGraphRunConfig } from \"./TaskGraph\";\nimport type { GraphResultArray, GraphSingleTaskResult, TaskGraphRunner } from \"./TaskGraphRunner\";\nimport { taskPrototypeHasOwnExecute } from \"./TaskGraphRunner\";\nimport type { ITaskGraphScheduler } from \"./TaskGraphScheduler\";\n\n/**\n * @internal\n * Run-loop coordinator. Drives task selection via processScheduler,\n * arms graph-level timeout, propagates disabled cascade, aggregates progress,\n * and pushes status to outgoing edges.\n *\n * Stateless across runs — all per-run state arrives via `ctx`.\n *\n * Holds a back-reference to the facade so runLoop can call facade.runTask().\n * This keeps runTask as the single per-task choreography point that wires\n * EdgeMaterializer + StreamPump + the integration with TaskRunner.\n */\nexport class RunScheduler {\n constructor(\n private readonly graph: TaskGraph,\n private readonly processScheduler: ITaskGraphScheduler,\n private readonly facade: TaskGraphRunner\n ) {}\n\n /**\n * Pushes the status of a task to its target edges\n * @param node The task that produced the status\n *\n * For ConditionalTask, this method handles selective dataflow status:\n * - Active branch dataflows get COMPLETED status\n * - Inactive branch dataflows get DISABLED status\n */\n pushStatusFromNodeToEdges(\n node: ITask,\n ctx: RunContext | undefined,\n status?: TaskStatus,\n graph: TaskGraph = this.graph\n ): void {\n if (!node?.config?.id) return;\n\n const dataflows = graph.getTargetDataflows(node.id);\n const effectiveStatus = status ?? node.status;\n\n // Check if this is a ConditionalTask with selective branching\n if (node instanceof ConditionalTask && effectiveStatus === TaskStatus.COMPLETED) {\n // Build a map of output port -> branch ID for lookup\n const branches = node.config.branches ?? [];\n const portToBranch = new Map<string, string>();\n for (const branch of branches) {\n portToBranch.set(branch.outputPort, branch.id);\n }\n\n const activeBranches = node.getActiveBranches();\n\n for (const dataflow of dataflows) {\n // Preserve FAILED edges (e.g. transform chain failure) rather than\n // overwriting with the source task's completion status.\n if (dataflow.status === TaskStatus.FAILED) continue;\n const branchId = portToBranch.get(dataflow.sourceTaskPortId);\n if (branchId !== undefined) {\n // This dataflow is from a branch port\n if (activeBranches.has(branchId)) {\n // Branch is active - dataflow gets completed status\n dataflow.setStatus(TaskStatus.COMPLETED);\n } else {\n // Branch is inactive - dataflow gets disabled status\n dataflow.setStatus(TaskStatus.DISABLED);\n }\n } else {\n // Not a branch port (e.g., _activeBranches metadata) - use normal status\n dataflow.setStatus(effectiveStatus);\n }\n }\n\n // Cascade disabled status to downstream tasks\n this.propagateDisabledStatus(ctx, graph);\n return;\n }\n\n // Default behavior for non-conditional tasks\n dataflows.forEach((dataflow) => {\n // Preserve FAILED edges (e.g. transform chain failure) rather than\n // overwriting with the source task's completion status.\n if (dataflow.status === TaskStatus.FAILED) return;\n dataflow.setStatus(effectiveStatus);\n });\n }\n\n /**\n * Propagates DISABLED status through the graph.\n *\n * When a task's ALL incoming dataflows are DISABLED, that task becomes unreachable\n * and should also be disabled. This cascades through the graph until no more\n * tasks can be disabled.\n *\n * This is used by ConditionalTask to disable downstream tasks on inactive branches.\n *\n * `_ctx` is accepted for symmetry with other RunScheduler methods (which thread\n * per-run state through the RunContext) and to leave room for future per-run\n * scheduling state without a signature change. Currently unused — the cascade\n * operates on graph-level task status alone.\n */\n propagateDisabledStatus(_ctx: RunContext | undefined, graph: TaskGraph = this.graph): void {\n let changed = true;\n\n // Keep iterating until no more changes (fixed-point iteration)\n while (changed) {\n changed = false;\n\n for (const task of graph.getTasks()) {\n // Only consider tasks that are still pending\n if (task.status !== TaskStatus.PENDING) {\n continue;\n }\n\n const incomingDataflows = graph.getSourceDataflows(task.id);\n\n // Skip tasks with no incoming dataflows (root tasks)\n if (incomingDataflows.length === 0) {\n continue;\n }\n\n // Check if ALL incoming dataflows are DISABLED\n const allDisabled = incomingDataflows.every((df) => df.status === TaskStatus.DISABLED);\n\n if (allDisabled) {\n // This task is unreachable - disable it synchronously\n // Set status directly to avoid async issues\n task.status = TaskStatus.DISABLED;\n task.progress = 100;\n task.completedAt = new Date();\n task.emit(\"disabled\");\n task.emit(\"status\", task.status);\n\n // Propagate disabled status to its outgoing dataflows\n graph.getTargetDataflows(task.id).forEach((dataflow) => {\n dataflow.setStatus(TaskStatus.DISABLED);\n });\n\n // Mark as completed in scheduler so it doesn't wait for this task\n this.processScheduler.onTaskCompleted(task.id);\n\n changed = true;\n }\n }\n }\n }\n\n /**\n * Handles progress updates for the task graph by averaging `progress` across tasks whose class\n * declares its own `execute` (see {@link taskPrototypeHasOwnExecute}). Other nodes are ignored.\n */\n async handleProgress(\n ctx: RunContext,\n task: ITask,\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ): Promise<void> {\n const contributors = this.graph.getTasks().filter(taskPrototypeHasOwnExecute);\n if (contributors.length > 1) {\n const determinate = contributors.filter((t) => t.progress !== undefined);\n if (determinate.length === 0) {\n progress = undefined;\n } else {\n const sum = determinate.reduce((acc, t) => acc + t.progress!, 0);\n progress = Math.round(sum / determinate.length);\n }\n } else if (contributors.length === 1) {\n const [only] = contributors;\n progress = only.progress;\n }\n this.pushStatusFromNodeToEdges(task, ctx);\n // Emit aggregate progress before awaiting output push so UIs (and task `emit(\"progress\")` in\n // TaskRunner) are not blocked when pushOutput/narrowInput is slow or stalls mid-run.\n this.graph.emit(\"graph_progress\", progress, message, args);\n // Only push output for mid-run progress ticks while the task is actively executing.\n // Terminal-state handlers (complete, abort, error, disable) set task.status to their\n // terminal value before calling handleProgress(100), so the output push is skipped here —\n // the graph runner's own post-run pushOutputFromNodeToEdges handles the completed case.\n const isActive = task.status === TaskStatus.PROCESSING || task.status === TaskStatus.STREAMING;\n if (isActive && task.runOutputData && Object.keys(task.runOutputData).length > 0) {\n // Bracket access keeps `edgeMaterializer` protected on the facade — only `runScheduler` was widened to public.\n await this.facade[\"edgeMaterializer\"].pushOutputFromNodeToEdges(task, task.runOutputData);\n }\n }\n\n /**\n * Arms the graph-level timeout. The timer fires `pendingGraphTimeoutError`\n * and aborts the run when elapsed. No-op when `timeoutMs <= 0`.\n *\n * @remarks Treats `timeoutMs <= 0` as \"no timeout\" (silent no-op), not as\n * \"fire immediately\". Callers that want immediate cancellation should call\n * `ctx.abortController.abort()` directly.\n */\n armGraphTimeout(timeoutMs: number, ctx: RunContext): void {\n if (timeoutMs <= 0) return;\n ctx.pendingGraphTimeoutError = undefined;\n ctx.graphTimeoutTimer = setTimeout(() => {\n ctx.pendingGraphTimeoutError = new TaskGraphTimeoutError(timeoutMs);\n ctx.abortController.abort();\n }, timeoutMs);\n }\n\n /**\n * Clears the graph-level timeout timer if active.\n */\n clearGraphTimeout(ctx: RunContext): void {\n if (ctx.graphTimeoutTimer !== undefined) {\n clearTimeout(ctx.graphTimeoutTimer);\n ctx.graphTimeoutTimer = undefined;\n }\n }\n\n /**\n * Inner for-await loop body of {@link TaskGraphRunner.runGraph}. Drives the\n * processScheduler, dispatches tasks via `facade.runTask`, routes errors,\n * and pushes status/error to outgoing edges. Returns the per-leaf results\n * (terminal-state precedence is the facade's responsibility).\n */\n async runLoop<O extends TaskOutput>(\n input: TaskInput,\n config: TaskGraphRunConfig | undefined,\n ctx: RunContext,\n edgeMat: EdgeMaterializer\n ): Promise<GraphResultArray<O>> {\n const results: GraphResultArray<O> = [];\n\n try {\n // TODO: A different graph runner may chunk tasks that are in parallel\n // rather them all currently available\n for await (const task of this.processScheduler.tasks()) {\n if (ctx.abortController.signal.aborted) {\n break;\n }\n\n if (ctx.failedTaskErrors.size > 0) {\n break;\n }\n\n const isRootTask = this.graph.getSourceDataflows(task.id).length === 0;\n\n const runAsync = async () => {\n let errorRouted = false;\n try {\n // Root tasks (no incoming dataflows) receive the graph run input so e.g.\n // InputTask can seed the graph. Downstream tasks rely only on dataflow\n // edges plus task defaults — unless matchAllEmptyInputs is true, in which case\n // we filter the input to only include properties that are not connected via dataflows.\n const taskInput = isRootTask\n ? input\n : config?.matchAllEmptyInputs\n ? edgeMat.filterInputForTask(task, input)\n : {};\n\n // Bracket access — runTask stays protected on purpose; this is the back-ref entry point.\n const taskPromise = this.facade[\"runTask\"](task, taskInput);\n ctx.inProgressTasks.set(task.id, taskPromise);\n const taskResult = await taskPromise;\n\n if (this.graph.getTargetDataflows(task.id).length === 0) {\n // we save the results of all the leaves\n results.push(taskResult as GraphSingleTaskResult<O>);\n }\n } catch (error) {\n if (edgeMat.hasErrorOutputEdges(task)) {\n // Route the error through error-port dataflows instead of failing the graph.\n // pushErrorOutputToEdges sets edge statuses directly (COMPLETED for error\n // edges, DISABLED for normal edges), so we skip the normal status push.\n errorRouted = true;\n edgeMat.pushErrorOutputToEdges(task);\n } else {\n ctx.failedTaskErrors.set(task.id, error as TaskError);\n }\n } finally {\n // IMPORTANT: Push status to edges BEFORE notifying scheduler\n // This ensures dataflow statuses (including DISABLED) are set\n // before the scheduler checks which tasks are ready.\n // Skip normal status push when error routing already set edge statuses.\n if (!errorRouted) {\n this.pushStatusFromNodeToEdges(task, ctx);\n edgeMat.pushErrorFromNodeToEdges(task);\n }\n this.processScheduler.onTaskCompleted(task.id);\n }\n };\n\n // Start task execution without awaiting\n // so we can have many tasks running in parallel\n // but keep track of them to make sure they get awaited\n // otherwise, things will finish after this promise is resolved\n ctx.inProgressFunctions.set(Symbol(task.id as string), runAsync());\n }\n } catch (err) {\n getLogger().error(\"Error running graph\", { error: err });\n }\n\n // Wait for all tasks to complete since we did not await runAsync()/this.runTaskWithProvenance()\n await Promise.allSettled(Array.from(ctx.inProgressTasks.values()));\n // Clean up stragglers to avoid unhandled promise rejections\n await Promise.allSettled(Array.from(ctx.inProgressFunctions.values()));\n\n return results;\n }\n}\n",
|
|
16
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport type { UIConditionConfig } from \"./ConditionUtils\";\nimport { evaluateCondition, getNestedValue } from \"./ConditionUtils\";\nimport type { IExecuteContext } from \"./ITask\";\nimport { Task } from \"./Task\";\nimport type { TaskConfig, TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\nimport { TaskConfigSchema } from \"./TaskTypes\";\n\n/**\n * A predicate function that evaluates whether a branch condition is met.\n * Returns true if the branch should be active.\n */\nexport type ConditionFn<Input> = (input: Input) => boolean;\n\n/**\n * Configuration for a single branch in a ConditionalTask. When `condition`\n * returns true, the branch becomes active and its output port receives the\n * task's input data.\n */\nexport interface BranchConfig<Input> {\n readonly id: string;\n readonly condition: ConditionFn<Input>;\n /** Name of the output port that will receive data when this branch is active */\n readonly outputPort: string;\n}\n\nexport const conditionalTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...TaskConfigSchema[\"properties\"],\n branches: { type: \"array\", items: {} },\n defaultBranch: { type: \"string\" },\n exclusive: { type: \"boolean\" },\n conditionConfig: { type: \"object\", additionalProperties: true },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type ConditionalTaskConfig = TaskConfig & {\n /** Branches may contain ConditionFn functions — not JSON-schema-representable */\n readonly branches?: BranchConfig<any>[];\n readonly defaultBranch?: string;\n readonly exclusive?: boolean;\n /** Serializable UI condition configuration used to build branches at runtime. */\n readonly conditionConfig?: UIConditionConfig;\n};\n\n/**\n * A task that evaluates conditions to determine which downstream paths are active.\n *\n * Implements conditional branching within a task graph (if/then/else or switch/case).\n * In exclusive mode (default), branches are evaluated in order and only the first\n * match activates. In multi-path mode, all matching branches activate simultaneously.\n * Inactive branches DISABLE their outgoing dataflows, cascading to downstream tasks\n * with no other active inputs.\n */\nexport class ConditionalTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends ConditionalTaskConfig = ConditionalTaskConfig,\n> extends Task<Input, Output, Config> {\n static override type: TaskTypeName = \"ConditionalTask\";\n static override category = \"Flow Control\";\n static override title = \"Condition\";\n static override description = \"Route data based on conditions\";\n static override hasDynamicSchemas: boolean = true;\n\n public static override configSchema(): DataPortSchema {\n return conditionalTaskConfigSchema;\n }\n\n public override canSerializeConfig(): boolean {\n if (!this.config.branches) return true;\n return !this.config.branches.some((b) => typeof b.condition === \"function\");\n }\n\n /**\n * Set of branch IDs that are currently active after execution.\n * Populated during execute() and used by the graph runner to\n * determine which dataflows should be enabled vs disabled.\n */\n public activeBranches: Set<string> = new Set();\n\n // ========================================================================\n // Execution methods\n // ========================================================================\n\n /**\n * Builds runtime branch configs from serialized UI condition config.\n */\n private buildBranchesFromConditionConfig(\n conditionConfig: UIConditionConfig\n ): BranchConfig<Input>[] {\n if (!conditionConfig?.branches || conditionConfig.branches.length === 0) {\n return [\n {\n id: \"default\",\n condition: () => true,\n outputPort: \"1\",\n },\n ];\n }\n\n return conditionConfig.branches.map((branch, index) => ({\n id: branch.id,\n outputPort: String(index + 1),\n condition: (inputData: Input): boolean => {\n const fieldValue = getNestedValue(inputData as Record<string, unknown>, branch.field);\n return evaluateCondition(fieldValue, branch.operator, branch.value);\n },\n }));\n }\n\n /**\n * Resolves the effective branches to evaluate.\n * Uses config.branches if they have condition functions,\n * otherwise falls back to conditionConfig from input or extras.\n */\n private resolveBranches(input: Input): {\n branches: BranchConfig<Input>[];\n isExclusive: boolean;\n defaultBranch: string | undefined;\n fromConditionConfig: boolean;\n } {\n const configBranches = this.config.branches ?? [];\n\n // If config branches have condition functions, use them directly\n if (configBranches.length > 0 && typeof configBranches[0].condition === \"function\") {\n return {\n branches: configBranches,\n isExclusive: this.config.exclusive ?? true,\n defaultBranch: this.config.defaultBranch,\n fromConditionConfig: false,\n };\n }\n\n // Try to find serialized conditionConfig from input or config\n const conditionConfig =\n ((input as Record<string, unknown>).conditionConfig as UIConditionConfig | undefined) ??\n this.config.conditionConfig;\n\n if (conditionConfig) {\n return {\n branches: this.buildBranchesFromConditionConfig(conditionConfig),\n isExclusive: conditionConfig.exclusive ?? true,\n defaultBranch: conditionConfig.defaultBranch,\n fromConditionConfig: true,\n };\n }\n\n // Fallback: use config branches even if they lack conditions\n return {\n branches: configBranches,\n isExclusive: this.config.exclusive ?? true,\n defaultBranch: this.config.defaultBranch,\n fromConditionConfig: false,\n };\n }\n\n public override async execute(\n input: Input,\n context: IExecuteContext\n ): Promise<Output | undefined> {\n if (context.signal?.aborted) {\n return undefined;\n }\n\n // Clear previous branch activation state\n this.activeBranches.clear();\n\n const { branches, isExclusive, defaultBranch, fromConditionConfig } =\n this.resolveBranches(input);\n\n // Evaluate each branch condition\n for (const branch of branches) {\n try {\n const isActive = branch.condition(input);\n if (isActive) {\n this.activeBranches.add(branch.id);\n if (isExclusive) {\n // In exclusive mode, stop at first match\n break;\n }\n }\n } catch (error) {\n // If condition throws, treat it as false (branch not taken)\n getLogger().error(`Condition evaluation failed for branch \"${branch.id}\":`, { error });\n }\n }\n\n // If no branch matched and there's a default, use it\n if (this.activeBranches.size === 0 && defaultBranch) {\n const defaultBranchExists = branches.some((b) => b.id === defaultBranch);\n if (defaultBranchExists) {\n this.activeBranches.add(defaultBranch);\n }\n }\n\n // Build output: if from conditionConfig, use the UI-style output building\n if (fromConditionConfig) {\n return this.buildConditionConfigOutput(input, branches, isExclusive);\n }\n\n // Build output: pass through input to active branch ports\n return this.buildOutput(input);\n }\n\n /**\n * Builds output in the UI-style format where inputs are passed through\n * with numbered suffixes based on matched branches.\n */\n protected buildConditionConfigOutput(\n input: Input,\n branches: BranchConfig<Input>[],\n isExclusive: boolean\n ): Output {\n const output: Record<string, unknown> = {};\n\n // Remove conditionConfig from pass-through data\n const { conditionConfig, ...passThrough } = input as Record<string, unknown>;\n const inputKeys = Object.keys(passThrough);\n\n // Find matched branch number\n let matchedBranchNumber: number | null = null;\n for (let i = 0; i < branches.length; i++) {\n if (this.activeBranches.has(branches[i].id)) {\n if (matchedBranchNumber === null) {\n matchedBranchNumber = i + 1;\n }\n }\n }\n\n if (isExclusive) {\n if (matchedBranchNumber !== null) {\n for (const key of inputKeys) {\n output[`${key}_${matchedBranchNumber}`] = passThrough[key];\n }\n } else {\n for (const key of inputKeys) {\n output[`${key}_else`] = passThrough[key];\n }\n }\n } else {\n for (let i = 0; i < branches.length; i++) {\n if (this.activeBranches.has(branches[i].id)) {\n for (const key of inputKeys) {\n output[`${key}_${i + 1}`] = passThrough[key];\n }\n }\n }\n }\n\n return output as Output;\n }\n\n /**\n * Builds the output object with data routed to active branch ports.\n * Each active branch's output port receives the full input data.\n *\n * @param input - The input data to pass through to active branches\n * @returns Output object with active branch ports populated\n */\n protected buildOutput(input: Input): Output {\n const output: Record<string, unknown> = {\n _activeBranches: Array.from(this.activeBranches),\n };\n\n const branches = this.config.branches ?? [];\n\n // For each active branch, populate its output port with the input data\n for (const branch of branches) {\n if (this.activeBranches.has(branch.id)) {\n // Pass through all input properties to the active branch's output port\n output[branch.outputPort] = { ...input };\n }\n }\n\n return output as Output;\n }\n\n // ========================================================================\n // Branch information methods\n // ========================================================================\n\n public isBranchActive(branchId: string): boolean {\n return this.activeBranches.has(branchId);\n }\n\n /** Returns a copy to prevent external modification. */\n public getActiveBranches(): Set<string> {\n return new Set(this.activeBranches);\n }\n\n public getPortActiveStatus(): Map<string, boolean> {\n const status = new Map<string, boolean>();\n const branches = this.config.branches ?? [];\n\n for (const branch of branches) {\n status.set(branch.outputPort, this.activeBranches.has(branch.id));\n }\n\n return status;\n }\n\n // ========================================================================\n // Schema methods\n // ========================================================================\n\n static override outputSchema(): DataPortSchema {\n // Base schema - actual properties are determined by branch configuration\n return {\n type: \"object\",\n properties: {\n _activeBranches: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"List of active branch IDs after condition evaluation\",\n },\n },\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n }\n\n override outputSchema(): DataPortSchema {\n const branches = this.config?.branches ?? [];\n const properties: Record<string, any> = {\n _activeBranches: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"List of active branch IDs after condition evaluation\",\n },\n };\n\n // Add each branch's output port to the schema\n for (const branch of branches) {\n properties[branch.outputPort] = {\n type: \"object\",\n description: `Output for branch \"${branch.id}\" when active`,\n additionalProperties: true,\n };\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: false,\n } as DataPortSchema;\n }\n\n static override inputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n }\n\n override inputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n }\n}\n",
|
|
17
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Comparison operators supported by the UI condition builder.\n */\nexport type ComparisonOperator =\n | \"equals\"\n | \"not_equals\"\n | \"greater_than\"\n | \"greater_or_equal\"\n | \"less_than\"\n | \"less_or_equal\"\n | \"contains\"\n | \"starts_with\"\n | \"ends_with\"\n | \"is_empty\"\n | \"is_not_empty\"\n | \"is_true\"\n | \"is_false\";\n\n/**\n * Serialized condition branch configuration from the UI builder.\n * Used by ConditionalTask to auto-build runtime condition functions.\n */\nexport interface UIConditionBranch {\n id: string;\n field: string;\n operator: ComparisonOperator;\n value: string;\n}\n\n/**\n * Serialized condition configuration from the UI builder.\n * Used by ConditionalTask to auto-build runtime branch configs.\n */\nexport interface UIConditionConfig {\n branches: UIConditionBranch[];\n exclusive: boolean;\n defaultBranch?: string;\n}\n\n/**\n * Evaluates a condition based on operator type.\n *\n * @param fieldValue - The value of the field being tested\n * @param operator - The comparison operator to apply\n * @param compareValue - The value to compare against (always a string from the UI)\n * @returns true if the condition is met, false otherwise\n */\nexport function evaluateCondition(\n fieldValue: unknown,\n operator: ComparisonOperator,\n compareValue: string\n): boolean {\n // Handle null/undefined\n if (fieldValue === null || fieldValue === undefined) {\n switch (operator) {\n case \"is_empty\":\n return true;\n case \"is_not_empty\":\n return false;\n case \"is_true\":\n return false;\n case \"is_false\":\n return true;\n default:\n return false;\n }\n }\n\n const strValue = String(fieldValue);\n const numValue = Number(fieldValue);\n\n switch (operator) {\n case \"equals\":\n // Try numeric comparison first, then string\n if (!isNaN(numValue) && !isNaN(Number(compareValue))) {\n return numValue === Number(compareValue);\n }\n return strValue === compareValue;\n\n case \"not_equals\":\n if (!isNaN(numValue) && !isNaN(Number(compareValue))) {\n return numValue !== Number(compareValue);\n }\n return strValue !== compareValue;\n\n case \"greater_than\":\n return numValue > Number(compareValue);\n\n case \"greater_or_equal\":\n return numValue >= Number(compareValue);\n\n case \"less_than\":\n return numValue < Number(compareValue);\n\n case \"less_or_equal\":\n return numValue <= Number(compareValue);\n\n case \"contains\":\n return strValue.toLowerCase().includes(compareValue.toLowerCase());\n\n case \"starts_with\":\n return strValue.toLowerCase().startsWith(compareValue.toLowerCase());\n\n case \"ends_with\":\n return strValue.toLowerCase().endsWith(compareValue.toLowerCase());\n\n case \"is_empty\":\n return strValue === \"\" || (Array.isArray(fieldValue) && fieldValue.length === 0);\n\n case \"is_not_empty\":\n return strValue !== \"\" && !(Array.isArray(fieldValue) && fieldValue.length === 0);\n\n case \"is_true\":\n return Boolean(fieldValue) === true;\n\n case \"is_false\":\n return Boolean(fieldValue) === false;\n\n default:\n return false;\n }\n}\n\n/**\n * Get a value from a nested object using dot notation.\n * e.g., \"user.name\" would get obj.user.name\n *\n * @param obj - The object to read from\n * @param path - Dot-separated path to the value\n * @returns The value at the path, or undefined if any segment is missing\n */\nexport function getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== \"object\") {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n",
|
|
18
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { deepEqual, EventEmitter, uuid4 } from \"@workglow/util\";\nimport type { DataPortSchema, SchemaNode } from \"@workglow/util/schema\";\nimport { compileSchema } from \"@workglow/util/schema\";\nimport { type CachePolicy, DEFAULT_CACHE_POLICY } from \"../cache/CachePolicy\";\nimport { DATAFLOW_ALL_PORTS } from \"../task-graph/Dataflow\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport type { IExecuteContext, IExecutePreviewContext, IRunConfig, ITask } from \"./ITask\";\nimport { EMPTY_ENTITLEMENTS, type TaskEntitlements } from \"./TaskEntitlements\";\nimport {\n TaskAbortedError,\n TaskConfigurationError,\n TaskError,\n TaskInvalidInputError,\n TaskSerializationError,\n} from \"./TaskError\";\nimport type {\n TaskEventListener,\n TaskEventListeners,\n TaskEventParameters,\n TaskEvents,\n} from \"./TaskEvents\";\nimport type { JsonTaskItem, TaskGraphItemJson, TaskGraphJsonOptions } from \"./TaskJSON\";\nimport { TaskRunner } from \"./TaskRunner\";\nimport type { TaskConfig, TaskIdType, TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\nimport { TaskConfigSchema, TaskStatus } from \"./TaskTypes\";\n\n/**\n * Base class for all tasks that implements the ITask interface.\n * This abstract class provides common functionality for both simple and compound tasks.\n *\n * The Task class is responsible for:\n * 1. Defining what a task is (inputs, outputs, configuration)\n * 2. Providing the execution logic (via execute and executePreview)\n * 3. Delegating the running logic to a TaskRunner\n */\nexport class Task<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends TaskConfig = TaskConfig,\n> implements ITask<Input, Output, Config> {\n // ========================================================================\n // Static properties - should be overridden by subclasses\n // ========================================================================\n\n public static type: TaskTypeName = \"Task\";\n\n public static category: string = \"Hidden\";\n\n public static title: string = \"\";\n\n public static description: string = \"\";\n\n public static cacheable: boolean = true;\n\n /**\n * Version number for this task class, used to bust the output cache when the task's\n * implementation changes. Increment when a change would produce different outputs for\n * the same inputs. Combined with ancestor versions via getCacheVersion().\n * Subclasses should override this when their execute() logic changes in a\n * backwards-incompatible way (different output for same input).\n */\n public static version: number = 1;\n\n /**\n * Default cache policy for this task class. Used by `getCachePolicy()` when the\n * task does not override the method. Subclasses with side effects should set\n * `{ kind: \"none\" }`; tasks producing non-deterministic-but-expensive outputs\n * (e.g., image generation without a seed) should set `{ kind: \"private\" }`.\n */\n public static cachePolicy: CachePolicy = { kind: \"deterministic\" };\n\n /**\n * Whether this task has dynamic input/output schemas that can change at runtime.\n * Tasks with dynamic schemas should override instance methods for inputSchema() and/or outputSchema()\n * and emit 'schemaChange' events when their schemas change.\n */\n public static hasDynamicSchemas: boolean = false;\n\n /**\n * When true, dynamically added input ports (via the universal \"Add Input\" handle in the builder)\n * are mirrored as output ports of the same name and type. Set this on pass-through tasks that\n * forward their additional inputs to their outputs unchanged.\n */\n public static passthroughInputsToOutputs: boolean = false;\n\n /**\n * When true, this task can be saved as a custom task with a preset configuration.\n * Tasks that have meaningful user-facing config options beyond the base fields should set this.\n */\n public static customizable: boolean = false;\n\n /**\n * When true, this task defines the graph's output. The graph runner will\n * collect results only from tasks with this flag when they exist among the\n * leaf nodes; otherwise it falls back to collecting from all leaves.\n */\n public static isGraphOutput: boolean = false;\n\n /**\n * When true, this task does no real work — it only forwards inputs to outputs\n * (e.g. `InputTask`, `OutputTask`). Such tasks are excluded from graph-level\n * progress averaging because they jump from 0% to 100% and would dilute the bar.\n */\n public static isPassthrough: boolean = false;\n\n /**\n * Whether this task has dynamic entitlements that can change at runtime.\n * Tasks with dynamic entitlements should override the instance entitlements() method\n * and emit 'entitlementChange' events when their entitlements change.\n */\n public static hasDynamicEntitlements: boolean = false;\n\n /**\n * Entitlements required by this task class.\n * Subclasses override to declare their permission requirements.\n */\n public static entitlements(): TaskEntitlements {\n return EMPTY_ENTITLEMENTS;\n }\n\n public static inputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n } as const satisfies DataPortSchema;\n }\n\n public static outputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n } as const satisfies DataPortSchema;\n }\n\n /**\n * Config schema for this task. Subclasses that add config properties MUST override this\n * and spread TaskConfigSchema[\"properties\"] into their own properties object.\n */\n public static configSchema(): DataPortSchema {\n return TaskConfigSchema;\n }\n\n // ========================================================================\n // Task Execution Methods - Core logic provided by subclasses\n // ========================================================================\n\n /**\n * The actual task execution logic for subclasses to override\n *\n * @param input The input to the task\n * @param config The configuration for the task\n * @throws TaskError if the task fails\n * @returns The output of the task or undefined if no changes\n */\n public async execute(_input: Input, context: IExecuteContext): Promise<Output | undefined> {\n if (context.signal?.aborted) {\n throw new TaskAbortedError(\"Task aborted\");\n }\n return undefined;\n }\n\n /**\n * Default implementation of executePreview that does nothing.\n * Subclasses should override this to provide actual preview functionality.\n *\n * This is generally for UI updating, and should be lightweight.\n * @param input The input to the task\n * @returns The preview output, or undefined for \"no preview update\"\n */\n public async executePreview(\n _input: Input,\n _context: IExecutePreviewContext\n ): Promise<Output | undefined> {\n return undefined;\n }\n\n // ========================================================================\n // TaskRunner delegation - Executes and manages the task\n // ========================================================================\n\n /**\n * The TaskGraph that owns this task, set by {@link TaskGraph#addTask}.\n * Used by {@link TaskRunner#runPreviewStream} to locate upstream tasks\n * and subscribe to their streaming events.\n */\n public parentGraph?: TaskGraph;\n\n protected _runner: TaskRunner<Input, Output, Config> | undefined;\n\n public get runner(): TaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new TaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n /**\n * Runs the task and returns the output\n * Delegates to the task runner\n *\n * @param overrides Optional input overrides\n * @param runConfig Optional per-call run configuration (merged with task's runConfig)\n * @throws TaskError if the task fails\n * @returns The task output\n */\n async run(overrides: Partial<Input> = {}, runConfig: Partial<IRunConfig> = {}): Promise<Output> {\n return this.runner.run(overrides, { ...this.runConfig, ...runConfig });\n }\n\n /**\n * Runs the task in preview mode. Delegates to the task runner.\n */\n public async runPreview(overrides: Partial<Input> = {}): Promise<Output> {\n return this.runner.runPreview(overrides);\n }\n\n public abort(): void {\n this.runner.abort();\n }\n\n public async disable(): Promise<void> {\n await this.runner.disable();\n }\n\n // ========================================================================\n // Static to Instance conversion methods\n // ========================================================================\n\n public inputSchema(): DataPortSchema {\n return (this.constructor as typeof Task).inputSchema();\n }\n\n public outputSchema(): DataPortSchema {\n return (this.constructor as typeof Task).outputSchema();\n }\n\n public configSchema(): DataPortSchema {\n return (this.constructor as typeof Task).configSchema();\n }\n\n /**\n * Gets entitlements for this task instance.\n * For tasks with dynamic entitlements, override this to compute based on config/state.\n */\n public entitlements(): TaskEntitlements {\n return (this.constructor as typeof Task).entitlements();\n }\n\n /**\n * Emits an entitlementChange event when the task's required entitlements change.\n * Call this from tasks with dynamic entitlements when their configuration changes\n * in a way that affects their entitlements.\n */\n protected emitEntitlementChange(entitlements?: TaskEntitlements): void {\n const final = entitlements ?? this.entitlements();\n this.emit(\"entitlementChange\", final);\n }\n\n public get type(): TaskTypeName {\n return (this.constructor as typeof Task).type;\n }\n\n public get category(): string {\n return (this.constructor as typeof Task).category;\n }\n\n public get title(): string {\n return this.config?.title ?? (this.constructor as typeof Task).title;\n }\n\n public get description(): string {\n return this.config?.description ?? (this.constructor as typeof Task).description;\n }\n\n /**\n * Whether this task instance is currently cacheable. Reads `runConfig.cacheable`\n * and `config.cacheable` first (per-instance overrides for back-compat), then\n * derives from `getCachePolicy(runInputData)`.\n *\n * Note: for tasks that override `getCachePolicy(inputs)` with input-dependent\n * logic (e.g., `AiImageOutputTask` returns `private` when seed is absent), the\n * value of `task.cacheable` can change as `runInputData` changes. Prefer calling\n * `getCachePolicy(inputs)` directly when you have explicit inputs.\n */\n public get cacheable(): boolean {\n if (this.runConfig?.cacheable !== undefined) return this.runConfig.cacheable;\n if (this.config?.cacheable !== undefined) return this.config.cacheable;\n return this.getCachePolicy((this.runInputData ?? {}) as unknown as Input).kind !== \"none\";\n }\n\n /**\n * Returns a dot-separated string of version numbers collected from each class in the\n * prototype chain (leaf first) that declares its own `version` static property.\n * Every class that owns a `version` contributes one segment, including the base Task\n * class. Returns \"1\" when called directly on a Task instance with no subclassing\n * (Task.version === 1 is the sole contributor).\n *\n * Use this as the cache-key version component: when any ancestor's version changes,\n * the combined string changes and the cached output is invalidated.\n */\n public getCacheVersion(): string {\n const versions: number[] = [];\n let ctor: unknown = this.constructor;\n while (ctor && ctor !== Function.prototype) {\n if (\n Object.prototype.hasOwnProperty.call(ctor, \"version\") &&\n typeof (ctor as { version?: unknown }).version === \"number\"\n ) {\n versions.push((ctor as { version: number }).version);\n }\n ctor = Object.getPrototypeOf(ctor as object);\n }\n if (versions.length === 0) versions.push(1);\n return versions.join(\".\");\n }\n\n /**\n * Returns the effective cache policy for this task given its inputs.\n *\n * Resolution order:\n * 1. Per-instance `runConfig.cacheable === false` or `config.cacheable === false`\n * → `{ kind: \"none\" }` (callsite opt-out wins).\n * 2. Class-static `cacheable === false` (declared on the subclass) →\n * `{ kind: \"none\" }`. The coarse on/off flag remains supported alongside\n * the canonical `cachePolicy`; setting it on the class is equivalent\n * to declaring `static cachePolicy: CachePolicy = { kind: \"none\" }`.\n * 3. Class-static `cachePolicy` if declared.\n * 4. {@link DEFAULT_CACHE_POLICY}.\n *\n * Override for dynamic decisions (e.g., AiImageOutputTask returns `private`\n * when seed is absent).\n */\n public getCachePolicy(_inputs: Input): CachePolicy {\n const ctor = this.constructor as typeof Task;\n if (this.runConfig?.cacheable === false || this.config?.cacheable === false)\n return { kind: \"none\" };\n if (\n Object.prototype.hasOwnProperty.call(ctor, \"cacheable\") &&\n (ctor as { cacheable?: unknown }).cacheable === false &&\n !Object.prototype.hasOwnProperty.call(ctor, \"cachePolicy\")\n ) {\n return { kind: \"none\" };\n }\n return ctor.cachePolicy ?? DEFAULT_CACHE_POLICY;\n }\n\n // ========================================================================\n // Instance properties using @template types\n // ========================================================================\n\n /**\n * Default input values for this task.\n * If no overrides at run time, then this would be equal to the input.\n * resetInputData() will reset inputs to these defaults.\n */\n defaults: Record<string, any>;\n\n /**\n * The input to the task at the time of the task run.\n * This takes defaults from construction time and overrides from run time.\n * It is the input that created the output.\n */\n runInputData: Record<string, any> = {};\n\n /**\n * The output of the task at the time of the task run.\n * This is the result of the task execution.\n */\n runOutputData: Record<string, any> = {};\n\n // ========================================================================\n // Task state properties\n // ========================================================================\n\n config: Config;\n\n /**\n * Frozen snapshot of config at construction time, used by toJSON and\n * as the resolution source for re-runs (so fresh lookups use original IDs).\n */\n readonly originalConfig: Readonly<Record<string, unknown>> | undefined;\n\n public get id(): unknown {\n return this.config.id;\n }\n\n /**\n * Runtime configuration (not serialized with the task).\n * Set via the constructor's third argument or mutated by the graph runner.\n */\n runConfig: Partial<IRunConfig> = {};\n\n status: TaskStatus = TaskStatus.PENDING;\n\n /**\n * Current progress, 0..100 for measured progress, `undefined` for\n * indeterminate. Initialized to 0 (not started).\n */\n progress: number | undefined = 0;\n\n createdAt: Date = new Date();\n\n startedAt?: Date;\n\n completedAt?: Date;\n\n error?: TaskError;\n\n public get events(): EventEmitter<TaskEventListeners> {\n if (!this._events) {\n this._events = new EventEmitter<TaskEventListeners>();\n }\n return this._events;\n }\n protected _events: EventEmitter<TaskEventListeners> | undefined;\n\n /**\n * Creates a new task instance\n *\n * @param config Configuration for the task (includes defaults for input values)\n * @param runConfig Runtime configuration for the task\n */\n constructor(config: NoInfer<Partial<Config>> = {}, runConfig: NoInfer<Partial<IRunConfig>> = {}) {\n const { defaults: callerDefaultInputs, ...restConfig } = config as Partial<Config> & {\n defaults?: Partial<Input>;\n };\n\n const inputDefaults = this.getDefaultInputsFromStaticInputDefinitions();\n const mergedDefaults = Object.assign(inputDefaults, callerDefaultInputs ?? {});\n // Strip symbol properties (like [$JSONSchema]) before storing defaults\n this.defaults = this.stripSymbols(mergedDefaults) as Record<string, any>;\n this.resetInputData();\n\n const title = (this.constructor as typeof Task).title || undefined;\n const baseConfig = Object.assign(\n {\n ...(title ? { title } : {}),\n },\n restConfig\n ) as Config;\n if (baseConfig.id === undefined) {\n (baseConfig as Record<string, unknown>).id = uuid4();\n }\n this.config = this.validateAndApplyConfigDefaults(baseConfig);\n try {\n this.originalConfig = Object.freeze(structuredClone(this.config) as Record<string, unknown>);\n } catch {\n // Config contains non-cloneable values (e.g. functions).\n // canSerializeConfig() should return false for such tasks.\n this.originalConfig = undefined;\n }\n\n this.runConfig = runConfig;\n\n // Reject input schemas that declare a `__cv` port: this name is reserved by\n // CacheCoordinator.buildKey for the cache version sentinel. Allowing a task\n // to declare it would silently shadow cache versioning and cause cache\n // collisions across versions. `inputSchema()` can legally return a boolean\n // (see addInput/setInput handling); skip the check in that case.\n const inputSchema = (this.constructor as typeof Task).inputSchema();\n if (\n inputSchema &&\n typeof inputSchema !== \"boolean\" &&\n inputSchema.properties &&\n Object.prototype.hasOwnProperty.call(inputSchema.properties, \"__cv\")\n ) {\n throw new TaskConfigurationError(\n `Task \"${(this.constructor as typeof Task).type}\": input port name '__cv' is reserved ` +\n `for cache versioning. Rename the port to avoid collision with the cache key sentinel.`\n );\n }\n }\n\n // ========================================================================\n // Input/Output handling\n // ========================================================================\n\n getDefaultInputsFromStaticInputDefinitions(): Partial<Input> {\n const schema = this.inputSchema();\n if (typeof schema === \"boolean\") {\n return {};\n }\n try {\n const compiledSchema = this.getInputSchemaNode();\n const defaultData = compiledSchema.getData(undefined, {\n addOptionalProps: true,\n removeInvalidData: false,\n useTypeDefaults: false,\n });\n return (defaultData || {}) as Partial<Input>;\n } catch (error) {\n console.warn(\n `Failed to compile input schema for ${this.type}, falling back to manual extraction:`,\n error\n );\n // Fallback to manual extraction if compilation fails\n return Object.entries(schema.properties || {}).reduce<Record<string, any>>(\n (acc, [id, prop]) => {\n const defaultValue = (prop as any).default;\n if (defaultValue !== undefined) {\n acc[id] = defaultValue;\n }\n return acc;\n },\n {}\n ) as Partial<Input>;\n }\n }\n\n public resetInputData(): void {\n this.runInputData = this.smartClone(this.defaults) as Record<string, any>;\n }\n\n /**\n * Smart clone that deep-clones plain objects and arrays while preserving\n * class instances (objects with non-Object prototype) by reference.\n * Detects and throws an error on circular references.\n *\n * This is necessary because:\n * - structuredClone cannot clone class instances (methods are lost)\n * - JSON.parse/stringify loses methods and fails on circular references\n * - Class instances like repositories should be passed by reference\n *\n * This breaks the idea of everything being json serializable, but it allows\n * more efficient use cases. Do be careful with this though! Use sparingly.\n *\n * @param obj The object to clone\n * @param visited Set of objects in the current cloning path (for circular reference detection)\n * @returns A cloned object with class instances preserved by reference\n */\n private smartClone(obj: any, visited: WeakSet<object> = new WeakSet()): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n // Primitives (string, number, boolean, symbol, bigint) are returned as-is\n if (typeof obj !== \"object\") {\n return obj;\n }\n\n // Check for circular references\n if (visited.has(obj)) {\n throw new TaskConfigurationError(\n \"Circular reference detected in input data. \" +\n \"Cannot clone objects with circular references.\"\n );\n }\n\n // Clone TypedArrays (Float32Array, Int8Array, etc.) to avoid shared-mutation\n // between defaults and runInputData, while preserving DataView by reference.\n if (ArrayBuffer.isView(obj)) {\n // Preserve DataView instances by reference (constructor signature differs)\n if (typeof DataView !== \"undefined\" && obj instanceof DataView) {\n return obj;\n }\n // For TypedArrays, create a new instance with the same data\n const typedArray = obj as any;\n return new (typedArray.constructor as any)(typedArray);\n }\n\n // Preserve class instances (objects with non-Object/non-Array prototype)\n // This includes repository instances, custom classes, etc.\n if (!Array.isArray(obj)) {\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) {\n return obj; // Pass by reference\n }\n }\n\n // Add object to visited set before recursing\n visited.add(obj);\n\n try {\n // Deep clone arrays, preserving class instances within\n if (Array.isArray(obj)) {\n return obj.map((item) => this.smartClone(item, visited));\n }\n\n // Deep clone plain objects\n const result: Record<string, any> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = this.smartClone(obj[key], visited);\n }\n }\n return result;\n } finally {\n // Remove from visited set after processing to allow the same object\n // in different branches (non-circular references)\n visited.delete(obj);\n }\n }\n\n public setDefaults(defaults: Partial<Input>): void {\n // Strip symbol properties (like [$JSONSchema]) before storing defaults\n this.defaults = this.stripSymbols(defaults) as Partial<Input>;\n }\n\n public setInput(input: Partial<Input>): void {\n const schema = this.inputSchema();\n if (typeof schema === \"boolean\") {\n if (schema === true) {\n for (const [inputId, value] of Object.entries(input)) {\n if (value !== undefined) {\n this.runInputData[inputId] = value;\n }\n }\n }\n return;\n }\n const properties = schema.properties || {};\n\n for (const [inputId, prop] of Object.entries(properties)) {\n if (input[inputId] !== undefined) {\n this.runInputData[inputId] = input[inputId];\n } else if (\n this.runInputData[inputId] === undefined &&\n (prop as { default?: unknown }).default !== undefined\n ) {\n this.runInputData[inputId] = prop.default;\n }\n }\n\n // If additionalProperties is true, also copy any additional input properties\n if (schema.additionalProperties) {\n for (const [inputId, value] of Object.entries(input)) {\n if (!(inputId in properties)) {\n this.runInputData[inputId] = value;\n }\n }\n }\n }\n\n /**\n * Adds/merges input data during graph execution.\n * Unlike {@link setInput}, this method:\n * - Detects changes using deep equality\n * - Accumulates array values (appends rather than replaces)\n * - Handles DATAFLOW_ALL_PORTS for pass-through\n * - Handles additionalProperties for dynamic schemas\n *\n * @param overrides The input data to merge\n * @returns true if any input data was changed, false otherwise\n */\n public addInput(overrides: Partial<Input> | undefined): boolean {\n if (!overrides) return false;\n\n let changed = false;\n const inputSchema = this.inputSchema();\n\n if (typeof inputSchema === \"boolean\") {\n if (inputSchema === false) {\n return false;\n }\n // Schema is `true` - accept any input\n for (const [key, value] of Object.entries(overrides)) {\n if (!deepEqual(this.runInputData[key], value)) {\n this.runInputData[key] = value;\n changed = true;\n }\n }\n return changed;\n }\n\n const properties = inputSchema.properties || {};\n\n for (const [inputId, prop] of Object.entries(properties)) {\n if (inputId === DATAFLOW_ALL_PORTS) {\n this.runInputData = { ...this.runInputData, ...overrides };\n changed = true;\n } else {\n if (overrides[inputId] === undefined) continue;\n const isArray =\n (prop as any)?.type === \"array\" ||\n ((prop as any)?.type === \"any\" &&\n (Array.isArray(overrides[inputId]) || Array.isArray(this.runInputData[inputId])));\n\n if (isArray) {\n const existingItems = Array.isArray(this.runInputData[inputId])\n ? this.runInputData[inputId]\n : this.runInputData[inputId] !== undefined\n ? [this.runInputData[inputId]]\n : [];\n const newitems = [...existingItems];\n\n const overrideItem = overrides[inputId];\n if (Array.isArray(overrideItem)) {\n newitems.push(...overrideItem);\n } else {\n newitems.push(overrideItem);\n }\n this.runInputData[inputId] = newitems;\n changed = true;\n } else {\n if (!deepEqual(this.runInputData[inputId], overrides[inputId])) {\n this.runInputData[inputId] = overrides[inputId];\n changed = true;\n }\n }\n }\n }\n\n // If additionalProperties is true, also accept any additional input properties\n if (inputSchema.additionalProperties) {\n for (const [inputId, value] of Object.entries(overrides)) {\n if (!(inputId in properties)) {\n if (!deepEqual(this.runInputData[inputId], value)) {\n this.runInputData[inputId] = value;\n changed = true;\n }\n }\n }\n }\n\n return changed;\n }\n\n /**\n * Stub for narrowing input. Override in subclasses for custom logic.\n * @param input The input to narrow\n * @param _registry Optional service registry for lookups\n * @returns The (possibly narrowed) input\n */\n public async narrowInput(\n input: Partial<Input>,\n _registry: ServiceRegistry\n ): Promise<Partial<Input>> {\n return input;\n }\n\n // ========================================================================\n // Event handling methods\n // ========================================================================\n\n public subscribe<Event extends TaskEvents>(\n name: Event,\n fn: TaskEventListener<Event>\n ): () => void {\n return this.events.subscribe(name, fn);\n }\n\n public on<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n this.events.on(name, fn);\n }\n\n public off<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n this.events.off(name, fn);\n }\n\n public once<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n this.events.once(name, fn);\n }\n\n /**\n * Returns a promise that resolves when the specified event is emitted\n */\n public waitOn<Event extends TaskEvents>(name: Event): Promise<TaskEventParameters<Event>> {\n return this.events.waitOn(name) as Promise<TaskEventParameters<Event>>;\n }\n\n public emit<Event extends TaskEvents>(name: Event, ...args: TaskEventParameters<Event>): void {\n // Route through `events` so the emitter exists: `this._events?.emit` dropped progress when\n // nothing had accessed `task.events` yet (e.g. parent MapTask before CLI wired listeners).\n this.events.emit(name, ...args);\n }\n\n /**\n * Emits a schemaChange event when the task's input or output schema changes.\n * This should be called by tasks with dynamic schemas when their configuration\n * changes in a way that affects their schemas.\n *\n * @param inputSchema - The new input schema (optional, will use current schema if not provided)\n * @param outputSchema - The new output schema (optional, will use current schema if not provided)\n */\n protected emitSchemaChange(inputSchema?: DataPortSchema, outputSchema?: DataPortSchema): void {\n const finalInputSchema = inputSchema ?? this.inputSchema();\n const finalOutputSchema = outputSchema ?? this.outputSchema();\n this.emit(\"schemaChange\", finalInputSchema, finalOutputSchema);\n }\n\n // ========================================================================\n // Input validation methods\n // ========================================================================\n\n /**\n * Gets the compiled config schema node, or undefined if no configSchema is defined.\n *\n * The compiled schema is cached directly on the concrete class object (not in a shared\n * inherited Map) so that each subclass always uses its own configSchema() result.\n * A shared Map keyed only by type name can be poisoned if a different class computes\n * and caches the schema first — e.g., due to cross-package static-method resolution\n * inconsistencies in bundled outputs.\n */\n private static getConfigSchemaNode(): SchemaNode | undefined {\n const schema = this.configSchema();\n if (!schema) return undefined;\n // Use Object.hasOwn so each class gets its own entry rather than inheriting\n // from a parent class that already cached under the same key.\n if (!Object.hasOwn(this, \"__compiledConfigSchema\")) {\n try {\n const schemaNode =\n typeof schema === \"boolean\"\n ? compileSchema(schema ? {} : { not: {} })\n : compileSchema(schema);\n Object.defineProperty(this, \"__compiledConfigSchema\", {\n value: schemaNode,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n } catch (error) {\n console.warn(`Failed to compile config schema for ${this.type}:`, error);\n return undefined;\n }\n }\n return (this as any).__compiledConfigSchema as SchemaNode;\n }\n\n /**\n * Validates config against configSchema.\n * Returns config as-is; throws on validation errors.\n * Returns config as-is if no configSchema is defined.\n */\n private validateAndApplyConfigDefaults(config: Config): Config {\n const ctor = this.constructor as typeof Task;\n const schemaNode = ctor.getConfigSchemaNode();\n if (!schemaNode) return config;\n\n const result = schemaNode.validate(config);\n if (!result.valid) {\n const errorMessages = result.errors.map((e) => {\n const path = e.data?.pointer || \"\";\n return `${e.message}${path ? ` (${path})` : \"\"}`;\n });\n throw new TaskConfigurationError(\n `[${ctor.name}] Configuration Error: ${errorMessages.join(\", \")}`\n );\n }\n\n return config;\n }\n\n protected static generateInputSchemaNode(schema: DataPortSchema) {\n if (typeof schema === \"boolean\") {\n if (schema === false) {\n return compileSchema({ not: {} });\n }\n return compileSchema({});\n }\n return compileSchema(schema);\n }\n\n /**\n * Gets the compiled input schema, cached per class (not in a shared inherited Map).\n * Uses Object.hasOwn so each subclass stores its own compiled schema and never\n * picks up a stale entry cached by a different class with the same type name.\n */\n protected static getInputSchemaNode(): SchemaNode {\n if (!Object.hasOwn(this, \"__compiledInputSchema\")) {\n const dataPortSchema = this.inputSchema();\n const schemaNode = this.generateInputSchemaNode(dataPortSchema);\n try {\n Object.defineProperty(this, \"__compiledInputSchema\", {\n value: schemaNode,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n } catch (error) {\n // If compilation fails, fall back to accepting any object structure\n // This is a safety net for schemas that json-schema-library can't compile\n console.warn(\n `Failed to compile input schema for ${this.type}, falling back to permissive validation:`,\n error\n );\n Object.defineProperty(this, \"__compiledInputSchema\", {\n value: compileSchema({}),\n writable: true,\n configurable: true,\n enumerable: false,\n });\n }\n }\n return (this as any).__compiledInputSchema as SchemaNode;\n }\n\n protected getInputSchemaNode(): SchemaNode {\n return (this.constructor as typeof Task).getInputSchemaNode();\n }\n\n /**\n * Validates an input data object against the task's input schema\n */\n public async validateInput(input: Input): Promise<boolean> {\n if (typeof input !== \"object\" || input === null) {\n throw new TaskInvalidInputError(\"Input must be an object\");\n }\n const ctor = this.constructor as typeof Task;\n let schemaNode: SchemaNode;\n if (ctor.hasDynamicSchemas) {\n // Dynamic-schema tasks use instance inputSchema() (e.g. config.inputSchema), not the static fallback.\n // The cached getInputSchemaNode uses static inputSchema() which would reject valid instance-specific inputs.\n const instanceSchema = this.inputSchema();\n schemaNode = ctor.generateInputSchemaNode(instanceSchema);\n } else {\n schemaNode = this.getInputSchemaNode();\n }\n const result = schemaNode.validate(input);\n\n if (!result.valid) {\n const errorMessages = result.errors.map((e) => {\n const path = e.data.pointer || \"\";\n return `${e.message}${path ? ` (${path})` : \"\"}`;\n });\n const err = new TaskInvalidInputError(\n `Task \"${this.type}\" (${this.id}): Input ${JSON.stringify(Object.keys(input))} does not match schema: ${errorMessages.join(\", \")}`\n );\n err.taskType = this.type;\n err.taskId = this.id;\n throw err;\n }\n\n return true;\n }\n\n // ========================================================================\n // Serialization methods\n // ========================================================================\n\n /**\n * Strips symbol properties from an object to make it serializable\n * @param obj The object to strip symbols from\n * @returns A new object without symbol properties\n */\n private stripSymbols(obj: any): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n // Preserve TypedArrays (Float32Array, Int8Array, etc.)\n if (ArrayBuffer.isView(obj)) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => this.stripSymbols(item));\n }\n if (typeof obj === \"object\") {\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) {\n return obj;\n }\n\n const result: Record<string, any> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = this.stripSymbols(obj[key]);\n }\n }\n return result;\n }\n return obj;\n }\n\n /**\n * Returns whether the task's config can be serialized to JSON.\n * Override in subclasses that store non-serializable values (functions) in config.\n * Called by toJSON — if false, toJSON throws TaskSerializationError.\n */\n public canSerializeConfig(): boolean {\n return true;\n }\n\n /**\n * Serializes the task and its subtasks into a format that can be stored\n * @param _options Options controlling serialization (used by subclasses)\n * @returns The serialized task and subtasks\n */\n public toJSON(_options?: TaskGraphJsonOptions): TaskGraphItemJson {\n const ctor = this.constructor as typeof Task;\n\n if (!this.canSerializeConfig() || !this.originalConfig) {\n throw new TaskSerializationError(this.type);\n }\n\n // Build config by extracting only serializable properties defined in the configSchema.\n // We filter through the schema to avoid accidentally including non-serializable\n // values (e.g. functions like WhileTask.condition) or internal-only properties\n // that were never part of the serialized output and that consuming applications\n // don't expect (e.g. `queue` from task-specific configs).\n const schema = ctor.configSchema();\n const schemaProperties =\n typeof schema !== \"boolean\" && schema?.properties\n ? (schema.properties as Record<string, Record<string, unknown>>)\n : {};\n\n const config: Record<string, unknown> = {};\n for (const [key, propSchema] of Object.entries(schemaProperties)) {\n if (key === \"id\") continue;\n // Skip internal properties marked as hidden (e.g. queue, compoundMerge)\n // except inputSchema/outputSchema/extras which are needed for task reconstruction\n if (\n propSchema?.[\"x-ui-hidden\"] === true &&\n key !== \"inputSchema\" &&\n key !== \"outputSchema\" &&\n key !== \"extras\"\n ) {\n continue;\n }\n const value = (this.originalConfig as Record<string, unknown>)[key];\n if (value === undefined) continue;\n // Skip non-serializable values (functions, symbols, etc.)\n if (typeof value === \"function\" || typeof value === \"symbol\") continue;\n config[key] = value;\n }\n\n // Omit title/description when they match the static class defaults\n if (config.title === ctor.title) delete config.title;\n if (config.description === ctor.description) delete config.description;\n\n // Omit empty extras\n const extras = config.extras as Record<string, unknown> | undefined;\n if (!extras || Object.keys(extras).length === 0) delete config.extras;\n\n const base: TaskGraphItemJson = {\n id: this.id,\n type: this.type,\n defaults: this.defaults,\n };\n if (Object.keys(config).length > 0) {\n base.config = config;\n }\n\n return this.stripSymbols(base) as TaskGraphItemJson;\n }\n\n /**\n * Converts the task to a JSON format suitable for dependency tracking\n * @param options Options controlling serialization (used by subclasses)\n * @returns The task and subtasks in JSON thats easier for humans to read\n */\n public toDependencyJSON(options?: TaskGraphJsonOptions): JsonTaskItem {\n const json = this.toJSON(options);\n return json;\n }\n\n // ========================================================================\n // Internal graph methods\n // ========================================================================\n\n /**\n * Checks if the task has children. Useful to gate to use of the internal subGraph\n * as this will return without creating a new graph if graph is non-existent .\n *\n * @returns True if the task has children, otherwise false\n */\n public hasChildren(): boolean {\n return (\n this._subGraph !== undefined &&\n this._subGraph !== null &&\n this._subGraph.getTasks().length > 0\n );\n }\n\n private _taskAddedListener: (taskId: TaskIdType) => void = () => {\n this.emit(\"regenerate\");\n };\n\n /**\n * The internal task graph containing subtasks\n *\n * In the base case, these may just be incidental tasks that are not part of the task graph\n * but are used to manage the task's state as part of task execution. Therefore, the graph\n * is not used by the default runner.\n */\n protected _subGraph: TaskGraph | undefined = undefined;\n\n /**\n * Sets the subtask graph for the compound task\n * @param subGraph The subtask graph to set\n */\n set subGraph(subGraph: TaskGraph) {\n if (this._subGraph) {\n this._subGraph.off(\"task_added\", this._taskAddedListener);\n }\n this._subGraph = subGraph;\n this._subGraph.on(\"task_added\", this._taskAddedListener);\n }\n\n /**\n * The internal task graph containing subtasks\n *\n * In the base case, these may just be incidental tasks that are not part of the task graph\n * but are used to manage the task's state as part of task execution. Therefore, the graph\n * is not used by the default runner.\n *\n * Creates a new graph if one doesn't exist.\n *\n * @returns The task graph\n */\n get subGraph(): TaskGraph {\n if (!this._subGraph) {\n this._subGraph = new TaskGraph();\n this._subGraph.on(\"task_added\", this._taskAddedListener);\n }\n return this._subGraph;\n }\n\n /**\n * Regenerates the task graph, which is internal state to execute() with config.own()\n *\n * This is a destructive operation that removes all dataflows and tasks from the graph.\n * It is used to reset the graph to a clean state.\n *\n * GraphAsTask and others override this and do not call super\n */\n public regenerateGraph(): void {\n if (this.hasChildren()) {\n for (const dataflow of this.subGraph.getDataflows()) {\n this.subGraph.removeDataflow(dataflow);\n }\n for (const child of this.subGraph.getTasks()) {\n this.subGraph.removeTask(child.id);\n }\n }\n this.events.emit(\"regenerate\");\n }\n}\n\n/**\n * Test helper: clear the dedup Set so each test case can re-trigger the\n * one-time legacy-`cacheable` deprecation warning. Lives in production code\n * (not a __tests__ file) so it's reachable from outside the package's test\n * harness; the leading double-underscore signals \"do not rely on this in\n * application code\".\n */\nexport function __resetCacheableDeprecationWarnings(): void {\n (\n Task as unknown as { __cacheableDeprecationWarned: Set<string> }\n ).__cacheableDeprecationWarned.clear();\n}\n",
|
|
19
|
+
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type CachePolicy = { kind: \"deterministic\" } | { kind: \"private\" } | { kind: \"none\" };\n\nexport const DEFAULT_CACHE_POLICY: CachePolicy = { kind: \"deterministic\" };\n\nexport function isPolicyCached(policy: CachePolicy): boolean {\n return policy.kind !== \"none\";\n}\n\nexport function isPolicyPrivate(policy: CachePolicy): boolean {\n return policy.kind === \"private\";\n}\n",
|
|
14
20
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IDisposeStrategy, ResourceScope } from \"@workglow/util\";\nimport { EventEmitter, ServiceRegistry, uuid4 } from \"@workglow/util\";\nimport { DirectedAcyclicGraph } from \"@workglow/util/graph\";\nimport { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { ITask } from \"../task/ITask\";\nimport type { StreamEvent } from \"../task/StreamTypes\";\nimport type { TaskEntitlements } from \"../task/TaskEntitlements\";\nimport type { JsonTaskItem, TaskGraphJson, TaskGraphJsonOptions } from \"../task/TaskJSON\";\nimport type { TaskIdType, TaskInput, TaskOutput, TaskStatus } from \"../task/TaskTypes\";\nimport type { PipeFunction } from \"./Conversions\";\nimport { ensureTask } from \"./Conversions\";\nimport type { DataflowIdType } from \"./Dataflow\";\nimport { Dataflow } from \"./Dataflow\";\nimport { computeGraphEntitlements } from \"./GraphEntitlementUtils\";\nimport { addBoundaryNodesToDependencyJson, addBoundaryNodesToGraphJson } from \"./GraphSchemaUtils\";\nimport type { ITaskGraph } from \"./ITaskGraph\";\nimport {\n EventTaskGraphToDagMapping,\n GraphEventDagEvents,\n GraphEventDagParameters,\n TaskGraphEventListener,\n TaskGraphEvents,\n TaskGraphEventStatusParameters,\n TaskGraphStatusEvents,\n TaskGraphStatusListeners,\n} from \"./TaskGraphEvents\";\nimport type { GraphResultArray } from \"./TaskGraphRunner\";\nimport { CompoundMergeStrategy, GraphResult, TaskGraphRunner } from \"./TaskGraphRunner\";\n\n/**\n * Configuration for running a task graph\n */\nexport interface TaskGraphRunConfig {\n /** Optional output cache to use for this task graph */\n outputCache?: TaskOutputRepository | boolean;\n /** Optional if we should match all empty inputs with the graph input */\n matchAllEmptyInputs?: boolean;\n /** Optional signal to abort the task graph */\n parentSignal?: AbortSignal;\n /** Optional service registry to use for this task graph (creates child from global if not provided) */\n registry?: ServiceRegistry;\n /**\n * When true, streaming leaf tasks (no outgoing edges) accumulate their full\n * output so the workflow return value is complete. Defaults to true.\n * Pass false for subgraph runs where the parent handles streaming via\n * subscriptions and does not rely on the return value for stream data.\n */\n accumulateLeafOutputs?: boolean;\n /**\n * Maximum time in milliseconds for the entire graph execution.\n * When exceeded, all in-progress tasks are aborted and a TaskTimeoutError is thrown.\n */\n timeout?: number;\n /**\n * Maximum number of tasks allowed in the graph. Validated before execution starts.\n * Defaults to no limit. Set this to prevent runaway graph construction.\n */\n maxTasks?: number;\n /**\n * When true, check entitlements via the registered IEntitlementEnforcer before\n * graph execution begins. Throws TaskEntitlementError if any required (non-optional)\n * entitlements are denied. Default: false.\n */\n enforceEntitlements?: boolean;\n /**\n * Resource scope for collecting heavyweight resource disposers during graph\n * execution. Threaded to all tasks via IExecuteContext.\n *\n * If omitted, the top-level runner creates a private scope and `disposeAll()`s\n * it when the run finishes (success, error, or abort) — automatic cleanup for\n * casual callers.\n *\n * If provided, the caller owns the lifecycle; the runner never calls\n * `disposeAll`. Use this to share resources (e.g., a loaded AI model) across\n * multiple runs, then dispose at app shutdown.\n */\n resourceScope?: ResourceScope;\n\n /** Same semantics as on {@link IRunConfig}. */\n disposeStrategy?: IDisposeStrategy;\n\n /**\n * Stable identifier for this logical run. When provided, the graph runner\n * wraps the `private` cache slot in a {@link RunPrivateCacheRepo} keyed by\n * this value, so that a restarted run (same `runId`) can resume from cached\n * private outputs rather than re-executing every task.\n */\n runId?: string;\n}\n\nexport interface TaskGraphRunPreviewConfig extends Omit<\n TaskGraphRunConfig,\n \"enforceEntitlements\" | \"timeout\"\n> {\n /** Optional service registry to use for this task graph */\n registry?: ServiceRegistry;\n}\n\nclass TaskGraphDAG extends DirectedAcyclicGraph<\n ITask<any, any, any>,\n Dataflow,\n TaskIdType,\n DataflowIdType\n> {\n constructor() {\n super(\n (task: ITask<any, any, any>) => task.id,\n (dataflow: Dataflow) => dataflow.id\n );\n }\n}\n\ninterface TaskGraphConstructorConfig {\n outputCache?: TaskOutputRepository;\n dag?: TaskGraphDAG;\n}\n\n/**\n * Represents a task graph, a directed acyclic graph of tasks and data flows\n */\nexport class TaskGraph implements ITaskGraph {\n /** Optional output cache to use for this task graph */\n public outputCache?: TaskOutputRepository;\n\n constructor({ outputCache, dag }: TaskGraphConstructorConfig = {}) {\n this.outputCache = outputCache;\n this._dag = dag || new TaskGraphDAG();\n }\n\n private _dag: TaskGraphDAG;\n\n private _runner: TaskGraphRunner | undefined;\n public get runner(): TaskGraphRunner {\n if (!this._runner) {\n this._runner = new TaskGraphRunner(this, this.outputCache);\n }\n return this._runner;\n }\n\n // ========================================================================\n // Public methods\n // ========================================================================\n\n /**\n * Runs the task graph\n * @param config Configuration for the graph run\n * @returns A promise that resolves when all tasks are complete\n * @throws TaskError if any tasks have failed\n */\n public run<ExecuteOutput extends TaskOutput>(\n input: TaskInput = {} as TaskInput,\n config: TaskGraphRunConfig = {}\n ): Promise<GraphResultArray<ExecuteOutput>> {\n return this.runner.runGraph<ExecuteOutput>(input, {\n outputCache: config?.outputCache || this.outputCache,\n parentSignal: config?.parentSignal || undefined,\n accumulateLeafOutputs: config?.accumulateLeafOutputs,\n registry: config?.registry,\n timeout: config?.timeout,\n maxTasks: config?.maxTasks,\n resourceScope: config?.resourceScope,\n disposeStrategy: config?.disposeStrategy,\n runId: config?.runId,\n });\n }\n\n /**\n * Runs the task graph in preview mode\n * @returns A promise that resolves when all tasks are complete\n * @throws TaskError if any tasks have failed\n */\n public runPreview<Output extends TaskOutput>(\n input: TaskInput = {} as TaskInput,\n config: TaskGraphRunConfig = {}\n ): Promise<GraphResultArray<Output>> {\n return this.runner.runGraphPreview<Output>(input, config);\n }\n\n public mergeExecuteOutputsToRunOutput<\n ExecuteOutput extends TaskOutput,\n Merge extends CompoundMergeStrategy = CompoundMergeStrategy,\n >(\n results: GraphResultArray<ExecuteOutput>,\n compoundMerge: Merge\n ): GraphResult<ExecuteOutput, Merge> {\n return this.runner.mergeExecuteOutputsToRunOutput(results, compoundMerge);\n }\n\n public abort() {\n this.runner.abort();\n }\n\n public async disable() {\n await this.runner.disable();\n }\n\n /**\n * Retrieves a task from the task graph by its id\n * @param id The id of the task to retrieve\n * @returns The task with the given id, or undefined if not found\n */\n public getTask(id: TaskIdType): ITask<any, any, any> | undefined {\n return this._dag.getNode(id);\n }\n\n /**\n * Retrieves all tasks in the task graph\n * @returns An array of tasks in the task graph\n */\n public getTasks(): ITask<any, any, any>[] {\n return this._dag.getNodes();\n }\n\n /**\n * Retrieves all tasks in the task graph topologically sorted\n * @returns An array of tasks in the task graph topologically sorted\n */\n public topologicallySortedNodes(): ITask<any, any, any>[] {\n return this._dag.topologicallySortedNodes();\n }\n\n /**\n * Returns true if the underlying DAG is acyclic. Cycles are already rejected\n * synchronously by {@link addDataflow}, so this is a defensive check for\n * direct `_dag` manipulation or invariant re-assertion after cloning.\n */\n public isAcyclic(): boolean {\n return this._dag.isAcyclic();\n }\n\n /**\n * Adds a task to the task graph\n * @param task The task to add\n * @returns The current task graph\n */\n public addTask(fn: PipeFunction<any, any>, config?: any): unknown;\n public addTask(task: ITask<any, any, any>): unknown;\n public addTask(task: ITask<any, any, any> | PipeFunction<any, any>, config?: any): unknown {\n const t = ensureTask(task, config);\n t.parentGraph = this;\n return this._dag.addNode(t);\n }\n\n /**\n * Adds multiple tasks to the task graph\n * @param tasks The tasks to add\n * @returns The current task graph\n */\n public addTasks(tasks: PipeFunction<any, any>[]): unknown[];\n public addTasks(tasks: ITask<any, any, any>[]): unknown[];\n public addTasks(tasks: ITask<any, any, any>[] | PipeFunction<any, any>[]): unknown[] {\n const resolved = tasks.map(ensureTask);\n for (const t of resolved) {\n t.parentGraph = this;\n }\n return this._dag.addNodes(resolved);\n }\n\n /**\n * Adds a data flow to the task graph\n * @param dataflow The data flow to add\n * @returns The current task graph\n */\n public addDataflow(dataflow: Dataflow) {\n return this._dag.addEdge(dataflow.sourceTaskId, dataflow.targetTaskId, dataflow);\n }\n\n /**\n * Adds multiple data flows to the task graph\n * @param dataflows The data flows to add\n * @returns The current task graph\n */\n public addDataflows(dataflows: Dataflow[]) {\n const addedEdges = dataflows.map<[s: unknown, t: unknown, e: Dataflow]>((edge) => {\n return [edge.sourceTaskId, edge.targetTaskId, edge];\n });\n return this._dag.addEdges(addedEdges);\n }\n\n /**\n * Retrieves a data flow from the task graph by its id\n * @param id The id of the data flow to retrieve\n * @returns The data flow with the given id, or undefined if not found\n */\n public getDataflow(id: DataflowIdType): Dataflow | undefined {\n for (const [, , edge] of this._dag.getEdges()) {\n if (edge.id === id) {\n return edge;\n }\n }\n return undefined;\n }\n\n /**\n * Retrieves all data flows in the task graph\n * @returns An array of data flows in the task graph\n */\n public getDataflows(): Dataflow[] {\n return this._dag.getEdges().map((edge) => edge[2]);\n }\n\n /**\n * Removes a data flow from the task graph\n * @param dataflow The data flow to remove\n * @returns The current task graph\n */\n public removeDataflow(dataflow: Dataflow) {\n return this._dag.removeEdge(dataflow.sourceTaskId, dataflow.targetTaskId, dataflow.id);\n }\n\n /**\n * Retrieves the data flows that are sources of a given task\n * @param taskId The id of the task to retrieve sources for\n * @returns An array of data flows that are sources of the given task\n */\n public getSourceDataflows(taskId: unknown): Dataflow[] {\n return this._dag.inEdges(taskId).map(([, , dataflow]) => dataflow);\n }\n\n /**\n * Retrieves the data flows that are targets of a given task\n * @param taskId The id of the task to retrieve targets for\n * @returns An array of data flows that are targets of the given task\n */\n public getTargetDataflows(taskId: unknown): Dataflow[] {\n return this._dag.outEdges(taskId).map(([, , dataflow]) => dataflow);\n }\n\n /**\n * Retrieves the tasks that are sources of a given task\n * @param taskId The id of the task to retrieve sources for\n * @returns An array of tasks that are sources of the given task\n */\n public getSourceTasks(taskId: unknown): ITask<any, any, any>[] {\n return this.getSourceDataflows(taskId).map((dataflow) => this.getTask(dataflow.sourceTaskId)!);\n }\n\n /**\n * Retrieves the tasks that are targets of a given task\n * @param taskId The id of the task to retrieve targets for\n * @returns An array of tasks that are targets of the given task\n */\n public getTargetTasks(taskId: unknown): ITask<any, any, any>[] {\n return this.getTargetDataflows(taskId).map((dataflow) => this.getTask(dataflow.targetTaskId)!);\n }\n\n /**\n * Removes a task from the task graph\n * @param taskId The id of the task to remove\n * @returns The current task graph\n */\n public removeTask(taskId: unknown) {\n return this._dag.removeNode(taskId);\n }\n\n public resetGraph() {\n this.runner.resetGraph(this, uuid4());\n }\n\n /**\n * Converts the task graph to a JSON format suitable for dependency tracking\n * @param options Options controlling serialization (e.g., boundary nodes)\n * @returns A TaskGraphJson object representing the tasks and dataflows\n */\n public toJSON(options?: TaskGraphJsonOptions): TaskGraphJson {\n const tasks = this.getTasks().map((node) => node.toJSON(options));\n const dataflows = this.getDataflows().map((df) => df.toJSON());\n let json: TaskGraphJson = {\n tasks,\n dataflows,\n };\n if (options?.withBoundaryNodes) {\n json = addBoundaryNodesToGraphJson(json, this);\n }\n return json;\n }\n\n /**\n * Converts the task graph to a JSON format suitable for dependency tracking\n * @param options Options controlling serialization (e.g., boundary nodes)\n * @returns An array of JsonTaskItem objects, each representing a task and its dependencies\n */\n public toDependencyJSON(options?: TaskGraphJsonOptions): JsonTaskItem[] {\n const tasks = this.getTasks().flatMap((node) => node.toDependencyJSON(options));\n this.getDataflows().forEach((df) => {\n const target = tasks.find((node) => node.id === df.targetTaskId)!;\n if (!target.dependencies) {\n target.dependencies = {};\n }\n const targetDeps = target.dependencies[df.targetTaskPortId];\n if (!targetDeps) {\n target.dependencies[df.targetTaskPortId] = {\n id: df.sourceTaskId,\n output: df.sourceTaskPortId,\n };\n } else {\n if (Array.isArray(targetDeps)) {\n targetDeps.push({\n id: df.sourceTaskId,\n output: df.sourceTaskPortId,\n });\n } else {\n target.dependencies[df.targetTaskPortId] = [\n targetDeps,\n { id: df.sourceTaskId, output: df.sourceTaskPortId },\n ];\n }\n }\n });\n if (options?.withBoundaryNodes) {\n return addBoundaryNodesToDependencyJson(tasks, this);\n }\n return tasks;\n }\n\n // ========================================================================\n // Event handling\n // ========================================================================\n\n public get events(): EventEmitter<TaskGraphStatusListeners> {\n if (!this._events) {\n this._events = new EventEmitter<TaskGraphStatusListeners>();\n }\n return this._events;\n }\n protected _events: EventEmitter<TaskGraphStatusListeners> | undefined;\n\n /**\n * Subscribes to an event\n * @param name - The event name to listen for\n * @param fn - The callback function to execute when the event occurs\n * @returns a function to unsubscribe from the event\n */\n public subscribe<Event extends TaskGraphEvents>(\n name: Event,\n fn: TaskGraphEventListener<Event>\n ): () => void {\n this.on(name, fn);\n return () => this.off(name, fn);\n }\n\n /**\n * Subscribes to status changes on all tasks (existing and future)\n * @param callback - Function called when any task's status changes\n * @param callback.taskId - The ID of the task whose status changed\n * @param callback.status - The new status of the task\n * @returns a function to unsubscribe from all task status events\n */\n public subscribeToTaskStatus(\n callback: (taskId: TaskIdType, status: TaskStatus) => void\n ): () => void {\n const unsubscribes: (() => void)[] = [];\n\n // Subscribe to status events on all existing tasks\n const tasks = this.getTasks();\n tasks.forEach((task) => {\n const unsub = task.subscribe(\"status\", (status) => {\n callback(task.id, status);\n });\n unsubscribes.push(unsub);\n });\n\n const handleTaskAdded = (taskId: TaskIdType) => {\n const task = this.getTask(taskId);\n if (!task || typeof task.subscribe !== \"function\") return;\n\n const unsub = task.subscribe(\"status\", (status) => {\n callback(task.id, status);\n });\n unsubscribes.push(unsub);\n };\n\n const graphUnsub = this.subscribe(\"task_added\", handleTaskAdded);\n unsubscribes.push(graphUnsub);\n\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n };\n }\n\n /**\n * Subscribes to progress updates on all tasks (existing and future)\n * @param callback - Function called when any task reports progress\n * @param callback.taskId - The ID of the task reporting progress\n * @param callback.progress - The progress value (0-100)\n * @param callback.message - Optional progress message\n * @param callback.args - Additional arguments passed with the progress update\n * @returns a function to unsubscribe from all task progress events\n */\n public subscribeToTaskProgress(\n callback: (\n taskId: TaskIdType,\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ) => void\n ): () => void {\n const unsubscribes: (() => void)[] = [];\n\n // Subscribe to progress events on all existing tasks\n const tasks = this.getTasks();\n tasks.forEach((task) => {\n const unsub = task.subscribe(\"progress\", (progress, message, ...args) => {\n callback(task.id, progress, message, ...args);\n });\n unsubscribes.push(unsub);\n });\n\n const handleTaskAdded = (taskId: TaskIdType) => {\n const task = this.getTask(taskId);\n if (!task || typeof task.subscribe !== \"function\") return;\n\n const unsub = task.subscribe(\"progress\", (progress, message, ...args) => {\n callback(task.id, progress, message, ...args);\n });\n unsubscribes.push(unsub);\n };\n\n const graphUnsub = this.subscribe(\"task_added\", handleTaskAdded);\n unsubscribes.push(graphUnsub);\n\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n };\n }\n\n /**\n * Subscribes to status changes on all dataflows (existing and future)\n * @param callback - Function called when any dataflow's status changes\n * @param callback.dataflowId - The ID of the dataflow whose status changed\n * @param callback.status - The new status of the dataflow\n * @returns a function to unsubscribe from all dataflow status events\n */\n public subscribeToDataflowStatus(\n callback: (dataflowId: DataflowIdType, status: TaskStatus) => void\n ): () => void {\n const unsubscribes: (() => void)[] = [];\n\n // Subscribe to status events on all existing dataflows\n const dataflows = this.getDataflows();\n dataflows.forEach((dataflow) => {\n const unsub = dataflow.subscribe(\"status\", (status) => {\n callback(dataflow.id, status);\n });\n unsubscribes.push(unsub);\n });\n\n const handleDataflowAdded = (dataflowId: DataflowIdType) => {\n const dataflow = this.getDataflow(dataflowId);\n if (!dataflow || typeof dataflow.subscribe !== \"function\") return;\n\n const unsub = dataflow.subscribe(\"status\", (status) => {\n callback(dataflow.id, status);\n });\n unsubscribes.push(unsub);\n };\n\n const graphUnsub = this.subscribe(\"dataflow_added\", handleDataflowAdded);\n unsubscribes.push(graphUnsub);\n\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n };\n }\n\n /**\n * Subscribes to streaming events on the task graph.\n * Listens for task_stream_start, task_stream_chunk, and task_stream_end\n * events emitted by the TaskGraphRunner during streaming task execution.\n *\n * @param callbacks - Object with optional callbacks for each streaming event\n * @returns a function to unsubscribe from all streaming events\n */\n public subscribeToTaskStreaming(callbacks: {\n onStreamStart?: (taskId: TaskIdType) => void;\n onStreamChunk?: (taskId: TaskIdType, event: StreamEvent) => void;\n onStreamEnd?: (taskId: TaskIdType, output: Record<string, any>) => void;\n }): () => void {\n const unsubscribes: (() => void)[] = [];\n\n if (callbacks.onStreamStart) {\n const unsub = this.subscribe(\"task_stream_start\", callbacks.onStreamStart);\n unsubscribes.push(unsub);\n }\n\n if (callbacks.onStreamChunk) {\n const unsub = this.subscribe(\"task_stream_chunk\", callbacks.onStreamChunk);\n unsubscribes.push(unsub);\n }\n\n if (callbacks.onStreamEnd) {\n const unsub = this.subscribe(\"task_stream_end\", callbacks.onStreamEnd);\n unsubscribes.push(unsub);\n }\n\n return () => {\n unsubscribes.forEach((unsub) => unsub());\n };\n }\n\n /**\n * Subscribes to entitlement changes on all tasks (existing and future).\n * When any task's entitlements change, the graph recomputes and emits its own\n * `entitlementChange` event. Structural changes (task_added, task_removed) also trigger.\n *\n * @param callback - Function called with the aggregated entitlements whenever they change\n * @returns a function to unsubscribe from all entitlement events\n */\n public subscribeToTaskEntitlements(\n callback: (entitlements: TaskEntitlements) => void\n ): () => void {\n const globalUnsubs: (() => void)[] = [];\n const taskUnsubs = new Map<TaskIdType, () => void>();\n\n const emitChange = () => {\n const entitlements = computeGraphEntitlements(this);\n this.emit(\"entitlementChange\", entitlements);\n callback(entitlements);\n };\n\n const subscribeTask = (taskId: TaskIdType) => {\n const task = this.getTask(taskId);\n if (!task || typeof task.subscribe !== \"function\") return;\n const unsub = task.subscribe(\"entitlementChange\", () => emitChange());\n taskUnsubs.set(taskId, unsub);\n };\n\n // Subscribe to entitlementChange events on all existing tasks\n for (const task of this.getTasks()) {\n subscribeTask(task.id);\n }\n\n // Emit the initial state immediately so subscribers don't miss the current entitlements\n emitChange();\n\n // Subscribe to new tasks being added\n globalUnsubs.push(\n this.subscribe(\"task_added\", (taskId: TaskIdType) => {\n subscribeTask(taskId);\n emitChange();\n })\n );\n\n globalUnsubs.push(\n this.subscribe(\"task_removed\", (taskId: TaskIdType) => {\n const unsub = taskUnsubs.get(taskId);\n if (unsub) {\n unsub();\n taskUnsubs.delete(taskId);\n }\n emitChange();\n })\n );\n\n return () => {\n globalUnsubs.forEach((unsub) => unsub());\n taskUnsubs.forEach((unsub) => unsub());\n taskUnsubs.clear();\n };\n }\n\n /**\n * Registers an event listener for the specified event\n * @param name - The event name to listen for\n * @param fn - The callback function to execute when the event occurs\n */\n on<Event extends TaskGraphEvents>(name: Event, fn: TaskGraphEventListener<Event>) {\n const dagEvent = EventTaskGraphToDagMapping[name as keyof typeof EventTaskGraphToDagMapping];\n if (dagEvent) {\n // Safe cast: TaskGraph dag events (task_added, etc.) have the same signature as\n // the underlying DAG events (node-added, etc.) - both pass IDs, not full objects\n return this._dag.on(dagEvent, fn as Parameters<typeof this._dag.on>[1]);\n }\n return this.events.on(\n name as TaskGraphStatusEvents,\n fn as TaskGraphEventListener<TaskGraphStatusEvents>\n );\n }\n\n /**\n * Removes an event listener for the specified event\n * @param name - The event name to listen for\n * @param fn - The callback function to execute when the event occurs\n */\n off<Event extends TaskGraphEvents>(name: Event, fn: TaskGraphEventListener<Event>) {\n const dagEvent = EventTaskGraphToDagMapping[name as keyof typeof EventTaskGraphToDagMapping];\n if (dagEvent) {\n // Safe cast: TaskGraph dag events (task_added, etc.) have the same signature as\n // the underlying DAG events (node-added, etc.) - both pass IDs, not full objects\n return this._dag.off(dagEvent, fn as Parameters<typeof this._dag.off>[1]);\n }\n return this.events.off(\n name as TaskGraphStatusEvents,\n fn as TaskGraphEventListener<TaskGraphStatusEvents>\n );\n }\n\n /**\n * Emits an event for the specified event\n * @param name - The event name to emit\n * @param args - The arguments to pass to the event listener\n */\n emit<E extends GraphEventDagEvents>(name: E, ...args: GraphEventDagParameters<E>): void;\n emit<E extends TaskGraphStatusEvents>(name: E, ...args: TaskGraphEventStatusParameters<E>): void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n emit(name: string, ...args: any[]): void {\n const dagEvent = EventTaskGraphToDagMapping[name as keyof typeof EventTaskGraphToDagMapping];\n if (dagEvent) {\n // Safe: overload signatures guarantee correct arg types at call sites\n return (this.emit_dag as Function).call(this, name, ...args);\n } else {\n return (this.emit_local as Function).call(this, name, ...args);\n }\n }\n\n protected emit_local<Event extends TaskGraphStatusEvents>(\n name: Event,\n ...args: TaskGraphEventStatusParameters<Event>\n ) {\n return this.events?.emit(name, ...args);\n }\n\n protected emit_dag<Event extends GraphEventDagEvents>(\n name: Event,\n ...args: GraphEventDagParameters<Event>\n ) {\n const dagEvent = EventTaskGraphToDagMapping[name as keyof typeof EventTaskGraphToDagMapping];\n // Safe cast: GraphEventDagParameters matches the DAG's emit parameters (both are ID-based)\n return this._dag.emit(dagEvent, ...(args as unknown as [unknown]));\n }\n}\n\n/**\n * Super simple helper if you know the input and output handles, and there is only one each\n *\n * @param tasks\n * @param inputHandle\n * @param outputHandle\n * @returns\n */\nfunction serialGraphEdges(\n tasks: ITask<any, any, any>[],\n inputHandle: string,\n outputHandle: string\n): Dataflow[] {\n const edges: Dataflow[] = [];\n for (let i = 0; i < tasks.length - 1; i++) {\n edges.push(new Dataflow(tasks[i].id, inputHandle, tasks[i + 1].id, outputHandle));\n }\n return edges;\n}\n\n/**\n * Super simple helper if you know the input and output handles, and there is only one each\n *\n * @param tasks\n * @param inputHandle\n * @param outputHandle\n * @returns\n */\nexport function serialGraph(\n tasks: ITask<any, any, any>[],\n inputHandle: string,\n outputHandle: string\n): TaskGraph {\n const graph = new TaskGraph();\n graph.addTasks(tasks);\n graph.addDataflows(serialGraphEdges(tasks, inputHandle, outputHandle));\n return graph;\n}\n",
|
|
15
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport { CycleError } from \"@workglow/util/graph\";\nimport type { DataPortSchema, SchemaNode } from \"@workglow/util/schema\";\nimport { compileSchema } from \"@workglow/util/schema\";\nimport { computeGraphEntitlements } from \"../task-graph/GraphEntitlementUtils\";\nimport { computeGraphInputSchema, computeGraphOutputSchema } from \"../task-graph/GraphSchemaUtils\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport { CompoundMergeStrategy, PROPERTY_ARRAY } from \"../task-graph/TaskGraphRunner\";\nimport type { CreateLoopWorkflow } from \"../task-graph/WorkflowFactories\";\nimport { GraphAsTaskRunner } from \"./GraphAsTaskRunner\";\nimport type { IExecuteContext, IRunConfig } from \"./ITask\";\nimport type { StreamEvent, StreamFinish } from \"./StreamTypes\";\nimport { Task } from \"./Task\";\nimport type { TaskEntitlements } from \"./TaskEntitlements\";\nimport type { TaskEventListener, TaskEvents } from \"./TaskEvents\";\nimport type { JsonTaskItem, TaskGraphItemJson, TaskGraphJsonOptions } from \"./TaskJSON\";\nimport type { TaskConfig, TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\nimport { TaskConfigSchema } from \"./TaskTypes\";\n\nexport const graphAsTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...TaskConfigSchema[\"properties\"],\n compoundMerge: { type: \"string\", \"x-ui-hidden\": true },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type GraphAsTaskConfig<Input extends TaskInput = TaskInput> = TaskConfig<Input> & {\n /** subGraph is extracted in the constructor before validation — not in the JSON schema */\n subGraph?: TaskGraph;\n compoundMerge?: CompoundMergeStrategy;\n};\n\n/**\n * A task that contains a subgraph of tasks\n */\nexport class GraphAsTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends GraphAsTaskConfig<Input> = GraphAsTaskConfig<Input>,\n> extends Task<Input, Output, Config> {\n // ========================================================================\n // Static properties - should be overridden by subclasses\n // ========================================================================\n\n public static override type: TaskTypeName = \"GraphAsTask\";\n public static override title: string = \"Group\";\n public static override description: string = \"A group of tasks that are executed together\";\n public static override category: string = \"Flow Control\";\n public static compoundMerge: CompoundMergeStrategy = PROPERTY_ARRAY;\n\n /** This task has dynamic schemas that change based on the subgraph structure */\n public static override hasDynamicSchemas: boolean = true;\n\n /** Entitlements are always dynamic — they depend on child tasks in the subgraph */\n public static override hasDynamicEntitlements: boolean = true;\n\n // ========================================================================\n // Constructor\n // ========================================================================\n\n /**\n * `subGraph` is extracted from `config` and applied to the instance before\n * validating the remainder of the config.\n */\n constructor(config: Partial<Config> = {}, runConfig: Partial<IRunConfig> = {}) {\n const { subGraph, ...rest } = config;\n super(rest as Partial<Config>, runConfig);\n if (subGraph) {\n this.subGraph = subGraph;\n }\n this.regenerateGraph();\n }\n\n // ========================================================================\n // TaskRunner delegation - Executes and manages the task\n // ========================================================================\n\n declare _runner: GraphAsTaskRunner<Input, Output, Config>;\n\n override get runner(): GraphAsTaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new GraphAsTaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n // ========================================================================\n // Static to Instance conversion methods\n // ========================================================================\n\n public static override configSchema(): DataPortSchema {\n return graphAsTaskConfigSchema;\n }\n\n public get compoundMerge(): CompoundMergeStrategy {\n return this.config?.compoundMerge || (this.constructor as typeof GraphAsTask).compoundMerge;\n }\n\n public override get cacheable(): boolean {\n return (\n this.runConfig?.cacheable ??\n this.config?.cacheable ??\n ((this.constructor as typeof GraphAsTask).cacheable && !this.hasChildren())\n );\n }\n\n // ========================================================================\n // Input/Output handling\n // ========================================================================\n\n /**\n * Override inputSchema to compute it dynamically from the subgraph at runtime.\n * For root tasks (no incoming edges) all input properties are collected.\n * For non-root tasks, only REQUIRED properties that are not satisfied by\n * any internal dataflow are added — this ensures that required inputs are\n * included in the graph's input schema without pulling in every optional\n * downstream property.\n */\n public override inputSchema(): DataPortSchema {\n // If there's no subgraph or it has no children, fall back to the static schema\n if (!this.hasChildren()) {\n return (this.constructor as typeof Task).inputSchema();\n }\n\n return computeGraphInputSchema(this.subGraph);\n }\n\n protected _inputSchemaNode: SchemaNode | undefined;\n protected override getInputSchemaNode(): SchemaNode {\n // every graph as task is different, so we need to compile the schema for each one\n if (!this._inputSchemaNode) {\n try {\n const dataPortSchema = this.inputSchema();\n const schemaNode = Task.generateInputSchemaNode(dataPortSchema);\n this._inputSchemaNode = schemaNode;\n } catch (error) {\n // If compilation fails, fall back to accepting any object structure.\n // This is a safety net for schemas that json-schema-library can't compile.\n getLogger().warn(\n `GraphAsTask \"${this.type}\" (${this.id}): Failed to compile input schema, ` +\n `falling back to permissive validation. Inputs will NOT be validated.`,\n { error, taskType: this.type, taskId: this.id }\n );\n this._inputSchemaNode = compileSchema({});\n }\n }\n return this._inputSchemaNode!;\n }\n\n /**\n * Compute output schema dynamically from the subgraph. Depends on the\n * compoundMerge strategy and the nodes at the last level.\n */\n public override outputSchema(): DataPortSchema {\n // If there's no subgraph or it has no children, fall back to the static schema\n if (!this.hasChildren()) {\n return (this.constructor as typeof Task).outputSchema();\n }\n\n return computeGraphOutputSchema(this.subGraph);\n }\n\n /**\n * Aggregates entitlements from all tasks in the subgraph.\n */\n public override entitlements(): TaskEntitlements {\n if (!this.hasChildren()) {\n return (this.constructor as typeof Task).entitlements();\n }\n return computeGraphEntitlements(this.subGraph);\n }\n\n public override resetInputData(): void {\n super.resetInputData();\n if (this.hasChildren()) {\n this.subGraph!.getTasks().forEach((node) => {\n node.resetInputData();\n });\n this.subGraph!.getDataflows().forEach((dataflow) => {\n dataflow.reset();\n });\n }\n }\n\n // ========================================================================\n // Streaming pass-through\n // ========================================================================\n\n /**\n * Stream pass-through for compound tasks: runs the subgraph and forwards\n * streaming events from ending nodes to the outer graph. Also re-yields\n * any input streams from upstream for cases where this GraphAsTask is\n * itself downstream of another streaming task.\n */\n async *executeStream(input: Input, context: IExecuteContext): AsyncIterable<StreamEvent<Output>> {\n // Forward upstream input streams first (pass-through from outer graph)\n if (context.inputStreams) {\n for (const [, stream] of context.inputStreams) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value.type === \"finish\") continue;\n yield value as StreamEvent<Output>;\n }\n } finally {\n reader.releaseLock();\n }\n }\n }\n\n // Run the subgraph and forward streaming events from ending nodes\n if (this.hasChildren()) {\n const endingNodeIds = new Set<unknown>();\n const tasks = this.subGraph.getTasks();\n for (const task of tasks) {\n if (this.subGraph.getTargetDataflows(task.id).length === 0) {\n endingNodeIds.add(task.id);\n }\n }\n\n const eventQueue: StreamEvent<Output>[] = [];\n let subgraphDone = false;\n\n // Eager promise/resolver — always available for producers to signal.\n // Prevents a race where producers call a stale or undefined resolver,\n // causing the generator to hang on a promise that never resolves.\n // `isWaiting` is true only while the generator is suspended at `await notifyPromise`.\n // `hasPending` records a notification that arrived while the generator was active,\n // so the generator skips the next wait without allocating a new promise.\n let { promise: notifyPromise, resolve: notifyResolve } = Promise.withResolvers<void>();\n let isWaiting = false;\n let hasPending = false;\n const notify = () => {\n if (isWaiting) {\n // Wake the generator and prepare a fresh deferred for the next wait.\n notifyResolve();\n ({ promise: notifyPromise, resolve: notifyResolve } = Promise.withResolvers<void>());\n isWaiting = false;\n } else {\n // Generator is still draining; skip the allocation.\n hasPending = true;\n }\n };\n\n const unsub = this.subGraph.subscribeToTaskStreaming({\n onStreamChunk: (taskId, event) => {\n if (endingNodeIds.has(taskId) && event.type !== \"finish\") {\n eventQueue.push(event as StreamEvent<Output>);\n notify();\n }\n },\n });\n\n const runPromise = this.subGraph\n .run<Output>(input, { parentSignal: context.signal, accumulateLeafOutputs: false })\n .then(\n (results) => {\n subgraphDone = true;\n notify();\n return results;\n },\n (err) => {\n subgraphDone = true;\n notify();\n throw err;\n }\n );\n\n // Yield events as they arrive from ending nodes\n while (!subgraphDone) {\n if (eventQueue.length === 0) {\n if (hasPending) {\n // A notification arrived while we were active; consume it without blocking.\n hasPending = false;\n } else {\n isWaiting = true;\n await notifyPromise;\n }\n }\n while (eventQueue.length > 0) {\n yield eventQueue.shift()!;\n }\n }\n // Drain any remaining events\n while (eventQueue.length > 0) {\n yield eventQueue.shift()!;\n }\n\n unsub();\n\n const results = await runPromise;\n const mergedOutput = this.subGraph.mergeExecuteOutputsToRunOutput(\n results,\n this.compoundMerge\n ) as Output;\n yield { type: \"finish\", data: mergedOutput } as StreamFinish<Output>;\n } else {\n yield { type: \"finish\", data: input as unknown as Output } as StreamFinish<Output>;\n }\n }\n\n // ========================================================================\n // Compound task methods\n // ========================================================================\n\n /**\n * Defensive re-assertion of the DAG invariant for the subgraph. `TaskGraph`\n * already rejects cycle-creating dataflows at `addDataflow` time, but this\n * runs a full topo sort so that any direct `_dag` manipulation or cycle\n * introduced via recursive subgraph composition surfaces here with a clear\n * error rather than deep inside the runner.\n */\n public validateAcyclic(): void {\n if (!this.hasChildren()) return;\n if (!this.subGraph.isAcyclic()) {\n throw new CycleError(\n `${this.type} (${this.id}): subgraph contains a cycle — loop tasks must wrap an acyclic subgraph.`\n );\n }\n for (const child of this.subGraph.getTasks()) {\n if (child instanceof GraphAsTask) {\n child.validateAcyclic();\n }\n }\n }\n\n /**\n * Regenerates the subtask graph and emits a \"regenerate\" event.\n * Subclasses override to implement actual regeneration logic; they only\n * need to call this method to emit the event.\n */\n public override regenerateGraph(): void {\n this._inputSchemaNode = undefined;\n this.events.emit(\"regenerate\");\n this.emitEntitlementChange();\n }\n\n // ========================================================================\n // SubGraph entitlement forwarding\n // ========================================================================\n\n /** Unsubscribe handle for the current subGraph entitlement subscription */\n private _entitlementUnsub: (() => void) | undefined;\n\n /**\n * Guards against re-entry while the synchronous initial emit of\n * `subscribeToTaskEntitlements` is unwinding. Without this, the initial\n * emit's callback re-reads `this.subGraph`, which would re-trigger\n * `_syncSubGraphEntitlementSubscription` before `_entitlementUnsub` has\n * been assigned and loop forever.\n */\n private _subscribingEntitlements: boolean = false;\n\n /**\n * Subscribe to the subGraph's aggregated entitlement changes and forward\n * them as an entitlementChange event on this task so that the parent\n * TaskGraph / Workflow sees the update.\n */\n private _subscribeToSubGraphEntitlements(graph: TaskGraph): void {\n this._entitlementUnsub?.();\n this._entitlementUnsub = undefined;\n this._subscribingEntitlements = true;\n try {\n this._entitlementUnsub = graph.subscribeToTaskEntitlements(() => {\n this.emitEntitlementChange();\n });\n } finally {\n this._subscribingEntitlements = false;\n }\n }\n\n private _syncSubGraphEntitlementSubscription(\n graph: TaskGraph | undefined = this._subGraph\n ): void {\n if (this._subscribingEntitlements) return;\n\n if ((this._events?.listenerCount(\"entitlementChange\") ?? 0) === 0) {\n this._entitlementUnsub?.();\n this._entitlementUnsub = undefined;\n return;\n }\n\n if (!graph || this._entitlementUnsub) {\n return;\n }\n\n this._subscribeToSubGraphEntitlements(graph);\n }\n\n public override subscribe<Event extends TaskEvents>(\n name: Event,\n fn: TaskEventListener<Event>\n ): () => void {\n const unsub = super.subscribe(name, fn);\n if (name !== \"entitlementChange\") {\n return unsub;\n }\n\n this._syncSubGraphEntitlementSubscription();\n\n return () => {\n unsub();\n this._syncSubGraphEntitlementSubscription();\n };\n }\n\n public override on<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n super.on(name, fn);\n if (name === \"entitlementChange\") {\n this._syncSubGraphEntitlementSubscription();\n }\n }\n\n public override off<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n super.off(name, fn);\n if (name === \"entitlementChange\") {\n this._syncSubGraphEntitlementSubscription();\n }\n }\n\n public override once<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n super.once(name, fn);\n if (name === \"entitlementChange\") {\n this._syncSubGraphEntitlementSubscription();\n }\n }\n\n public override set subGraph(subGraph: TaskGraph) {\n this._entitlementUnsub?.();\n this._entitlementUnsub = undefined;\n super.subGraph = subGraph;\n this._syncSubGraphEntitlementSubscription(subGraph);\n }\n\n override get subGraph(): TaskGraph {\n const graph = super.subGraph;\n // The base getter may have lazily created a new graph — subscribe only when needed.\n this._syncSubGraphEntitlementSubscription(graph);\n return graph;\n }\n\n // ========================================================================\n // Serialization methods\n // ========================================================================\n\n public override toJSON(options?: TaskGraphJsonOptions): TaskGraphItemJson {\n let json = super.toJSON(options);\n const hasChildren = this.hasChildren();\n if (hasChildren) {\n json = {\n ...json,\n merge: this.compoundMerge,\n subgraph: this.subGraph!.toJSON(options),\n };\n }\n return json;\n }\n\n public override toDependencyJSON(options?: TaskGraphJsonOptions): JsonTaskItem {\n const json = this.toJSON(options);\n if (this.hasChildren()) {\n if (\"subgraph\" in json) {\n delete json.subgraph;\n }\n return { ...json, subtasks: this.subGraph!.toDependencyJSON(options) };\n }\n return json;\n }\n}\n\ndeclare module \"../task-graph/Workflow\" {\n interface Workflow {\n /**\n * Starts a group that wraps inner tasks in a GraphAsTask subgraph.\n * Use .endGroup() to close the group and return to the parent workflow.\n */\n group: CreateLoopWorkflow<TaskInput, TaskOutput, GraphAsTaskConfig<TaskInput>>;\n\n /**\n * Ends the group and returns to the parent workflow.\n */\n endGroup(): Workflow;\n }\n}\n\n// Prototype assignments live in Workflow.ts (bottom of file) to avoid\n// circular-dependency issues at module evaluation time.\n",
|
|
21
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport type { CachePolicy } from \"../cache/CachePolicy\";\nimport type { IExecuteContext, ITask } from \"../task/ITask\";\nimport { Task } from \"../task/Task\";\nimport type { DataPorts } from \"../task/TaskTypes\";\nimport { DATAFLOW_ALL_PORTS } from \"./Dataflow\";\nimport type { ITaskGraph } from \"./ITaskGraph\";\nimport type { IWorkflow } from \"./IWorkflow\";\nimport { TaskGraph } from \"./TaskGraph\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type PipeFunction<I extends DataPorts = any, O extends DataPorts = any> = (\n input: I,\n context: IExecuteContext\n) => O | Promise<O>;\n\nexport type Taskish<A extends DataPorts = DataPorts, B extends DataPorts = DataPorts> =\n | PipeFunction<A, B>\n | ITask<A, B>\n | ITaskGraph\n | IWorkflow<A, B>;\n\n// ============================================================================\n// GraphAsTask wrapper factory (deferred seam)\n//\n// `ensureTask` wraps a TaskGraph/Workflow in a GraphAsTask subclass, but\n// GraphAsTask's runner depends — via TaskRunner, which imports `ensureTask` —\n// back on this module: an inherent cycle. GraphAsTask.ts owns the wrapper\n// subclasses (so they extend GraphAsTask directly, no casts) and registers\n// this factory once it has finished evaluating; `ensureTask` calls it lazily.\n// ============================================================================\n\nexport type GraphWrapperParams = {\n subGraph: TaskGraph;\n isOwned: boolean;\n isWorkflow: boolean;\n config: any;\n};\n\nexport type GraphWrapperFactory = (params: GraphWrapperParams) => ITask<any, any, any>;\n\nlet _graphWrapperFactory: GraphWrapperFactory | undefined;\n\n/** Called from {@link GraphAsTask} once its module has finished evaluating. */\nexport function registerGraphWrapperFactory(factory: GraphWrapperFactory): void {\n _graphWrapperFactory = factory;\n}\n\nfunction graphWrapperFactory(): GraphWrapperFactory {\n if (!_graphWrapperFactory) {\n throw new Error(\n \"GraphAsTask is not registered yet. Ensure @workglow/task-graph has finished loading.\"\n );\n }\n return _graphWrapperFactory;\n}\n\n// ============================================================================\n// ensureTask — converts Taskish values into ITask instances\n// ============================================================================\n\nfunction convertPipeFunctionToTask<I extends DataPorts, O extends DataPorts>(\n fn: PipeFunction<I, O>,\n config?: any\n): ITask<I, O> {\n // Plain JS functions used inside `pipe()` cannot declare port schemas, so\n // the wrapper must accept (and emit) any object shape. The previous\n // `additionalProperties: false` (alongside a single `[DATAFLOW_ALL_PORTS]`\n // (\"*\") property) caused the JSON-schema validator to treat \"*\" as a\n // literal key and reject every real upstream port — e.g. `{ json, metadata }`\n // from `FetchUrlTask` — breaking any `pipe(task, async fn, ...)` chain with\n // TaskInvalidInputError. The runtime already handles the \"*\" wildcard in\n // `Task.addInput`; the schema just needs to permit the data through.\n class QuickTask extends Task<I, O> {\n public static override type = fn.name ? `𝑓 ${fn.name}` : \"𝑓\";\n public static override inputSchema = () => {\n return {\n type: \"object\",\n properties: {\n [DATAFLOW_ALL_PORTS]: {},\n },\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n };\n public static override outputSchema = () => {\n return {\n type: \"object\",\n properties: {\n [DATAFLOW_ALL_PORTS]: {},\n },\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n };\n public static override cachePolicy: CachePolicy = { kind: \"none\" };\n public override async execute(input: I, context: IExecuteContext) {\n return fn(input, context);\n }\n }\n return new QuickTask(config);\n}\n\n/**\n * Checks if a value implements the IWorkflow interface (has a `graph` property\n * that is a TaskGraph and a `run` method). Used instead of `instanceof Workflow`\n * to avoid a circular dependency with the Workflow module.\n */\nfunction isWorkflowLike(arg: unknown): arg is IWorkflow {\n return (\n arg != null &&\n typeof arg === \"object\" &&\n \"graph\" in arg &&\n arg.graph instanceof TaskGraph &&\n \"run\" in arg &&\n typeof arg.run === \"function\"\n );\n}\n\nexport function ensureTask<I extends DataPorts, O extends DataPorts>(\n arg: Taskish<I, O>,\n config: any = {}\n): ITask<any, any, any> {\n if (arg instanceof Task) {\n return arg;\n }\n if (arg instanceof TaskGraph) {\n const { isOwned, ...cleanConfig } = config;\n return graphWrapperFactory()({\n subGraph: arg,\n isOwned: Boolean(isOwned),\n isWorkflow: false,\n config: cleanConfig,\n });\n }\n if (isWorkflowLike(arg)) {\n const { isOwned, ...cleanConfig } = config;\n return graphWrapperFactory()({\n subGraph: arg.graph,\n isOwned: Boolean(isOwned),\n isWorkflow: true,\n config: cleanConfig,\n });\n }\n return convertPipeFunctionToTask(arg as PipeFunction<I, O>, config);\n}\n",
|
|
22
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { EventParameters } from \"@workglow/util\";\nimport type { StreamEvent } from \"../task/StreamTypes\";\nimport type { TaskEntitlements } from \"../task/TaskEntitlements\";\nimport { TaskIdType } from \"../task/TaskTypes\";\nimport { DataflowIdType } from \"./Dataflow\";\n\n/**\n * Events that can be emitted by the TaskGraph\n */\n\nexport type TaskGraphStatusListeners = {\n graph_progress: (progress: number | undefined, message?: string, ...args: any[]) => void;\n start: () => void;\n complete: () => void;\n error: (error: Error) => void;\n abort: () => void;\n disabled: () => void;\n /** Fired when a task in the graph starts streaming */\n task_stream_start: (taskId: TaskIdType) => void;\n /** Fired for each stream chunk produced by a task in the graph */\n task_stream_chunk: (taskId: TaskIdType, event: StreamEvent) => void;\n /** Fired when a task in the graph finishes streaming */\n task_stream_end: (taskId: TaskIdType, output: Record<string, any>) => void;\n /** Fired when the aggregated entitlements of the graph change */\n entitlementChange: (entitlements: TaskEntitlements) => void;\n};\nexport type TaskGraphStatusEvents = keyof TaskGraphStatusListeners;\nexport type TaskGraphStatusListener<Event extends TaskGraphStatusEvents> =\n TaskGraphStatusListeners[Event];\nexport type TaskGraphEventStatusParameters<Event extends TaskGraphStatusEvents> = EventParameters<\n TaskGraphStatusListeners,\n Event\n>;\n\nexport type GraphEventDagListeners = {\n task_added: (taskId: TaskIdType) => void;\n task_removed: (taskId: TaskIdType) => void;\n task_replaced: (taskId: TaskIdType) => void;\n dataflow_added: (dataflowId: DataflowIdType) => void;\n dataflow_removed: (dataflowId: DataflowIdType) => void;\n dataflow_replaced: (dataflowId: DataflowIdType) => void;\n};\nexport type GraphEventDagEvents = keyof GraphEventDagListeners;\nexport type GraphEventDagListener<Event extends GraphEventDagEvents> =\n GraphEventDagListeners[Event];\nexport type GraphEventDagParameters<Event extends GraphEventDagEvents> = EventParameters<\n GraphEventDagListeners,\n Event\n>;\n\nexport type TaskGraphListeners = TaskGraphStatusListeners & GraphEventDagListeners;\nexport type TaskGraphEvents = keyof TaskGraphListeners;\nexport type TaskGraphEventListener<Event extends TaskGraphEvents> = TaskGraphListeners[Event];\nexport type TaskGraphEventParameters<Event extends TaskGraphEvents> = EventParameters<\n TaskGraphListeners,\n Event\n>;\n\nexport const EventDagToTaskGraphMapping = {\n \"node-added\": \"task_added\",\n \"node-removed\": \"task_removed\",\n \"node-replaced\": \"task_replaced\",\n \"edge-added\": \"dataflow_added\",\n \"edge-removed\": \"dataflow_removed\",\n \"edge-replaced\": \"dataflow_replaced\",\n} as const;\n\nexport const EventTaskGraphToDagMapping = {\n task_added: \"node-added\",\n task_removed: \"node-removed\",\n task_replaced: \"node-replaced\",\n dataflow_added: \"edge-added\",\n dataflow_removed: \"edge-removed\",\n dataflow_replaced: \"edge-replaced\",\n} as const;\n",
|
|
16
23
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ISpan } from \"@workglow/util\";\nimport {\n collectPropertyValues,\n ConvertAllToOptionalArray,\n getLogger,\n getTelemetryProvider,\n globalServiceRegistry,\n ResourceScope,\n ServiceRegistry,\n SpanStatusCode,\n uuid4,\n} from \"@workglow/util\";\nimport { CACHE_REGISTRY, DefaultCacheRegistry, RunPrivateCacheRepo } from \"../cache\";\nimport { TASK_OUTPUT_REPOSITORY, TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport { ENTITLEMENT_ENFORCER, formatEntitlementDenial } from \"../task/EntitlementEnforcer\";\nimport { ITask } from \"../task/ITask\";\nimport { isTaskStreamable } from \"../task/StreamTypes\";\nimport { Task } from \"../task/Task\";\nimport {\n TaskAbortedError,\n TaskConfigurationError,\n TaskEntitlementError,\n TaskError,\n} from \"../task/TaskError\";\nimport { TaskInput, TaskOutput, TaskStatus } from \"../task/TaskTypes\";\nimport { EdgeMaterializer } from \"./EdgeMaterializer\";\nimport { computeGraphEntitlements } from \"./GraphEntitlementUtils\";\nimport { RunContext } from \"./RunContext\";\nimport { RunScheduler } from \"./RunScheduler\";\nimport { StreamPump } from \"./StreamPump\";\nimport { TaskGraph, TaskGraphRunConfig, TaskGraphRunPreviewConfig } from \"./TaskGraph\";\nimport { DependencyBasedScheduler, TopologicalScheduler } from \"./TaskGraphScheduler\";\n\n/**\n * Identifies tasks whose progress is meaningful to graph-level averaging. A task contributes when\n * it does real work — either because:\n *\n * - it declares its own `execute` on the subclass prototype (standard case), or\n * - it declares its own `executeStream` on the subclass prototype (streaming tasks keep their\n * `execute` on `Task.prototype` but still do real work), or\n * - it wraps a subgraph (`hasChildren()` — e.g. `GraphAsTask` / `WorkflowAsTask` /\n * `IteratorTask` / `WhileTask` / `FallbackTask`). Their runners route subgraph\n * `graph_progress` through {@link TaskRunner.handleProgress}, so `task.progress` tracks\n * the nested work and the averaging is accurate.\n *\n * Tasks flagged `isPassthrough` (e.g. `InputTask`, `OutputTask`) are always excluded: they only\n * forward data and would jump from 0% to 100%, diluting the bar.\n */\nexport function taskPrototypeHasOwnExecute(task: ITask): boolean {\n const Ctor = task.constructor as typeof Task;\n if (Ctor.isPassthrough) return false;\n return (\n Object.hasOwn(Ctor.prototype, \"execute\") ||\n Object.hasOwn(Ctor.prototype, \"executeStream\") ||\n task.hasChildren()\n );\n}\n\nexport type GraphSingleTaskResult<T> = {\n id: unknown;\n type: String;\n data: T;\n};\nexport type GraphResultArray<T> = Array<GraphSingleTaskResult<T>>;\nexport type PropertyArrayGraphResult<T> = ConvertAllToOptionalArray<T>;\nexport type AnyGraphResult<T> = PropertyArrayGraphResult<T> | GraphResultArray<T>;\n\nexport const PROPERTY_ARRAY = \"PROPERTY_ARRAY\" as const;\nexport const GRAPH_RESULT_ARRAY = \"GRAPH_RESULT_ARRAY\" as const;\n\nexport type GraphResultMap<T> = {\n // array of results with id for tasks that created them -- output is an array of {id, type, data}[]\n [GRAPH_RESULT_ARRAY]: GraphResultArray<T>;\n // property-array -- output is consolidation of each output property, with duplicate properties turned into an array\n [PROPERTY_ARRAY]: PropertyArrayGraphResult<T>;\n};\n\nexport type CompoundMergeStrategy = typeof PROPERTY_ARRAY | typeof GRAPH_RESULT_ARRAY;\n\nexport type GraphResult<\n Output,\n Merge extends CompoundMergeStrategy,\n> = GraphResultMap<Output>[Merge];\n\n/**\n * Class for running a task graph\n * Manages the execution of tasks in a task graph, including caching\n */\nexport class TaskGraphRunner {\n protected running = false;\n /**\n * Whether the task graph is currently running in preview mode.\n * Read by EdgeMaterializer via bracket access (`runner[\"previewRunning\"]`).\n */\n protected previewRunning = false;\n\n public readonly graph: TaskGraph;\n\n protected outputCache?: TaskOutputRepository;\n\n /**\n * True when the caller explicitly passed `outputCache: false` in the run\n * config, meaning all caching (including CACHE_REGISTRY-based routing) should\n * be suppressed. Distinct from `this.outputCache === undefined`, which just\n * means no legacy repo was configured (CACHE_REGISTRY may still apply).\n */\n protected legacyCacheExplicitlyDisabled: boolean = false;\n\n /**\n * Whether leaf tasks (no outgoing edges) should accumulate their streaming\n * output. True by default so workflow return values are complete.\n */\n protected accumulateLeafOutputs: boolean = true;\n /**\n * Service registry for this graph run.\n * Read by EdgeMaterializer via bracket access (`runner[\"registry\"]`).\n */\n protected registry: ServiceRegistry = globalServiceRegistry;\n\n protected resourceScope?: ResourceScope;\n\n /**\n * Per-run state. Set by handleStart, cleared by handleComplete/Error/Abort.\n * The only mutable per-run state on the facade — exists so the public abort()\n * and disable() methods (which take no arguments) have something to act on.\n */\n protected currentCtx?: RunContext;\n\n /**\n * Stable identifier for the current graph run. Threaded from\n * {@link TaskGraphRunConfig.runId} through handleStart so that each\n * per-task run call carries the same identifier.\n */\n protected runId?: string;\n\n /**\n * Run-private cache wrapper for the current run. Set by handleStart when a\n * runId and private cache slot are both present; cleared at the end of each\n * run. Used to fire-and-forget clearRun() after a successful run.\n */\n protected currentRunPrivate?: RunPrivateCacheRepo;\n protected baseRegistryForRun?: ServiceRegistry;\n\n protected readonly edgeMaterializer: EdgeMaterializer;\n\n protected readonly streamPump: StreamPump;\n\n /**\n * Read by EdgeMaterializer via bracket access (`runner[\"runScheduler\"]`).\n */\n protected readonly runScheduler: RunScheduler;\n\n constructor(\n graph: TaskGraph,\n outputCache?: TaskOutputRepository,\n protected processScheduler = new DependencyBasedScheduler(graph),\n protected previewScheduler = new TopologicalScheduler(graph)\n ) {\n this.graph = graph;\n // Wire the constructor cache into both the runner (used by runTask) and the\n // graph. Without `this.outputCache = outputCache`, a runner constructed as\n // `new TaskGraphRunner(graph, cache).runGraph()` would silently never cache\n // because runTask reads `this.outputCache`, not `graph.outputCache`.\n this.outputCache = outputCache;\n graph.outputCache = outputCache;\n this.edgeMaterializer = new EdgeMaterializer(graph, this);\n this.streamPump = new StreamPump(graph, this.processScheduler, this.edgeMaterializer);\n this.runScheduler = new RunScheduler(graph, this.processScheduler, this);\n this.streamPump.setRunScheduler(this.runScheduler);\n }\n\n // ========================================================================\n // Public methods\n // ========================================================================\n\n public async runGraph<ExecuteOutput extends TaskOutput>(\n input: TaskInput = {} as TaskInput,\n config?: TaskGraphRunConfig\n ): Promise<GraphResultArray<ExecuteOutput>> {\n const ownsScope = config?.resourceScope === undefined;\n const effectiveConfig: TaskGraphRunConfig = ownsScope\n ? {\n ...config,\n resourceScope: new ResourceScope({ strategy: config?.disposeStrategy }),\n }\n : config!;\n\n try {\n await this.handleStart(effectiveConfig);\n\n // Capture ctx locally — terminal handlers (handleAbort/Error/Complete)\n // clear this.currentCtx, but the abort signal listener may invoke\n // handleAbort while runGraph's loop or epilogue is still running.\n // The local reference keeps per-run state readable until runGraph returns.\n const ctx = this.currentCtx!;\n\n const results = await this.runScheduler.runLoop<ExecuteOutput>(\n input,\n effectiveConfig,\n ctx,\n this.edgeMaterializer\n );\n\n // Check graph-level timeout first — it is the root cause when tasks fail due\n // to the graph abort signal, and should take precedence over any task-level\n // TaskAbortedError that was placed in failedTaskErrors as a consequence.\n // Capture pendingGraphTimeoutError BEFORE calling handleAbort, which clears currentCtx.\n const pendingTimeout = ctx.pendingGraphTimeoutError;\n if (pendingTimeout) {\n await this.handleAbort();\n throw pendingTimeout;\n }\n if (ctx.failedTaskErrors.size > 0) {\n const latestError = ctx.failedTaskErrors.values().next().value!;\n await this.handleError(latestError);\n throw latestError;\n }\n if (ctx.abortController.signal.aborted) {\n await this.handleAbort();\n throw new TaskAbortedError();\n }\n\n await this.handleComplete();\n\n // Await cleanup of run-private cache entries so that a same-runId restart\n // immediately after this call cannot race against deletions.\n const runPrivateToClean = this.currentRunPrivate;\n this.currentRunPrivate = undefined;\n if (runPrivateToClean) {\n try {\n await runPrivateToClean.clearRun();\n } catch (e) {\n getLogger().warn(\"RunPrivateCacheRepo.clearRun failed\", { error: e });\n }\n }\n\n return this.filterLeafResults(results);\n } finally {\n if (ownsScope) {\n await effectiveConfig.resourceScope!.runComplete();\n // Only clear our auto-created reference. Caller-passed scopes keep the\n // caller's lifecycle; `handleStart` overwrites the field on the next\n // run anyway via `effectiveConfig`.\n this.resourceScope = undefined;\n }\n }\n }\n\n /**\n * Runs the task graph in preview mode\n * @param input Optional input to pass to root tasks (tasks with no incoming dataflows)\n * @param config Optional configuration for the preview run. Supports overriding the\n * ServiceRegistry (`registry`), providing an output cache (`outputCache`), passing an\n * abort signal (`parentSignal`), and controlling whether streaming leaf task outputs are\n * accumulated into the return value (`accumulateLeafOutputs`).\n * @returns A promise that resolves when all tasks are complete\n * @throws TaskConfigurationError if the graph is already running in preview\n */\n public async runGraphPreview<Output extends TaskOutput>(\n input: TaskInput = {} as TaskInput,\n config?: TaskGraphRunPreviewConfig\n ): Promise<GraphResultArray<Output>> {\n await this.handleStartPreview(config);\n\n // runPreview is on the UI preview hot path (fires per keystroke), so\n // instrumentation only runs when telemetry is enabled. Without the gate,\n // the four performance.now() calls per task and the per-run debug log\n // payload would burn cycles on every preview update.\n const telemetry = getTelemetryProvider();\n const telemetryEnabled = telemetry.isEnabled;\n const previewRunId = telemetryEnabled ? uuid4() : \"\";\n let previewSpan: ISpan | undefined;\n if (telemetryEnabled) {\n previewSpan = telemetry.startSpan(\"workglow.graph.runPreview\", {\n attributes: {\n \"workglow.graph.preview.run_id\": previewRunId,\n \"workglow.graph.task_count\": this.graph.getTasks().length,\n \"workglow.graph.dataflow_count\": this.graph.getDataflows().length,\n },\n });\n }\n\n const t0 = telemetryEnabled ? performance.now() : 0;\n const taskTimings: Array<{\n id: unknown;\n type: string;\n runPreviewMs: number;\n pushOutputMs: number;\n }> = [];\n\n const results: GraphResultArray<Output> = [];\n try {\n for await (const task of this.previewScheduler.tasks()) {\n const isRootTask = this.graph.getSourceDataflows(task.id).length === 0;\n\n if (task.status === TaskStatus.PENDING) {\n task.resetInputData();\n this.edgeMaterializer.copyInputFromEdgesToNode(task);\n // TODO: cacheable here??\n // if (task.cacheable) {\n // const results = await this.outputCache?.getOutput(\n // (task.constructor as any).type,\n // task.runInputData\n // );\n // if (results) {\n // task.runOutputData = results;\n // }\n // }\n }\n\n // For root tasks (no incoming dataflows), apply the input parameter\n // This is important for GraphAsTask subgraphs where the InputTask needs\n // to receive the parent's input values\n const taskInput = isRootTask ? input : {};\n\n if (telemetryEnabled) {\n const taskType = String(\n (task.constructor as any).runtype || (task.constructor as typeof Task).type || \"?\"\n );\n const tPreview = performance.now();\n const taskResult = await task.runPreview(taskInput);\n const runPreviewMs = performance.now() - tPreview;\n const tPush = performance.now();\n await this.edgeMaterializer.pushOutputFromNodeToEdges(task, taskResult);\n const pushOutputMs = performance.now() - tPush;\n taskTimings.push({ id: task.id, type: taskType, runPreviewMs, pushOutputMs });\n\n if (this.graph.getTargetDataflows(task.id).length === 0) {\n results.push({\n id: task.id,\n type: (task.constructor as any).runtype || (task.constructor as any).type,\n data: taskResult as Output,\n });\n }\n } else {\n const taskResult = await task.runPreview(taskInput);\n await this.edgeMaterializer.pushOutputFromNodeToEdges(task, taskResult);\n\n if (this.graph.getTargetDataflows(task.id).length === 0) {\n results.push({\n id: task.id,\n type: (task.constructor as any).runtype || (task.constructor as any).type,\n data: taskResult as Output,\n });\n }\n }\n }\n await this.handleCompletePreview();\n\n if (previewSpan) {\n const totalMs = performance.now() - t0;\n previewSpan.setAttributes({\n \"workglow.graph.preview.duration_ms\": Math.round(totalMs * 1000) / 1000,\n \"workglow.graph.preview.tasks_executed\": taskTimings.length,\n });\n previewSpan.setStatus(SpanStatusCode.OK);\n previewSpan.end();\n getLogger().debug(\"task graph runPreview timings\", {\n previewRunId,\n totalMs: Math.round(totalMs * 1000) / 1000,\n taskTimings,\n });\n }\n\n return this.filterLeafResults(results);\n } catch (error) {\n await this.handleErrorPreview();\n\n if (previewSpan) {\n const totalMs = performance.now() - t0;\n const message = error instanceof Error ? error.message : String(error);\n previewSpan.setAttributes({\n \"workglow.graph.preview.duration_ms\": Math.round(totalMs * 1000) / 1000,\n \"workglow.graph.preview.tasks_executed\": taskTimings.length,\n });\n previewSpan.setStatus(SpanStatusCode.ERROR, message);\n previewSpan.end();\n getLogger().debug(\"task graph runPreview failed\", {\n previewRunId,\n totalMs: Math.round(totalMs * 1000) / 1000,\n taskTimings,\n error,\n });\n }\n\n throw error;\n }\n }\n\n public abort(): void {\n this.currentCtx?.abortController.abort();\n }\n\n public async disable(): Promise<void> {\n await this.handleDisable();\n }\n\n /**\n * Adds input data to a task. Delegates to {@link Task.addInput} for the\n * actual merging logic.\n */\n public addInputData(task: ITask, overrides: Partial<TaskInput> | undefined): void {\n if (!overrides) return;\n\n const changed = task.addInput(overrides);\n\n // TODO(str): This is a hack.\n if (changed && \"regenerateGraph\" in task && typeof task.regenerateGraph === \"function\") {\n task.regenerateGraph();\n }\n }\n\n // ========================================================================\n // Protected Handlers\n // ========================================================================\n\n /**\n * When leaf results include tasks with `isGraphOutput`, returns only those.\n * Otherwise returns all leaf results unchanged.\n */\n protected filterLeafResults<T>(results: GraphResultArray<T>): GraphResultArray<T> {\n if (results.length <= 1) return results;\n const graphOutputResults = results.filter((r) => {\n const task = this.graph.getTask(r.id);\n return task && (task.constructor as typeof Task).isGraphOutput;\n });\n return graphOutputResults.length > 0 ? graphOutputResults : results;\n }\n\n public mergeExecuteOutputsToRunOutput<\n ExecuteOutput extends TaskOutput,\n Merge extends CompoundMergeStrategy = CompoundMergeStrategy,\n >(\n results: GraphResultArray<ExecuteOutput>,\n compoundMerge: Merge\n ): GraphResult<ExecuteOutput, Merge> {\n if (compoundMerge === GRAPH_RESULT_ARRAY) {\n return results as GraphResult<ExecuteOutput, Merge>;\n }\n\n if (compoundMerge === PROPERTY_ARRAY) {\n let fixedOutput = {} as PropertyArrayGraphResult<ExecuteOutput>;\n const outputs = results.map((result: any) => result.data);\n if (outputs.length === 1) {\n fixedOutput = outputs[0];\n } else if (outputs.length > 1) {\n const collected = collectPropertyValues<ExecuteOutput>(outputs as ExecuteOutput[]);\n if (Object.keys(collected).length > 0) {\n fixedOutput = collected;\n }\n }\n return fixedOutput as GraphResult<ExecuteOutput, Merge>;\n }\n throw new TaskConfigurationError(`Unknown compound merge strategy: ${compoundMerge}`);\n }\n\n protected async runTask<T>(task: ITask, input: TaskInput): Promise<GraphSingleTaskResult<T>> {\n const isStreamable = isTaskStreamable(task);\n\n // For pass-through streaming tasks: if the task is streamable and has\n // streaming input edges, tee each stream so one copy is forwarded to\n // the task's executeStream() (via inputStreams) while the other stays\n // on the edge for materialization by awaitStreamInputs.\n if (isStreamable) {\n this.streamPump.prepareStreamingInputs(task);\n }\n\n // Await any active streams on input dataflow edges so their values\n // are materialized before we read them. This applies to ALL downstream\n // tasks (both streaming and non-streaming) because copyInputFromEdgesToNode\n // reads via getPortData() which requires materialized values.\n // Streaming downstream tasks are still unblocked early by the scheduler\n // (they can start setup while upstream is streaming), but their actual\n // input data waits for upstream completion.\n await this.streamPump.awaitStreamInputs(task, this.registry);\n\n this.edgeMaterializer.copyInputFromEdgesToNode(task);\n\n // Runtime entitlement enforcement for tasks with dynamic entitlements\n if (\n this.currentCtx?.activeEnforcer &&\n (task.constructor as typeof Task).hasDynamicEntitlements\n ) {\n const denied = await this.currentCtx.activeEnforcer.checkTask(task);\n if (denied.length > 0) {\n throw new TaskEntitlementError(\n `Task ${(task.constructor as typeof Task).type} denied entitlements: ${denied.map(formatEntitlementDenial).join(\", \")}`\n );\n }\n }\n\n if (isStreamable) {\n return this.streamPump.runStreamingTask<T>(task, input, this.currentCtx!, {\n registry: this.registry,\n outputCache: this.outputCache,\n resourceScope: this.resourceScope,\n accumulateLeafOutputs: this.accumulateLeafOutputs,\n updateProgress: (t, p, m, ...a) =>\n this.runScheduler.handleProgress(this.currentCtx!, t, p, m, ...a),\n runId: this.runId,\n legacyCacheExplicitlyDisabled: this.legacyCacheExplicitlyDisabled,\n });\n }\n\n const results = await task.runner.run(input, {\n // When caching was explicitly disabled (outputCache: false in run config),\n // pass `false` so TaskRunner clears any stale cacheRegistry. Otherwise pass\n // `this.outputCache` (which may be undefined, letting TaskRunner use\n // CACHE_REGISTRY from the per-run ServiceRegistry).\n outputCache: this.legacyCacheExplicitlyDisabled ? false : this.outputCache,\n updateProgress: async (\n task: ITask,\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ) =>\n await this.runScheduler.handleProgress(this.currentCtx!, task, progress, message, ...args),\n registry: this.registry,\n resourceScope: this.resourceScope,\n runId: this.runId,\n });\n\n await this.edgeMaterializer.pushOutputFromNodeToEdges(task, results);\n\n return {\n id: task.id,\n type: (task.constructor as any).runtype || (task.constructor as any).type,\n data: results as T,\n };\n }\n\n /** Resets the task graph, recursively. */\n public resetGraph(graph: TaskGraph, runnerId: string) {\n graph.getTasks().forEach((node) => {\n this.edgeMaterializer.resetTask(graph, node, runnerId);\n node.regenerateGraph();\n if (node.hasChildren()) {\n this.resetGraph(node.subGraph, runnerId);\n }\n });\n graph.getDataflows().forEach((dataflow) => {\n dataflow.reset();\n });\n }\n\n /**\n * Tracks private cache repos that have already received the durability warning,\n * keyed by the repo instance. WeakSet so a freshly constructed repo that is no\n * longer referenced is automatically eligible for re-warning if it shows up\n * again later. Static because routing is repo-instance scoped, not runner\n * scoped — a process can have one durable repo and many `TaskGraphRunner`s.\n */\n private static __durabilityWarnedRepos = new WeakSet<object>();\n\n /**\n * Conservative two-tier detector that decides whether a graph may route any\n * task to the `private` cache slot. Used by both the durability warning and\n * the `runId`-required guard in {@link handleStart}.\n *\n * 1. Read the static `cachePolicy` off the task's constructor. If `kind` is\n * \"private\", the task is definitely private.\n * 2. Otherwise, if the task overrides `getCachePolicy` (i.e. its prototype's\n * method is not `Task.prototype.getCachePolicy`), conservatively treat it\n * as potentially private — the override may decide based on inputs that\n * are not available at graph-start time.\n *\n * Note: probing `getCachePolicy({} as any)` is unsafe because input-dependent\n * overrides can throw or return the wrong branch when given empty inputs.\n */\n public static graphUsesPrivatePolicy(graph: TaskGraph): boolean {\n return graph.getTasks().some((t) => {\n const ctor = t.constructor as typeof Task;\n if (ctor.cachePolicy?.kind === \"private\") return true;\n // Override detection: prototype method differs from Task.prototype's.\n const proto = ctor.prototype as { getCachePolicy?: unknown };\n if (\n typeof proto.getCachePolicy === \"function\" &&\n proto.getCachePolicy !== Task.prototype.getCachePolicy\n ) {\n return true;\n }\n return false;\n });\n }\n\n protected async handleStart(config?: TaskGraphRunConfig): Promise<void> {\n // Setup registry — create child from global if not provided\n if (config?.registry !== undefined) {\n this.registry = config.registry;\n } else if (this.registry === undefined) {\n this.registry = new ServiceRegistry(globalServiceRegistry.container.createChildContainer());\n }\n if (config?.resourceScope !== undefined) {\n this.resourceScope = config.resourceScope;\n }\n this.baseRegistryForRun = this.registry;\n\n // Store run identifier for per-task propagation.\n this.runId = config?.runId;\n\n // Warn once per non-durable private repo (across runs) when at least one\n // task in the graph routes to the private slot. This catches the\n // dev-mode-in-production misconfiguration where an in-memory store is wired\n // for convenience but restart-survival is expected. Rate-limited via a\n // WeakSet keyed by the repo instance so repeated `runGraph` calls against\n // the same registry do not flood the log.\n if (this.registry.has(CACHE_REGISTRY)) {\n const checkRegistry = this.registry.get(CACHE_REGISTRY);\n if (checkRegistry.private && !checkRegistry.private.isDurable()) {\n if (TaskGraphRunner.graphUsesPrivatePolicy(this.graph)) {\n const repo = checkRegistry.private as object;\n if (!TaskGraphRunner.__durabilityWarnedRepos.has(repo)) {\n TaskGraphRunner.__durabilityWarnedRepos.add(repo);\n getLogger().warn(\n \"TaskGraphRunner: private cache repo may be used but is non-durable — \" +\n \"restart-survival will not work. Ensure the CacheRegistry 'private' \" +\n \"slot is backed by a durable storage backend.\"\n );\n }\n }\n }\n\n // Strict guard: if the graph contains a private-policy task but no runId\n // was provided, we cannot namespace writes — they would land directly in\n // the shared private repo and collide across runs. TaskGraphRunner is the\n // documented owner of runId, so this is a configuration error.\n if (!this.runId && checkRegistry.private) {\n if (TaskGraphRunner.graphUsesPrivatePolicy(this.graph)) {\n throw new TaskConfigurationError(\n \"TaskGraphRunner: graph contains a private-policy task but no runId was provided. \" +\n \"Provide `runId` in TaskGraphRunConfig so private cache entries can be namespaced.\"\n );\n }\n }\n }\n\n // If there is a private cache slot and a runId, wrap the private slot in a\n // RunPrivateCacheRepo so all tasks in this run see a namespaced view of the\n // backing store. Build a child ServiceRegistry that overrides CACHE_REGISTRY\n // for this run only; the parent registry is unchanged.\n if (this.runId && this.registry.has(CACHE_REGISTRY)) {\n const baseRegistry = this.registry.get(CACHE_REGISTRY);\n if (baseRegistry.private) {\n const wrappedPrivate = new RunPrivateCacheRepo({\n backing: baseRegistry.private,\n runId: this.runId,\n });\n // Retain a reference so runGraph can fire-and-forget clearRun() after success.\n this.currentRunPrivate = wrappedPrivate;\n const wrappedRegistry = new DefaultCacheRegistry({\n deterministic: baseRegistry.deterministic,\n private: wrappedPrivate,\n });\n const childContainer = this.registry.container.createChildContainer();\n const runtimeServices = new ServiceRegistry(childContainer);\n // Copy all registrations from parent into child, then override CACHE_REGISTRY.\n runtimeServices.registerInstance(CACHE_REGISTRY, wrappedRegistry);\n this.registry = runtimeServices;\n\n // Register a disposal marker in the resource scope so the run boundary is\n // documented and callers can attach connection-bearing disposers on the same key.\n this.resourceScope?.register(`cache:private:${this.runId}`, async () => {\n // intentionally empty — RunPrivateCacheRepo has no resources of its own\n });\n }\n }\n\n this.accumulateLeafOutputs = config?.accumulateLeafOutputs !== false;\n\n if (config?.outputCache !== undefined) {\n if (typeof config.outputCache === \"boolean\") {\n if (config.outputCache === true) {\n this.outputCache = this.registry.get(TASK_OUTPUT_REPOSITORY);\n this.legacyCacheExplicitlyDisabled = false;\n } else {\n // outputCache: false — suppress all caching, including CACHE_REGISTRY.\n this.outputCache = undefined;\n this.legacyCacheExplicitlyDisabled = true;\n }\n } else {\n this.outputCache = config.outputCache;\n this.legacyCacheExplicitlyDisabled = false;\n }\n this.graph.outputCache = this.outputCache;\n } else {\n // No explicit outputCache in this run's config — preserve existing legacy\n // repo (if any) but do not disable CACHE_REGISTRY routing.\n this.legacyCacheExplicitlyDisabled = false;\n }\n\n // Prevent reentrancy\n if (this.running || this.previewRunning) {\n throw new TaskConfigurationError(\"Graph is already running\");\n }\n\n this.running = true;\n\n // Build per-run context (handles abortController + parentSignal wiring)\n const ctx = new RunContext(config?.parentSignal);\n this.currentCtx = ctx;\n\n ctx.abortController.signal.addEventListener(\"abort\", () => {\n this.handleAbort();\n });\n\n // Set up graph-level timeout if configured\n if (config?.timeout !== undefined) {\n this.runScheduler.armGraphTimeout(config.timeout, ctx);\n }\n\n // Notify the disposal strategy that a new run is starting. Inactivity\n // strategies clear any pending idle timers here, closing the race\n // window where a stale timer armed at the previous runComplete could\n // dispose a resource the new run is about to touch.\n if (this.resourceScope) {\n await this.resourceScope.runStart();\n }\n\n // Early-out if parent signal was already aborted (RunContext constructor\n // already aborted ctx.abortController in that case)\n if (ctx.abortController.signal.aborted) return;\n\n this.resetGraph(this.graph, ctx.runId);\n this.processScheduler.reset();\n // (in-progress maps + failedTaskErrors start empty on a fresh RunContext)\n\n try {\n if (config?.maxTasks !== undefined && config.maxTasks > 0) {\n const taskCount = this.graph.getTasks().length;\n if (taskCount > config.maxTasks) {\n throw new TaskConfigurationError(\n `Graph has ${taskCount} tasks, exceeding the limit of ${config.maxTasks}`\n );\n }\n }\n\n if (config?.enforceEntitlements) {\n if (!this.registry.has(ENTITLEMENT_ENFORCER)) {\n throw new TaskConfigurationError(\n \"enforceEntitlements is enabled but no IEntitlementEnforcer is registered. \" +\n \"Register an enforcer via ENTITLEMENT_ENFORCER before running the graph.\"\n );\n }\n const enforcer = this.registry.get(ENTITLEMENT_ENFORCER);\n const denied = await enforcer.checkAll(computeGraphEntitlements(this.graph));\n if (denied.length > 0) {\n throw new TaskEntitlementError(\n `Denied entitlements: ${denied.map(formatEntitlementDenial).join(\", \")}`\n );\n }\n ctx.activeEnforcer = enforcer;\n }\n } catch (err) {\n this.runScheduler.clearGraphTimeout(ctx);\n ctx.dispose();\n this.currentCtx = undefined;\n this.running = false;\n throw err;\n }\n\n const telemetry = getTelemetryProvider();\n if (telemetry.isEnabled) {\n ctx.telemetrySpan = telemetry.startSpan(\"workglow.graph.run\", {\n attributes: {\n \"workglow.graph.run_id\": ctx.runId,\n \"workglow.graph.task_count\": this.graph.getTasks().length,\n \"workglow.graph.dataflow_count\": this.graph.getDataflows().length,\n },\n });\n }\n\n this.graph.emit(\"start\");\n }\n\n protected async handleStartPreview(config?: TaskGraphRunConfig): Promise<void> {\n if (this.previewRunning) {\n throw new TaskConfigurationError(\"Graph is already running in preview\");\n }\n\n // Use explicit registry if provided; otherwise keep the existing one\n // (which is either globalServiceRegistry by default, or whatever handleStart set).\n if (config?.registry !== undefined) {\n this.registry = config.registry;\n }\n\n // Validate graph size limits (same as handleStart)\n if (config?.maxTasks !== undefined && config.maxTasks > 0) {\n const taskCount = this.graph.getTasks().length;\n if (taskCount > config.maxTasks) {\n throw new TaskConfigurationError(\n `Graph has ${taskCount} tasks, exceeding the limit of ${config.maxTasks}`\n );\n }\n }\n\n // Note: `timeout` is not enforced for preview runs. Preview execution is\n // event-driven with no single completion point, so a graph-level timeout\n // does not apply. Use per-task timeouts for individual task time limits.\n\n this.previewScheduler.reset();\n this.previewRunning = true;\n }\n\n protected clearGraphTimeout(): void {\n if (this.currentCtx) {\n this.runScheduler.clearGraphTimeout(this.currentCtx);\n }\n }\n\n protected async handleComplete(): Promise<void> {\n this.clearGraphTimeout();\n const ctx = this.currentCtx;\n this.running = false;\n\n if (ctx?.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.OK);\n ctx.telemetrySpan.end();\n }\n ctx?.dispose();\n this.currentCtx = undefined;\n if (this.baseRegistryForRun !== undefined) {\n this.registry = this.baseRegistryForRun;\n this.baseRegistryForRun = undefined;\n }\n\n this.graph.emit(\"complete\");\n }\n\n protected async handleCompletePreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n protected async handleError(error: TaskError): Promise<void> {\n this.clearGraphTimeout();\n await Promise.allSettled(\n this.graph.getTasks().map(async (task: ITask) => {\n if (task.status === TaskStatus.PROCESSING || task.status === TaskStatus.STREAMING) {\n return task.abort();\n }\n })\n );\n // Do NOT clear run-private entries on failure — left for restart / janitor TTL sweep.\n this.currentRunPrivate = undefined;\n const ctx = this.currentCtx;\n this.running = false;\n\n if (ctx?.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.ERROR, error.message);\n ctx.telemetrySpan.setAttributes({ \"workglow.graph.error\": error.message });\n ctx.telemetrySpan.end();\n }\n ctx?.dispose();\n this.currentCtx = undefined;\n if (this.baseRegistryForRun !== undefined) {\n this.registry = this.baseRegistryForRun;\n this.baseRegistryForRun = undefined;\n }\n\n this.graph.emit(\"error\", error);\n }\n\n protected async handleErrorPreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n /**\n * Handles task graph abortion.\n *\n * Single-fire: invoked from both the abort-signal listener installed in\n * `handleStart` and the `runGraph` epilogue when `signal.aborted`. Without\n * a guard, observers see two `\"abort\"` events for one logical abort. We\n * latch on `this.running` synchronously so the second caller is a no-op.\n */\n protected async handleAbort(): Promise<void> {\n if (!this.running) return;\n this.running = false;\n this.clearGraphTimeout();\n await Promise.allSettled(\n this.graph.getTasks().map(async (task: ITask) => {\n if (task.status === TaskStatus.PROCESSING || task.status === TaskStatus.STREAMING) {\n return task.abort();\n }\n })\n );\n // Do NOT clear run-private entries on abort — left for restart / janitor TTL sweep.\n this.currentRunPrivate = undefined;\n const ctx = this.currentCtx;\n\n if (ctx?.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.ERROR, \"aborted\");\n ctx.telemetrySpan.addEvent(\"workglow.graph.aborted\");\n ctx.telemetrySpan.end();\n }\n ctx?.dispose();\n this.currentCtx = undefined;\n if (this.baseRegistryForRun !== undefined) {\n this.registry = this.baseRegistryForRun;\n this.baseRegistryForRun = undefined;\n }\n\n this.graph.emit(\"abort\");\n }\n\n protected async handleAbortPreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n protected async handleDisable(): Promise<void> {\n await Promise.allSettled(\n this.graph.getTasks().map(async (task: ITask) => {\n if (task.status === TaskStatus.PENDING) {\n return task.disable();\n }\n })\n );\n this.running = false;\n this.graph.emit(\"disabled\");\n }\n}\n",
|
|
17
|
-
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\n\nexport interface CacheJanitorOptions {\n privateBacking: TaskOutputRepository;\n}\n\n/**\n * Periodic cleanup helper for run-private cache entries left behind by runs\n * that crashed and were never restarted.\n *\n * Run-private rows are namespaced by `RunPrivateCacheRepo` with the
|
|
18
|
-
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport type CachePolicy = { kind: \"deterministic\" } | { kind: \"private\" } | { kind: \"none\" };\n\nexport const DEFAULT_CACHE_POLICY: CachePolicy = { kind: \"deterministic\" };\n\nexport function isPolicyCached(policy: CachePolicy): boolean {\n return policy.kind !== \"none\";\n}\n\nexport function isPolicyPrivate(policy: CachePolicy): boolean {\n return policy.kind === \"private\";\n}\n",
|
|
24
|
+
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\n\nexport interface CacheJanitorOptions {\n privateBacking: TaskOutputRepository;\n}\n\n/**\n * Periodic cleanup helper for run-private cache entries left behind by runs\n * that crashed and were never restarted.\n *\n * Run-private rows are namespaced by `RunPrivateCacheRepo` with the\n * `__run:${runId}::${taskId}` prefix. This janitor sweeps those rows when they are older than\n * `olderThanMs`. Entries lacking the prefix (deterministic cache, shared tier)\n * are not touched.\n *\n * Apps schedule the sweep themselves (cron, periodic worker, on startup) —\n * libs does not run it automatically.\n */\nexport class CacheJanitor {\n private readonly privateBacking: TaskOutputRepository;\n\n constructor({ privateBacking }: CacheJanitorOptions) {\n this.privateBacking = privateBacking;\n }\n\n async sweepStaleRunPrivate(olderThanMs: number): Promise<void> {\n await this.privateBacking.clearOlderThanWithTaskTypePrefix(\"__run:\", olderThanMs);\n }\n}\n",
|
|
19
25
|
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createServiceToken } from \"@workglow/util\";\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\n\n/**\n * Two-slot registry of task output repositories selected by `CachePolicy.kind`.\n *\n * - `deterministic` — shared cache for tasks whose outputs are determined entirely\n * by their inputs. Same inputs → same outputs, safe to share across runs and\n * (in app deployments like builder) across projects.\n * - `private` — per-run cache for tasks producing non-deterministic outputs worth\n * keeping (e.g., image generation without a seed). Namespaced by `runId` so\n * two runs of the same workflow do not see each other's data.\n *\n * Both slots are optional. When a slot is unset, caching for matching tasks is\n * a silent no-op — the task still runs correctly, just uncached.\n */\nexport interface CacheRegistry {\n deterministic?: TaskOutputRepository;\n private?: TaskOutputRepository;\n}\n\nexport const CACHE_REGISTRY = createServiceToken<CacheRegistry>(\"taskgraph.cacheRegistry\");\n\nexport class DefaultCacheRegistry implements CacheRegistry {\n public deterministic?: TaskOutputRepository;\n public private?: TaskOutputRepository;\n\n constructor(init: Partial<CacheRegistry> = {}) {\n this.deterministic = init.deterministic;\n this.private = init.private;\n }\n}\n",
|
|
20
26
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createServiceToken, EventEmitter, EventParameters } from \"@workglow/util\";\nimport { TaskInput, TaskOutput } from \"../task/TaskTypes\";\n\nexport const TASK_OUTPUT_REPOSITORY = createServiceToken<TaskOutputRepository>(\n \"taskgraph.taskOutputRepository\"\n);\n\nexport type TaskOutputEventListeners = {\n output_saved: (taskType: string) => void;\n output_retrieved: (taskType: string) => void;\n output_cleared: () => void;\n output_pruned: () => void;\n};\n\nexport type TaskOutputEvents = keyof TaskOutputEventListeners;\n\nexport type TaskOutputEventListener<Event extends TaskOutputEvents> =\n TaskOutputEventListeners[Event];\n\nexport type TaskOutputEventParameters<Event extends TaskOutputEvents> = EventParameters<\n TaskOutputEventListeners,\n Event\n>;\n\n/**\n * Abstract class for managing task outputs in a repository\n * Provides methods for saving, retrieving, and clearing task outputs\n */\nexport abstract class TaskOutputRepository {\n outputCompression: boolean;\n\n constructor({ outputCompression = true }) {\n this.outputCompression = outputCompression;\n }\n\n private get events() {\n if (!this._events) {\n this._events = new EventEmitter<TaskOutputEventListeners>();\n }\n return this._events;\n }\n private _events: EventEmitter<TaskOutputEventListeners> | undefined;\n\n on<Event extends TaskOutputEvents>(name: Event, fn: TaskOutputEventListener<Event>) {\n this.events.on(name, fn);\n }\n\n off<Event extends TaskOutputEvents>(name: Event, fn: TaskOutputEventListener<Event>) {\n this.events.off(name, fn);\n }\n\n waitOn<Event extends TaskOutputEvents>(name: Event) {\n return this.events.waitOn(name) as Promise<TaskOutputEventParameters<Event>>;\n }\n\n emit<Event extends TaskOutputEvents>(name: Event, ...args: TaskOutputEventParameters<Event>) {\n this._events?.emit(name, ...args);\n }\n\n /**\n * Persist a task output keyed by `(taskType, fingerprint(inputs))`.\n *\n * Backing implementations upsert by primary key (last-writer-wins). For\n * deterministic cache entries (`CachePolicy.kind === \"deterministic\"`) this\n * is benign because all writers produce equal values. Run-private writes\n * are single-writer-per-runId in practice (one worker per run), so the\n * upsert behavior is also fine there.\n */\n abstract saveOutput(\n taskType: string,\n inputs: TaskInput,\n output: TaskOutput,\n createdAt?: Date // for testing purposes\n ): Promise<void>;\n\n abstract getOutput(taskType: string, inputs: TaskInput): Promise<TaskOutput | undefined>;\n\n abstract clear(): Promise<void>;\n\n abstract size(): Promise<number>;\n\n abstract clearOlderThan(olderThanInMs: number): Promise<void>;\n\n /**\n * Whether entries written to this repository will survive a process crash / restart.\n *\n * Used by the task runner to warn when `kind: \"private\"` tasks are configured with a\n * non-durable backing store (e.g., in-memory) — restart-survival, which is the whole\n * point of the private cache tier, will not actually work in that case.\n */\n abstract isDurable(): boolean;\n\n /**\n * Delete every entry whose `taskType` starts with `prefix`. Used by\n * `RunPrivateCacheRepo.clearRun()` to delete entries for a specific `runId`.\n *\n * Default implementation throws — backing repositories that support run-private\n * caching MUST override this.\n */\n async deleteByTaskTypePrefix(_prefix: string): Promise<void> {\n throw new Error(\n `${this.constructor.name}: deleteByTaskTypePrefix is not supported by this repository.`\n );\n }\n\n /**\n * Delete entries whose `taskType` starts with `prefix` and were created more\n * than `olderThanMs` ago. Used by `CacheJanitor.sweepStaleRunPrivate()`.\n *\n * Default implementation throws — backing repositories that support periodic\n * janitor sweeps of run-private rows MUST override this.\n */\n async clearOlderThanWithTaskTypePrefix(_prefix: string, _olderThanMs: number): Promise<void> {\n throw new Error(\n `${this.constructor.name}: clearOlderThanWithTaskTypePrefix is not supported by this repository.`\n );\n }\n\n /**\n * Count entries whose `taskType` starts with `prefix`. Used by\n * `RunPrivateCacheRepo.size()` so the wrapper's count reflects only its own\n * namespaced view rather than the entire backing store.\n *\n * Default implementation throws — backing repositories that support run-private\n * caching MUST override this.\n */\n async sizeByTaskTypePrefix(_prefix: string): Promise<number> {\n throw new Error(\n `${this.constructor.name}: sizeByTaskTypePrefix is not supported by this repository.`\n );\n }\n}\n",
|
|
21
|
-
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { TaskInput, TaskOutput } from \"../task/TaskTypes\";\n\nexport interface RunPrivateCacheRepoOptions {\n backing: TaskOutputRepository;\n runId: string;\n}\n\n/**\n * Wraps a TaskOutputRepository so that all entries are namespaced by `runId`.\n *\n * Namespacing happens at the `taskType` axis: rows are stored
|
|
27
|
+
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { TaskInput, TaskOutput } from \"../task/TaskTypes\";\n\nexport interface RunPrivateCacheRepoOptions {\n backing: TaskOutputRepository;\n runId: string;\n}\n\n/**\n * Wraps a TaskOutputRepository so that all entries are namespaced by `runId`.\n *\n * Namespacing happens at the repository's `taskType` axis: {@link CacheCoordinator}\n * passes each task's instance `id` for private-policy entries, so rows are stored\n * as `__run:${runId}::${taskId}` in the backing store. The input fingerprint is\n * unchanged for resume lookups within the same node.\n *\n * - Two wrappers with the same `runId` (e.g., a restart after a crash) see each\n * other's writes via the backing store — that's the restart-survival contract.\n * - Two wrappers with different `runId`s see only their own entries.\n */\nexport class RunPrivateCacheRepo extends TaskOutputRepository {\n private readonly backing: TaskOutputRepository;\n private readonly runId: string;\n\n constructor({ backing, runId }: RunPrivateCacheRepoOptions) {\n super({ outputCompression: backing.outputCompression });\n this.backing = backing;\n this.runId = runId;\n }\n\n private ns(cacheIdentity: string): string {\n return `__run:${this.runId}::${cacheIdentity}`;\n }\n\n public async saveOutput(\n cacheIdentity: string,\n inputs: TaskInput,\n output: TaskOutput,\n createdAt?: Date\n ): Promise<void> {\n await this.backing.saveOutput(this.ns(cacheIdentity), inputs, output, createdAt);\n }\n\n public async getOutput(\n cacheIdentity: string,\n inputs: TaskInput\n ): Promise<TaskOutput | undefined> {\n return this.backing.getOutput(this.ns(cacheIdentity), inputs);\n }\n\n /**\n * Override of `TaskOutputRepository.clear()` that only deletes entries\n * namespaced under THIS wrapper's `runId`. Entries from other runs are not\n * touched. Use the backing repository directly if you need a global clear.\n */\n public async clear(): Promise<void> {\n await this.clearRun();\n }\n\n /**\n * Delete every entry written through this wrapper's `runId`. Called by the\n * graph runner after a successful run, and by the janitor for stale runs.\n * Requires the backing repository to implement `deleteByTaskTypePrefix`.\n */\n public async clearRun(): Promise<void> {\n await this.backing.deleteByTaskTypePrefix(`__run:${this.runId}::`);\n }\n\n /**\n * Returns the count of entries namespaced under THIS wrapper's `runId`.\n * Consistent with `saveOutput`/`getOutput`/`clear()` being run-scoped.\n */\n public async size(): Promise<number> {\n return this.backing.sizeByTaskTypePrefix(`__run:${this.runId}::`);\n }\n\n /**\n * Override of `TaskOutputRepository.clearOlderThan()` scoped to THIS\n * wrapper's `runId`. Without the scope override, the wrapper would\n * accidentally prune the entire backing store (including deterministic\n * cache entries and other runs' private rows).\n */\n public async clearOlderThan(olderThanInMs: number): Promise<void> {\n await this.backing.clearOlderThanWithTaskTypePrefix(`__run:${this.runId}::`, olderThanInMs);\n }\n\n public isDurable(): boolean {\n return this.backing.isDurable();\n }\n}\n",
|
|
22
28
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createServiceToken } from \"@workglow/util\";\nimport type { EntitlementPolicy, EntitlementRule } from \"./EntitlementPolicy\";\nimport { evaluatePolicy } from \"./EntitlementPolicy\";\nimport type { IEntitlementResolver } from \"./EntitlementResolver\";\nimport { PERMISSIVE_RESOLVER } from \"./EntitlementResolver\";\nimport type { ITask } from \"./ITask\";\nimport type { Task } from \"./Task\";\nimport type { EntitlementGrant, TaskEntitlement, TaskEntitlements } from \"./TaskEntitlements\";\n\n// ========================================================================\n// Denial Type\n// ========================================================================\n\n/**\n * Why an entitlement was denied.\n * - `policy-deny`: matched a deny rule\n * - `default-deny`: no rule covered the entitlement\n * - `user-deny`: matched an ask rule and the resolver returned \"deny\"\n */\nexport type EntitlementDenialReason = \"policy-deny\" | \"default-deny\" | \"user-deny\";\n\n/**\n * A single denied entitlement with the reason and the matching rule (if any).\n * Returned by `IEntitlementEnforcer` to give callers enough context to build\n * actionable error messages without re-running policy evaluation.\n *\n * Discriminated union on `reason`:\n * - `policy-deny`: `matchedRule` is always present (it is the deny rule that matched).\n * - `user-deny`: `matchedRule` is always present (it is the ask rule that matched).\n * - `default-deny`: no rule matched at all; `matchedRule` is absent.\n */\nexport type EntitlementDenial =\n | {\n readonly entitlement: TaskEntitlement;\n readonly reason: \"policy-deny\";\n /** The deny rule that explicitly blocked this entitlement. */\n readonly matchedRule: EntitlementRule;\n }\n | {\n readonly entitlement: TaskEntitlement;\n readonly reason: \"default-deny\";\n }\n | {\n readonly entitlement: TaskEntitlement;\n readonly reason: \"user-deny\";\n /** The ask rule that triggered the user prompt. */\n readonly matchedRule: EntitlementRule;\n };\n\n/** Format a denial for inclusion in an error message. */\nexport function formatEntitlementDenial(denial: EntitlementDenial): string {\n switch (denial.reason) {\n case \"policy-deny\":\n return `${denial.entitlement.id} (denied by rule ${denial.matchedRule.id})`;\n case \"user-deny\":\n return `${denial.entitlement.id} (denied by user)`;\n case \"default-deny\":\n return `${denial.entitlement.id} (no matching grant)`;\n }\n}\n\n// ========================================================================\n// Enforcer Interface\n// ========================================================================\n\n/**\n * Interface for checking whether required entitlements are granted.\n * Register a custom implementation via the ServiceRegistry to enforce entitlements.\n *\n * Methods are async because resolving \"ask\" verdicts may require user interaction.\n */\nexport interface IEntitlementEnforcer {\n /**\n * Preflight check: evaluate all required entitlements against the policy.\n * Resolves \"ask\" verdicts via the resolver (prompt + save).\n * Returns the list of denials (non-optional entitlements only) — empty array when all granted.\n */\n checkAll(required: TaskEntitlements): Promise<readonly EntitlementDenial[]>;\n\n /**\n * Runtime check: evaluate a single task's dynamic entitlements.\n * Called during execution for tasks with `hasDynamicEntitlements`.\n */\n checkTask(task: ITask): Promise<readonly EntitlementDenial[]>;\n}\n\n// ========================================================================\n// Default Enforcers\n// ========================================================================\n\n/** Default permissive enforcer — grants everything. */\nexport const PERMISSIVE_ENFORCER: IEntitlementEnforcer = {\n checkAll: async () => [],\n checkTask: async () => [],\n};\n\n/**\n * Creates an enforcer from a unified entitlement policy with deny/grant/ask rules.\n *\n * Evaluation order: Deny → Grant → Ask → Default(deny).\n *\n * @param policy - The policy defining deny, grant, and ask rules\n * @param resolver - Pluggable resolver for handling \"ask\" verdicts. Defaults to PERMISSIVE_RESOLVER.\n */\nexport function createPolicyEnforcer(\n policy: EntitlementPolicy,\n resolver: IEntitlementResolver = PERMISSIVE_RESOLVER\n): IEntitlementEnforcer {\n async function resolveAsks(\n required: TaskEntitlements,\n taskType?: string,\n taskId?: unknown\n ): Promise<readonly EntitlementDenial[]> {\n const results = evaluatePolicy(policy, required);\n const denied: EntitlementDenial[] = [];\n\n for (const result of results) {\n if (result.verdict === \"denied\") {\n if (result.matchedRule) {\n denied.push({\n entitlement: result.entitlement,\n reason: \"policy-deny\",\n matchedRule: result.matchedRule,\n });\n } else {\n denied.push({ entitlement: result.entitlement, reason: \"default-deny\" });\n }\n } else if (result.verdict === \"ask\") {\n const request = {\n entitlement: result.entitlement,\n taskType: taskType ?? \"unknown\",\n taskId: taskId ?? \"unknown\",\n };\n // Check saved answer first; otherwise prompt and save\n let answer = resolver.lookup(request);\n if (answer === undefined) {\n answer = await resolver.prompt(request);\n resolver.save(request, answer);\n }\n if (answer === \"deny\") {\n // ask verdicts always have a matchedRule (the ask rule that fired)\n if (!result.matchedRule) {\n throw new Error(\n `Invariant violation: ask verdict for \"${result.entitlement.id}\" is missing matchedRule`\n );\n }\n denied.push({\n entitlement: result.entitlement,\n reason: \"user-deny\",\n matchedRule: result.matchedRule,\n });\n }\n }\n // \"granted\" — nothing to do\n }\n\n return denied;\n }\n\n return {\n async checkAll(required: TaskEntitlements): Promise<readonly EntitlementDenial[]> {\n return resolveAsks(required);\n },\n\n async checkTask(task: ITask): Promise<readonly EntitlementDenial[]> {\n const entitlements = task.entitlements();\n return resolveAsks(entitlements, (task.constructor as typeof Task).type, task.id);\n },\n };\n}\n\n/**\n * Creates an enforcer from scoped grants that support resource-level matching.\n * This is a convenience wrapper around `createPolicyEnforcer` with no deny or ask rules.\n *\n * Optional entitlements are never denied.\n */\nexport function createScopedEnforcer(grants: readonly EntitlementGrant[]): IEntitlementEnforcer {\n return createPolicyEnforcer({ deny: [], grant: grants, ask: [] });\n}\n\n/**\n * Creates an enforcer from a list of entitlement ID strings (broad grants).\n * Entitlement hierarchy is respected: granting \"network\" covers \"network:http\".\n * All grants are broad (no resource scoping). Optional entitlements are never denied.\n */\nexport function createGrantListEnforcer(grants: readonly string[]): IEntitlementEnforcer {\n return createScopedEnforcer(grants.map((id) => ({ id })));\n}\n\n// ========================================================================\n// Service Token\n// ========================================================================\n\n/** Service token for registering an entitlement enforcer in the ServiceRegistry */\nexport const ENTITLEMENT_ENFORCER = createServiceToken<IEntitlementEnforcer>(\n \"workglow.entitlementEnforcer\"\n);\n",
|
|
23
29
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {\n EntitlementGrant,\n EntitlementId,\n TaskEntitlement,\n TaskEntitlements,\n} from \"./TaskEntitlements\";\nimport { entitlementCovers, grantCoversResources } from \"./TaskEntitlements\";\n\n// ========================================================================\n// Policy Types\n// ========================================================================\n\n/**\n * A rule matching entitlements by ID and optional resource patterns.\n * Used for deny and ask rules. Same shape as EntitlementGrant.\n */\nexport interface EntitlementRule {\n readonly id: EntitlementId;\n /** Resource patterns (glob-style). When undefined, matches broadly. */\n readonly resources?: readonly string[];\n}\n\n/**\n * A unified entitlement policy combining deny, grant, and ask rules.\n *\n * Evaluation order: Deny → Grant → Ask → Default(deny).\n * - Deny rules override everything — if matched, the entitlement is denied.\n * - Grant rules auto-allow without prompting.\n * - Ask rules trigger a resolver to prompt the user.\n * - If no rule matches, the entitlement is denied.\n */\nexport interface EntitlementPolicy {\n /** Hard denials — checked first, override grants */\n readonly deny: readonly EntitlementRule[];\n /** Grants — auto-allowed without prompting */\n readonly grant: readonly EntitlementGrant[];\n /** Ask rules — require user approval via a resolver */\n readonly ask: readonly EntitlementRule[];\n}\n\n/**\n * The result of evaluating a single entitlement against a policy.\n */\nexport type EntitlementVerdict = \"granted\" | \"denied\" | \"ask\";\n\n/**\n * Per-entitlement result from policy evaluation.\n */\nexport interface EntitlementCheckResult {\n readonly verdict: EntitlementVerdict;\n readonly entitlement: TaskEntitlement;\n /** The rule that produced this verdict (for debugging/UI). Undefined when default-denied. */\n readonly matchedRule?: EntitlementRule;\n}\n\n/** An empty policy that denies everything (no grants, no denies, no asks). */\nexport const EMPTY_POLICY: EntitlementPolicy = Object.freeze({\n deny: Object.freeze([]),\n grant: Object.freeze([]),\n ask: Object.freeze([]),\n});\n\n// ========================================================================\n// Policy Evaluation\n// ========================================================================\n\n/**\n * Check if a rule covers a required entitlement.\n * Uses the same hierarchy and resource matching as grants:\n * - Rule ID must cover the entitlement ID (via `entitlementCovers`)\n * - Rule resources must cover the entitlement resources (via `grantCoversResources`)\n */\nfunction ruleCovers(rule: EntitlementRule, required: TaskEntitlement): boolean {\n if (!entitlementCovers(rule.id, required.id)) return false;\n return grantCoversResources(rule as EntitlementGrant, required);\n}\n\n/**\n * Evaluates a policy against a set of required entitlements.\n *\n * For each required entitlement (skipping optional ones):\n * 1. If any deny rule matches → `\"denied\"`\n * 2. If any grant rule matches → `\"granted\"`\n * 3. If any ask rule matches → `\"ask\"`\n * 4. Otherwise → `\"denied\"` (default deny)\n *\n * This is a pure function with no side effects.\n */\nexport function evaluatePolicy(\n policy: EntitlementPolicy,\n required: TaskEntitlements\n): readonly EntitlementCheckResult[] {\n const results: EntitlementCheckResult[] = [];\n\n for (const entitlement of required.entitlements) {\n if (entitlement.optional) continue;\n\n // 1. Check deny rules first\n const denyMatch = policy.deny.find((rule) => ruleCovers(rule, entitlement));\n if (denyMatch) {\n results.push({ verdict: \"denied\", entitlement, matchedRule: denyMatch });\n continue;\n }\n\n // 2. Check grant rules\n const grantMatch = policy.grant.find((rule) => ruleCovers(rule, entitlement));\n if (grantMatch) {\n results.push({ verdict: \"granted\", entitlement, matchedRule: grantMatch });\n continue;\n }\n\n // 3. Check ask rules\n const askMatch = policy.ask.find((rule) => ruleCovers(rule, entitlement));\n if (askMatch) {\n results.push({ verdict: \"ask\", entitlement, matchedRule: askMatch });\n continue;\n }\n\n // 4. Default deny\n results.push({ verdict: \"denied\", entitlement });\n }\n\n return results;\n}\n\n/**\n * Pure single-entitlement check. Convenience wrapper around `evaluatePolicy`\n * for callers that want the `can(action, resource)` style verdict in one call.\n *\n * Returns the per-entitlement check result with `verdict` (`\"granted\"`, `\"denied\"`,\n * or `\"ask\"`) and the `matchedRule` that produced it. No side effects — no\n * resolver is invoked even for `\"ask\"` verdicts; the caller decides how to\n * handle that.\n */\nexport function can(\n policy: EntitlementPolicy,\n id: EntitlementId,\n resources?: readonly string[]\n): EntitlementCheckResult {\n const required: TaskEntitlement = resources !== undefined ? { id, resources } : { id };\n // evaluatePolicy skips optional entitlements; we always pass a non-optional one.\n const [result] = evaluatePolicy(policy, { entitlements: [required] });\n return result;\n}\n",
|
|
24
30
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createServiceToken } from \"@workglow/util\";\nimport type { TaskEntitlement } from \"./TaskEntitlements\";\nimport type { TaskIdType } from \"./TaskTypes\";\n\n// ========================================================================\n// Resolver Types\n// ========================================================================\n\n/**\n * A request to the resolver for a user decision on an entitlement.\n */\nexport interface EntitlementAskRequest {\n /** The entitlement that needs a decision */\n readonly entitlement: TaskEntitlement;\n /** The task type requesting the entitlement */\n readonly taskType: string;\n /** The task instance ID requesting the entitlement */\n readonly taskId: TaskIdType;\n}\n\n/**\n * A user's answer to an entitlement ask.\n */\nexport type EntitlementAnswer = \"grant\" | \"deny\";\n\n// ========================================================================\n// Resolver Interface\n// ========================================================================\n\n/**\n * Pluggable interface for handling \"ask\" entitlement verdicts.\n *\n * The resolver is responsible for:\n * - Checking if a saved answer exists (`lookup`)\n * - Prompting the user for a decision (`prompt`)\n * - Persisting the user's answer for future lookups (`save`)\n *\n * Implementations vary by environment:\n * - Builder app: shows a dialog, persists answers per-project\n * - CLI: prints to terminal, saves in config\n * - Tests: use PERMISSIVE_RESOLVER or DENY_ALL_RESOLVER\n */\nexport interface IEntitlementResolver {\n /** Check if there's a saved answer for this ask. Returns undefined if not saved. */\n lookup(request: EntitlementAskRequest): EntitlementAnswer | undefined;\n /** Prompt the user and return their answer. May block on UI. */\n prompt(request: EntitlementAskRequest): Promise<EntitlementAnswer>;\n /** Save a user's answer for future lookups. */\n save(request: EntitlementAskRequest, answer: EntitlementAnswer): void;\n}\n\n// ========================================================================\n// Built-in Resolvers\n// ========================================================================\n\n/** Grants all asks without prompting. Useful for tests and permissive environments. */\nexport const PERMISSIVE_RESOLVER: IEntitlementResolver = {\n lookup: () => \"grant\",\n prompt: async () => \"grant\",\n save: () => {},\n};\n\n/** Denies all asks without prompting. Useful for locked-down environments. */\nexport const DENY_ALL_RESOLVER: IEntitlementResolver = {\n lookup: () => \"deny\",\n prompt: async () => \"deny\",\n save: () => {},\n};\n\n// ========================================================================\n// Service Token\n// ========================================================================\n\n/** Service token for registering an entitlement resolver in the ServiceRegistry */\nexport const ENTITLEMENT_RESOLVER = createServiceToken<IEntitlementResolver>(\n \"workglow.entitlementResolver\"\n);\n",
|
|
25
31
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchema, JsonSchema } from \"@workglow/util/schema\";\n\n/**\n * Stream mode determines how a task's streaming output is interpreted:\n * - `none`: No streaming (default). `execute()` returns `Promise<Output>`.\n * - `append`: Each chunk is a delta (e.g., a new token).\n * - `replace`: Each chunk is a corrected/revised snapshot of the complete output so far.\n * - `object`: Each chunk is a progressively more complete partial object snapshot.\n * - `mixed`: Multiple ports use different stream modes (e.g., append + object).\n *\n * Declared per-port via the `x-stream` schema extension property.\n * Absent `x-stream` = `\"none\"`.\n */\nexport type StreamMode = \"none\" | \"append\" | \"replace\" | \"object\" | \"mixed\";\n\n/**\n * Append mode: delta chunk (consumer accumulates).\n * `port` identifies which output port this delta belongs to.\n */\nexport type StreamTextDelta = {\n type: \"text-delta\";\n port: string;\n textDelta: string;\n};\n\n/**\n * Object delta for structured/object streaming.\n * `port` identifies which output port this delta belongs to.\n *\n * - **Non-array** (e.g. structured generation): each `objectDelta` is a\n * progressively more complete partial object snapshot. Consumers should\n * replace (not merge) their state with the latest delta.\n * - **Array** (e.g. tool calls): each `objectDelta` is a single-element\n * array containing one item to upsert by `id` into the accumulated array.\n */\nexport type StreamObjectDelta = {\n type: \"object-delta\";\n port: string;\n objectDelta: Record<string, unknown> | unknown[];\n};\n\n/**\n * Replace mode: full snapshot chunk (replaces previous state).\n */\nexport type StreamSnapshot<Output = Record<string, any>> = {\n type: \"snapshot\";\n data: Output;\n};\n\n/**\n * Signals that the stream has finished. In append mode, the runner\n * accumulates text-delta chunks into the append port (determined by\n * the output schema's `x-stream: \"append\"` annotation); `data` may\n * carry additional fields (merged into the final output).\n * In replace mode, `data` contains the final output.\n */\nexport type StreamFinish<Output = Record<string, any>> = {\n type: \"finish\";\n data: Output;\n};\n\n/**\n * Signals that the stream encountered an error.\n */\nexport type StreamError = {\n type: \"error\";\n error: Error;\n};\n\n/**\n * Phase / status event yielded by a streaming source to signal a named\n * phase transition (e.g. \"Preparing\", \"Generating\", \"Tool: search\").\n *\n * Carries an optional `progress` percentage for phases where progress\n * is measurable (e.g. \"Loading model\" with fractional percent), or\n * absent for indeterminate phases.\n *\n * Phase events are metadata, not data:\n * - They are emitted on `stream_chunk` for observability.\n * - They are NOT accumulated into dataflow edges.\n * - They are NOT included in the `finish` payload.\n * - The TaskRunner translates each phase event into a single\n * `progress` event with the phase's `progress` and `message`.\n * - They do NOT flip the task status to STREAMING; only data events\n * (`text-delta` / `object-delta` / `snapshot`) do.\n */\nexport type StreamPhase = {\n type: \"phase\";\n message: string;\n progress: number | undefined;\n};\n\n/**\n * Discriminated union of all stream event types.\n * Used as the element type for `AsyncIterable<StreamEvent>` streams\n * flowing through the DAG.\n */\nexport type StreamEvent<Output = Record<string, any>> =\n | StreamTextDelta\n | StreamObjectDelta\n | StreamSnapshot<Output>\n | StreamFinish<Output>\n | StreamError\n | StreamPhase;\n\n// ========================================================================\n// Port-level stream helpers\n// ========================================================================\n\n/**\n * Reads the `x-stream` value from a specific port property in a DataPortSchema.\n * Returns `\"none\"` when the property or the `x-stream` annotation is absent.\n *\n * @param schema - The task's input or output DataPortSchema\n * @param portId - The property name (port ID) to inspect\n * @returns The StreamMode declared on that port\n */\nexport function getPortStreamMode(schema: DataPortSchema | JsonSchema, portId: string): StreamMode {\n if (typeof schema === \"boolean\") return \"none\";\n const prop = (schema.properties as Record<string, any>)?.[portId];\n if (!prop || typeof prop === \"boolean\") return \"none\";\n const xStream = prop[\"x-stream\"];\n if (xStream === \"append\" || xStream === \"replace\" || xStream === \"object\") return xStream;\n return \"none\";\n}\n\n/**\n * Returns all ports that declare an `x-stream` annotation, along with their mode.\n *\n * @param schema - The task's output (or input) DataPortSchema\n * @returns Array of `{ port, mode }` for every annotated port\n */\nexport function getStreamingPorts(\n schema: DataPortSchema\n): Array<{ port: string; mode: StreamMode }> {\n if (typeof schema === \"boolean\") return [];\n const props = schema.properties;\n if (!props) return [];\n\n const result: Array<{ port: string; mode: StreamMode }> = [];\n for (const [name, prop] of Object.entries(props)) {\n if (!prop || typeof prop === \"boolean\") continue;\n const xStream = (prop as any)[\"x-stream\"];\n if (xStream === \"append\" || xStream === \"replace\" || xStream === \"object\") {\n result.push({ port: name, mode: xStream });\n }\n }\n return result;\n}\n\n/**\n * Returns the dominant output stream mode for a task by inspecting its output schema.\n * Returns `\"mixed\"` when ports use different modes (e.g., append + object).\n * Returns `\"none\"` if no output port declares streaming.\n */\nexport function getOutputStreamMode(outputSchema: DataPortSchema): StreamMode {\n const ports = getStreamingPorts(outputSchema);\n if (ports.length === 0) return \"none\";\n\n const mode = ports[0].mode;\n for (let i = 1; i < ports.length; i++) {\n if (ports[i].mode !== mode) {\n return \"mixed\";\n }\n }\n return mode;\n}\n\n/**\n * Determines whether a task supports streaming by checking if any output port\n * has an `x-stream` annotation AND the task implements `executeStream()`.\n *\n * @param task - The task to inspect (must have `outputSchema()` and optionally `executeStream`)\n * @returns true if the task can produce streaming output\n */\nexport function isTaskStreamable(task: {\n outputSchema(): DataPortSchema;\n executeStream?: (...args: any[]) => any;\n}): boolean {\n if (typeof task.executeStream !== \"function\") return false;\n return getOutputStreamMode(task.outputSchema()) !== \"none\";\n}\n\n/**\n * Returns the port ID (property name) of the first output port that declares\n * `x-stream: \"append\"`, or `undefined` if no such port exists.\n *\n * @param schema - The task's output DataPortSchema\n * @returns The port name with append streaming, or undefined\n */\nexport function getAppendPortId(schema: DataPortSchema): string | undefined {\n if (typeof schema === \"boolean\") return undefined;\n const props = schema.properties;\n if (!props) return undefined;\n\n for (const [name, prop] of Object.entries(props)) {\n if (!prop || typeof prop === \"boolean\") continue;\n if ((prop as any)[\"x-stream\"] === \"append\") return name;\n }\n return undefined;\n}\n\n/**\n * Determines whether a dataflow edge needs to accumulate stream events\n * into a materialized value for the target port.\n *\n * Accumulation is needed when:\n * - The source output port declares streaming (`x-stream` is set)\n * - AND the target input port does NOT accept the same stream mode\n *\n * @param sourceSchema - Output schema of the source task\n * @param sourcePort - Port ID on the source task\n * @param targetSchema - Input schema of the target task\n * @param targetPort - Port ID on the target task\n * @returns true if the edge should accumulate; false if stream can pass through\n */\nexport function edgeNeedsAccumulation(\n sourceSchema: DataPortSchema,\n sourcePort: string,\n targetSchema: DataPortSchema,\n targetPort: string\n): boolean {\n const sourceMode = getPortStreamMode(sourceSchema, sourcePort);\n if (sourceMode === \"none\") return false;\n const targetMode = getPortStreamMode(targetSchema, targetPort);\n return sourceMode !== targetMode;\n}\n\n/**\n * Returns the port ID (property name) of the first output port that declares\n * `x-stream: \"object\"`, or `undefined` if no such port exists.\n *\n * @param schema - The task's output DataPortSchema\n * @returns The port name with object streaming, or undefined\n */\nexport function getObjectPortId(schema: DataPortSchema): string | undefined {\n if (typeof schema === \"boolean\") return undefined;\n const props = schema.properties;\n if (!props) return undefined;\n\n for (const [name, prop] of Object.entries(props)) {\n if (!prop || typeof prop === \"boolean\") continue;\n if ((prop as any)[\"x-stream\"] === \"object\") return name;\n }\n return undefined;\n}\n\n/**\n * Returns a map of port names to their JSON Schemas for every output port\n * that declares `\"x-structured-output\": true`.\n *\n * @param schema - The task's output DataPortSchema\n * @returns Map of port-name → JSON Schema for structured output ports\n */\nexport function getStructuredOutputSchemas(schema: DataPortSchema): Map<string, JsonSchema> {\n const result = new Map<string, JsonSchema>();\n if (typeof schema === \"boolean\") return result;\n const props = schema.properties;\n if (!props) return result;\n\n for (const [name, prop] of Object.entries(props)) {\n if (!prop || typeof prop === \"boolean\") continue;\n if ((prop as any)[\"x-structured-output\"] === true) {\n result.set(name, prop as JsonSchema);\n }\n }\n return result;\n}\n\n/**\n * Returns true if the schema has any output port with `\"x-structured-output\": true`.\n */\nexport function hasStructuredOutput(schema: DataPortSchema): boolean {\n return getStructuredOutputSchemas(schema).size > 0;\n}\n",
|
|
26
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { deepEqual, EventEmitter, uuid4 } from \"@workglow/util\";\nimport type { DataPortSchema, SchemaNode } from \"@workglow/util/schema\";\nimport { compileSchema } from \"@workglow/util/schema\";\nimport { type CachePolicy, DEFAULT_CACHE_POLICY } from \"../cache/CachePolicy\";\nimport { DATAFLOW_ALL_PORTS } from \"../task-graph/Dataflow\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport type { IExecuteContext, IExecutePreviewContext, IRunConfig, ITask } from \"./ITask\";\nimport { EMPTY_ENTITLEMENTS, type TaskEntitlements } from \"./TaskEntitlements\";\nimport {\n TaskAbortedError,\n TaskConfigurationError,\n TaskError,\n TaskInvalidInputError,\n TaskSerializationError,\n} from \"./TaskError\";\nimport type {\n TaskEventListener,\n TaskEventListeners,\n TaskEventParameters,\n TaskEvents,\n} from \"./TaskEvents\";\nimport type { JsonTaskItem, TaskGraphItemJson, TaskGraphJsonOptions } from \"./TaskJSON\";\nimport { TaskRunner } from \"./TaskRunner\";\nimport type { TaskConfig, TaskIdType, TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\nimport { TaskConfigSchema, TaskStatus } from \"./TaskTypes\";\n\n/**\n * Base class for all tasks that implements the ITask interface.\n * This abstract class provides common functionality for both simple and compound tasks.\n *\n * The Task class is responsible for:\n * 1. Defining what a task is (inputs, outputs, configuration)\n * 2. Providing the execution logic (via execute and executePreview)\n * 3. Delegating the running logic to a TaskRunner\n */\nexport class Task<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends TaskConfig = TaskConfig,\n> implements ITask<Input, Output, Config> {\n // ========================================================================\n // Static properties - should be overridden by subclasses\n // ========================================================================\n\n public static type: TaskTypeName = \"Task\";\n\n public static category: string = \"Hidden\";\n\n public static title: string = \"\";\n\n public static description: string = \"\";\n\n public static cacheable: boolean = true;\n\n /**\n * Version number for this task class, used to bust the output cache when the task's\n * implementation changes. Increment when a change would produce different outputs for\n * the same inputs. Combined with ancestor versions via getCacheVersion().\n * Subclasses should override this when their execute() logic changes in a\n * backwards-incompatible way (different output for same input).\n */\n public static version: number = 1;\n\n /**\n * Default cache policy for this task class. Used by `getCachePolicy()` when the\n * task does not override the method. Subclasses with side effects should set\n * `{ kind: \"none\" }`; tasks producing non-deterministic-but-expensive outputs\n * (e.g., image generation without a seed) should set `{ kind: \"private\" }`.\n */\n public static cachePolicy: CachePolicy = { kind: \"deterministic\" };\n\n /**\n * Whether this task has dynamic input/output schemas that can change at runtime.\n * Tasks with dynamic schemas should override instance methods for inputSchema() and/or outputSchema()\n * and emit 'schemaChange' events when their schemas change.\n */\n public static hasDynamicSchemas: boolean = false;\n\n /**\n * When true, dynamically added input ports (via the universal \"Add Input\" handle in the builder)\n * are mirrored as output ports of the same name and type. Set this on pass-through tasks that\n * forward their additional inputs to their outputs unchanged.\n */\n public static passthroughInputsToOutputs: boolean = false;\n\n /**\n * When true, this task can be saved as a custom task with a preset configuration.\n * Tasks that have meaningful user-facing config options beyond the base fields should set this.\n */\n public static customizable: boolean = false;\n\n /**\n * When true, this task defines the graph's output. The graph runner will\n * collect results only from tasks with this flag when they exist among the\n * leaf nodes; otherwise it falls back to collecting from all leaves.\n */\n public static isGraphOutput: boolean = false;\n\n /**\n * When true, this task does no real work — it only forwards inputs to outputs\n * (e.g. `InputTask`, `OutputTask`). Such tasks are excluded from graph-level\n * progress averaging because they jump from 0% to 100% and would dilute the bar.\n */\n public static isPassthrough: boolean = false;\n\n /**\n * Whether this task has dynamic entitlements that can change at runtime.\n * Tasks with dynamic entitlements should override the instance entitlements() method\n * and emit 'entitlementChange' events when their entitlements change.\n */\n public static hasDynamicEntitlements: boolean = false;\n\n /**\n * Entitlements required by this task class.\n * Subclasses override to declare their permission requirements.\n */\n public static entitlements(): TaskEntitlements {\n return EMPTY_ENTITLEMENTS;\n }\n\n public static inputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n } as const satisfies DataPortSchema;\n }\n\n public static outputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n } as const satisfies DataPortSchema;\n }\n\n /**\n * Config schema for this task. Subclasses that add config properties MUST override this\n * and spread TaskConfigSchema[\"properties\"] into their own properties object.\n */\n public static configSchema(): DataPortSchema {\n return TaskConfigSchema;\n }\n\n // ========================================================================\n // Task Execution Methods - Core logic provided by subclasses\n // ========================================================================\n\n /**\n * The actual task execution logic for subclasses to override\n *\n * @param input The input to the task\n * @param config The configuration for the task\n * @throws TaskError if the task fails\n * @returns The output of the task or undefined if no changes\n */\n public async execute(_input: Input, context: IExecuteContext): Promise<Output | undefined> {\n if (context.signal?.aborted) {\n throw new TaskAbortedError(\"Task aborted\");\n }\n return undefined;\n }\n\n /**\n * Default implementation of executePreview that does nothing.\n * Subclasses should override this to provide actual preview functionality.\n *\n * This is generally for UI updating, and should be lightweight.\n * @param input The input to the task\n * @returns The preview output, or undefined for \"no preview update\"\n */\n public async executePreview(\n _input: Input,\n _context: IExecutePreviewContext\n ): Promise<Output | undefined> {\n return undefined;\n }\n\n // ========================================================================\n // TaskRunner delegation - Executes and manages the task\n // ========================================================================\n\n /**\n * The TaskGraph that owns this task, set by {@link TaskGraph#addTask}.\n * Used by {@link TaskRunner#runPreviewStream} to locate upstream tasks\n * and subscribe to their streaming events.\n */\n public parentGraph?: TaskGraph;\n\n protected _runner: TaskRunner<Input, Output, Config> | undefined;\n\n public get runner(): TaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new TaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n /**\n * Runs the task and returns the output\n * Delegates to the task runner\n *\n * @param overrides Optional input overrides\n * @param runConfig Optional per-call run configuration (merged with task's runConfig)\n * @throws TaskError if the task fails\n * @returns The task output\n */\n async run(overrides: Partial<Input> = {}, runConfig: Partial<IRunConfig> = {}): Promise<Output> {\n return this.runner.run(overrides, { ...this.runConfig, ...runConfig });\n }\n\n /**\n * Runs the task in preview mode. Delegates to the task runner.\n */\n public async runPreview(overrides: Partial<Input> = {}): Promise<Output> {\n return this.runner.runPreview(overrides);\n }\n\n public abort(): void {\n this.runner.abort();\n }\n\n public async disable(): Promise<void> {\n await this.runner.disable();\n }\n\n // ========================================================================\n // Static to Instance conversion methods\n // ========================================================================\n\n public inputSchema(): DataPortSchema {\n return (this.constructor as typeof Task).inputSchema();\n }\n\n public outputSchema(): DataPortSchema {\n return (this.constructor as typeof Task).outputSchema();\n }\n\n public configSchema(): DataPortSchema {\n return (this.constructor as typeof Task).configSchema();\n }\n\n /**\n * Gets entitlements for this task instance.\n * For tasks with dynamic entitlements, override this to compute based on config/state.\n */\n public entitlements(): TaskEntitlements {\n return (this.constructor as typeof Task).entitlements();\n }\n\n /**\n * Emits an entitlementChange event when the task's required entitlements change.\n * Call this from tasks with dynamic entitlements when their configuration changes\n * in a way that affects their entitlements.\n */\n protected emitEntitlementChange(entitlements?: TaskEntitlements): void {\n const final = entitlements ?? this.entitlements();\n this.emit(\"entitlementChange\", final);\n }\n\n public get type(): TaskTypeName {\n return (this.constructor as typeof Task).type;\n }\n\n public get category(): string {\n return (this.constructor as typeof Task).category;\n }\n\n public get title(): string {\n return this.config?.title ?? (this.constructor as typeof Task).title;\n }\n\n public get description(): string {\n return this.config?.description ?? (this.constructor as typeof Task).description;\n }\n\n /**\n * Whether this task instance is currently cacheable. Reads `runConfig.cacheable`\n * and `config.cacheable` first (per-instance overrides for back-compat), then\n * derives from `getCachePolicy(runInputData)`.\n *\n * Note: for tasks that override `getCachePolicy(inputs)` with input-dependent\n * logic (e.g., `AiImageOutputTask` returns `private` when seed is absent), the\n * value of `task.cacheable` can change as `runInputData` changes. Prefer calling\n * `getCachePolicy(inputs)` directly when you have explicit inputs.\n */\n public get cacheable(): boolean {\n if (this.runConfig?.cacheable !== undefined) return this.runConfig.cacheable;\n if (this.config?.cacheable !== undefined) return this.config.cacheable;\n return this.getCachePolicy((this.runInputData ?? {}) as unknown as Input).kind !== \"none\";\n }\n\n /**\n * Returns a dot-separated string of version numbers collected from each class in the\n * prototype chain (leaf first) that declares its own `version` static property.\n * Every class that owns a `version` contributes one segment, including the base Task\n * class. Returns \"1\" when called directly on a Task instance with no subclassing\n * (Task.version === 1 is the sole contributor).\n *\n * Use this as the cache-key version component: when any ancestor's version changes,\n * the combined string changes and the cached output is invalidated.\n */\n public getCacheVersion(): string {\n const versions: number[] = [];\n let ctor: unknown = this.constructor;\n while (ctor && ctor !== Function.prototype) {\n if (\n Object.prototype.hasOwnProperty.call(ctor, \"version\") &&\n typeof (ctor as { version?: unknown }).version === \"number\"\n ) {\n versions.push((ctor as { version: number }).version);\n }\n ctor = Object.getPrototypeOf(ctor as object);\n }\n if (versions.length === 0) versions.push(1);\n return versions.join(\".\");\n }\n\n /**\n * Returns the effective cache policy for this task given its inputs.\n *\n * Resolution order:\n * 1. Per-instance `runConfig.cacheable === false` or `config.cacheable === false`\n * → `{ kind: \"none\" }` (callsite opt-out wins).\n * 2. Class-static `cacheable === false` (declared on the subclass) →\n * `{ kind: \"none\" }`. The coarse on/off flag remains supported alongside\n * the canonical `cachePolicy`; setting it on the class is equivalent\n * to declaring `static cachePolicy: CachePolicy = { kind: \"none\" }`.\n * 3. Class-static `cachePolicy` if declared.\n * 4. {@link DEFAULT_CACHE_POLICY}.\n *\n * Override for dynamic decisions (e.g., AiImageOutputTask returns `private`\n * when seed is absent).\n */\n public getCachePolicy(_inputs: Input): CachePolicy {\n const ctor = this.constructor as typeof Task;\n if (this.runConfig?.cacheable === false || this.config?.cacheable === false)\n return { kind: \"none\" };\n if (\n Object.prototype.hasOwnProperty.call(ctor, \"cacheable\") &&\n (ctor as { cacheable?: unknown }).cacheable === false &&\n !Object.prototype.hasOwnProperty.call(ctor, \"cachePolicy\")\n ) {\n return { kind: \"none\" };\n }\n return ctor.cachePolicy ?? DEFAULT_CACHE_POLICY;\n }\n\n // ========================================================================\n // Instance properties using @template types\n // ========================================================================\n\n /**\n * Default input values for this task.\n * If no overrides at run time, then this would be equal to the input.\n * resetInputData() will reset inputs to these defaults.\n */\n defaults: Record<string, any>;\n\n /**\n * The input to the task at the time of the task run.\n * This takes defaults from construction time and overrides from run time.\n * It is the input that created the output.\n */\n runInputData: Record<string, any> = {};\n\n /**\n * The output of the task at the time of the task run.\n * This is the result of the task execution.\n */\n runOutputData: Record<string, any> = {};\n\n // ========================================================================\n // Task state properties\n // ========================================================================\n\n config: Config;\n\n /**\n * Frozen snapshot of config at construction time, used by toJSON and\n * as the resolution source for re-runs (so fresh lookups use original IDs).\n */\n readonly originalConfig: Readonly<Record<string, unknown>> | undefined;\n\n public get id(): unknown {\n return this.config.id;\n }\n\n /**\n * Runtime configuration (not serialized with the task).\n * Set via the constructor's third argument or mutated by the graph runner.\n */\n runConfig: Partial<IRunConfig> = {};\n\n status: TaskStatus = TaskStatus.PENDING;\n\n /**\n * Current progress, 0..100 for measured progress, `undefined` for\n * indeterminate. Initialized to 0 (not started).\n */\n progress: number | undefined = 0;\n\n createdAt: Date = new Date();\n\n startedAt?: Date;\n\n completedAt?: Date;\n\n error?: TaskError;\n\n public get events(): EventEmitter<TaskEventListeners> {\n if (!this._events) {\n this._events = new EventEmitter<TaskEventListeners>();\n }\n return this._events;\n }\n protected _events: EventEmitter<TaskEventListeners> | undefined;\n\n /**\n * Creates a new task instance\n *\n * @param config Configuration for the task (includes defaults for input values)\n * @param runConfig Runtime configuration for the task\n */\n constructor(config: NoInfer<Partial<Config>> = {}, runConfig: NoInfer<Partial<IRunConfig>> = {}) {\n const { defaults: callerDefaultInputs, ...restConfig } = config as Partial<Config> & {\n defaults?: Partial<Input>;\n };\n\n const inputDefaults = this.getDefaultInputsFromStaticInputDefinitions();\n const mergedDefaults = Object.assign(inputDefaults, callerDefaultInputs ?? {});\n // Strip symbol properties (like [$JSONSchema]) before storing defaults\n this.defaults = this.stripSymbols(mergedDefaults) as Record<string, any>;\n this.resetInputData();\n\n const title = (this.constructor as typeof Task).title || undefined;\n const baseConfig = Object.assign(\n {\n ...(title ? { title } : {}),\n },\n restConfig\n ) as Config;\n if (baseConfig.id === undefined) {\n (baseConfig as Record<string, unknown>).id = uuid4();\n }\n this.config = this.validateAndApplyConfigDefaults(baseConfig);\n try {\n this.originalConfig = Object.freeze(structuredClone(this.config) as Record<string, unknown>);\n } catch {\n // Config contains non-cloneable values (e.g. functions).\n // canSerializeConfig() should return false for such tasks.\n this.originalConfig = undefined;\n }\n\n this.runConfig = runConfig;\n\n // Reject input schemas that declare a `__cv` port: this name is reserved by\n // CacheCoordinator.buildKey for the cache version sentinel. Allowing a task\n // to declare it would silently shadow cache versioning and cause cache\n // collisions across versions. `inputSchema()` can legally return a boolean\n // (see addInput/setInput handling); skip the check in that case.\n const inputSchema = (this.constructor as typeof Task).inputSchema();\n if (\n inputSchema &&\n typeof inputSchema !== \"boolean\" &&\n inputSchema.properties &&\n Object.prototype.hasOwnProperty.call(inputSchema.properties, \"__cv\")\n ) {\n throw new TaskConfigurationError(\n `Task \"${(this.constructor as typeof Task).type}\": input port name '__cv' is reserved ` +\n `for cache versioning. Rename the port to avoid collision with the cache key sentinel.`\n );\n }\n }\n\n // ========================================================================\n // Input/Output handling\n // ========================================================================\n\n getDefaultInputsFromStaticInputDefinitions(): Partial<Input> {\n const schema = this.inputSchema();\n if (typeof schema === \"boolean\") {\n return {};\n }\n try {\n const compiledSchema = this.getInputSchemaNode();\n const defaultData = compiledSchema.getData(undefined, {\n addOptionalProps: true,\n removeInvalidData: false,\n useTypeDefaults: false,\n });\n return (defaultData || {}) as Partial<Input>;\n } catch (error) {\n console.warn(\n `Failed to compile input schema for ${this.type}, falling back to manual extraction:`,\n error\n );\n // Fallback to manual extraction if compilation fails\n return Object.entries(schema.properties || {}).reduce<Record<string, any>>(\n (acc, [id, prop]) => {\n const defaultValue = (prop as any).default;\n if (defaultValue !== undefined) {\n acc[id] = defaultValue;\n }\n return acc;\n },\n {}\n ) as Partial<Input>;\n }\n }\n\n public resetInputData(): void {\n this.runInputData = this.smartClone(this.defaults) as Record<string, any>;\n }\n\n /**\n * Smart clone that deep-clones plain objects and arrays while preserving\n * class instances (objects with non-Object prototype) by reference.\n * Detects and throws an error on circular references.\n *\n * This is necessary because:\n * - structuredClone cannot clone class instances (methods are lost)\n * - JSON.parse/stringify loses methods and fails on circular references\n * - Class instances like repositories should be passed by reference\n *\n * This breaks the idea of everything being json serializable, but it allows\n * more efficient use cases. Do be careful with this though! Use sparingly.\n *\n * @param obj The object to clone\n * @param visited Set of objects in the current cloning path (for circular reference detection)\n * @returns A cloned object with class instances preserved by reference\n */\n private smartClone(obj: any, visited: WeakSet<object> = new WeakSet()): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n // Primitives (string, number, boolean, symbol, bigint) are returned as-is\n if (typeof obj !== \"object\") {\n return obj;\n }\n\n // Check for circular references\n if (visited.has(obj)) {\n throw new TaskConfigurationError(\n \"Circular reference detected in input data. \" +\n \"Cannot clone objects with circular references.\"\n );\n }\n\n // Clone TypedArrays (Float32Array, Int8Array, etc.) to avoid shared-mutation\n // between defaults and runInputData, while preserving DataView by reference.\n if (ArrayBuffer.isView(obj)) {\n // Preserve DataView instances by reference (constructor signature differs)\n if (typeof DataView !== \"undefined\" && obj instanceof DataView) {\n return obj;\n }\n // For TypedArrays, create a new instance with the same data\n const typedArray = obj as any;\n return new (typedArray.constructor as any)(typedArray);\n }\n\n // Preserve class instances (objects with non-Object/non-Array prototype)\n // This includes repository instances, custom classes, etc.\n if (!Array.isArray(obj)) {\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) {\n return obj; // Pass by reference\n }\n }\n\n // Add object to visited set before recursing\n visited.add(obj);\n\n try {\n // Deep clone arrays, preserving class instances within\n if (Array.isArray(obj)) {\n return obj.map((item) => this.smartClone(item, visited));\n }\n\n // Deep clone plain objects\n const result: Record<string, any> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = this.smartClone(obj[key], visited);\n }\n }\n return result;\n } finally {\n // Remove from visited set after processing to allow the same object\n // in different branches (non-circular references)\n visited.delete(obj);\n }\n }\n\n public setDefaults(defaults: Partial<Input>): void {\n // Strip symbol properties (like [$JSONSchema]) before storing defaults\n this.defaults = this.stripSymbols(defaults) as Partial<Input>;\n }\n\n public setInput(input: Partial<Input>): void {\n const schema = this.inputSchema();\n if (typeof schema === \"boolean\") {\n if (schema === true) {\n for (const [inputId, value] of Object.entries(input)) {\n if (value !== undefined) {\n this.runInputData[inputId] = value;\n }\n }\n }\n return;\n }\n const properties = schema.properties || {};\n\n for (const [inputId, prop] of Object.entries(properties)) {\n if (input[inputId] !== undefined) {\n this.runInputData[inputId] = input[inputId];\n } else if (\n this.runInputData[inputId] === undefined &&\n (prop as { default?: unknown }).default !== undefined\n ) {\n this.runInputData[inputId] = prop.default;\n }\n }\n\n // If additionalProperties is true, also copy any additional input properties\n if (schema.additionalProperties) {\n for (const [inputId, value] of Object.entries(input)) {\n if (!(inputId in properties)) {\n this.runInputData[inputId] = value;\n }\n }\n }\n }\n\n /**\n * Adds/merges input data during graph execution.\n * Unlike {@link setInput}, this method:\n * - Detects changes using deep equality\n * - Accumulates array values (appends rather than replaces)\n * - Handles DATAFLOW_ALL_PORTS for pass-through\n * - Handles additionalProperties for dynamic schemas\n *\n * @param overrides The input data to merge\n * @returns true if any input data was changed, false otherwise\n */\n public addInput(overrides: Partial<Input> | undefined): boolean {\n if (!overrides) return false;\n\n let changed = false;\n const inputSchema = this.inputSchema();\n\n if (typeof inputSchema === \"boolean\") {\n if (inputSchema === false) {\n return false;\n }\n // Schema is `true` - accept any input\n for (const [key, value] of Object.entries(overrides)) {\n if (!deepEqual(this.runInputData[key], value)) {\n this.runInputData[key] = value;\n changed = true;\n }\n }\n return changed;\n }\n\n const properties = inputSchema.properties || {};\n\n for (const [inputId, prop] of Object.entries(properties)) {\n if (inputId === DATAFLOW_ALL_PORTS) {\n this.runInputData = { ...this.runInputData, ...overrides };\n changed = true;\n } else {\n if (overrides[inputId] === undefined) continue;\n const isArray =\n (prop as any)?.type === \"array\" ||\n ((prop as any)?.type === \"any\" &&\n (Array.isArray(overrides[inputId]) || Array.isArray(this.runInputData[inputId])));\n\n if (isArray) {\n const existingItems = Array.isArray(this.runInputData[inputId])\n ? this.runInputData[inputId]\n : this.runInputData[inputId] !== undefined\n ? [this.runInputData[inputId]]\n : [];\n const newitems = [...existingItems];\n\n const overrideItem = overrides[inputId];\n if (Array.isArray(overrideItem)) {\n newitems.push(...overrideItem);\n } else {\n newitems.push(overrideItem);\n }\n this.runInputData[inputId] = newitems;\n changed = true;\n } else {\n if (!deepEqual(this.runInputData[inputId], overrides[inputId])) {\n this.runInputData[inputId] = overrides[inputId];\n changed = true;\n }\n }\n }\n }\n\n // If additionalProperties is true, also accept any additional input properties\n if (inputSchema.additionalProperties) {\n for (const [inputId, value] of Object.entries(overrides)) {\n if (!(inputId in properties)) {\n if (!deepEqual(this.runInputData[inputId], value)) {\n this.runInputData[inputId] = value;\n changed = true;\n }\n }\n }\n }\n\n return changed;\n }\n\n /**\n * Stub for narrowing input. Override in subclasses for custom logic.\n * @param input The input to narrow\n * @param _registry Optional service registry for lookups\n * @returns The (possibly narrowed) input\n */\n public async narrowInput(\n input: Partial<Input>,\n _registry: ServiceRegistry\n ): Promise<Partial<Input>> {\n return input;\n }\n\n // ========================================================================\n // Event handling methods\n // ========================================================================\n\n public subscribe<Event extends TaskEvents>(\n name: Event,\n fn: TaskEventListener<Event>\n ): () => void {\n return this.events.subscribe(name, fn);\n }\n\n public on<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n this.events.on(name, fn);\n }\n\n public off<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n this.events.off(name, fn);\n }\n\n public once<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n this.events.once(name, fn);\n }\n\n /**\n * Returns a promise that resolves when the specified event is emitted\n */\n public waitOn<Event extends TaskEvents>(name: Event): Promise<TaskEventParameters<Event>> {\n return this.events.waitOn(name) as Promise<TaskEventParameters<Event>>;\n }\n\n public emit<Event extends TaskEvents>(name: Event, ...args: TaskEventParameters<Event>): void {\n // Route through `events` so the emitter exists: `this._events?.emit` dropped progress when\n // nothing had accessed `task.events` yet (e.g. parent MapTask before CLI wired listeners).\n this.events.emit(name, ...args);\n }\n\n /**\n * Emits a schemaChange event when the task's input or output schema changes.\n * This should be called by tasks with dynamic schemas when their configuration\n * changes in a way that affects their schemas.\n *\n * @param inputSchema - The new input schema (optional, will use current schema if not provided)\n * @param outputSchema - The new output schema (optional, will use current schema if not provided)\n */\n protected emitSchemaChange(inputSchema?: DataPortSchema, outputSchema?: DataPortSchema): void {\n const finalInputSchema = inputSchema ?? this.inputSchema();\n const finalOutputSchema = outputSchema ?? this.outputSchema();\n this.emit(\"schemaChange\", finalInputSchema, finalOutputSchema);\n }\n\n // ========================================================================\n // Input validation methods\n // ========================================================================\n\n /**\n * Gets the compiled config schema node, or undefined if no configSchema is defined.\n *\n * The compiled schema is cached directly on the concrete class object (not in a shared\n * inherited Map) so that each subclass always uses its own configSchema() result.\n * A shared Map keyed only by type name can be poisoned if a different class computes\n * and caches the schema first — e.g., due to cross-package static-method resolution\n * inconsistencies in bundled outputs.\n */\n private static getConfigSchemaNode(): SchemaNode | undefined {\n const schema = this.configSchema();\n if (!schema) return undefined;\n // Use Object.hasOwn so each class gets its own entry rather than inheriting\n // from a parent class that already cached under the same key.\n if (!Object.hasOwn(this, \"__compiledConfigSchema\")) {\n try {\n const schemaNode =\n typeof schema === \"boolean\"\n ? compileSchema(schema ? {} : { not: {} })\n : compileSchema(schema);\n Object.defineProperty(this, \"__compiledConfigSchema\", {\n value: schemaNode,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n } catch (error) {\n console.warn(`Failed to compile config schema for ${this.type}:`, error);\n return undefined;\n }\n }\n return (this as any).__compiledConfigSchema as SchemaNode;\n }\n\n /**\n * Validates config against configSchema.\n * Returns config as-is; throws on validation errors.\n * Returns config as-is if no configSchema is defined.\n */\n private validateAndApplyConfigDefaults(config: Config): Config {\n const ctor = this.constructor as typeof Task;\n const schemaNode = ctor.getConfigSchemaNode();\n if (!schemaNode) return config;\n\n const result = schemaNode.validate(config);\n if (!result.valid) {\n const errorMessages = result.errors.map((e) => {\n const path = e.data?.pointer || \"\";\n return `${e.message}${path ? ` (${path})` : \"\"}`;\n });\n throw new TaskConfigurationError(\n `[${ctor.name}] Configuration Error: ${errorMessages.join(\", \")}`\n );\n }\n\n return config;\n }\n\n protected static generateInputSchemaNode(schema: DataPortSchema) {\n if (typeof schema === \"boolean\") {\n if (schema === false) {\n return compileSchema({ not: {} });\n }\n return compileSchema({});\n }\n return compileSchema(schema);\n }\n\n /**\n * Gets the compiled input schema, cached per class (not in a shared inherited Map).\n * Uses Object.hasOwn so each subclass stores its own compiled schema and never\n * picks up a stale entry cached by a different class with the same type name.\n */\n protected static getInputSchemaNode(): SchemaNode {\n if (!Object.hasOwn(this, \"__compiledInputSchema\")) {\n const dataPortSchema = this.inputSchema();\n const schemaNode = this.generateInputSchemaNode(dataPortSchema);\n try {\n Object.defineProperty(this, \"__compiledInputSchema\", {\n value: schemaNode,\n writable: true,\n configurable: true,\n enumerable: false,\n });\n } catch (error) {\n // If compilation fails, fall back to accepting any object structure\n // This is a safety net for schemas that json-schema-library can't compile\n console.warn(\n `Failed to compile input schema for ${this.type}, falling back to permissive validation:`,\n error\n );\n Object.defineProperty(this, \"__compiledInputSchema\", {\n value: compileSchema({}),\n writable: true,\n configurable: true,\n enumerable: false,\n });\n }\n }\n return (this as any).__compiledInputSchema as SchemaNode;\n }\n\n protected getInputSchemaNode(): SchemaNode {\n return (this.constructor as typeof Task).getInputSchemaNode();\n }\n\n /**\n * Validates an input data object against the task's input schema\n */\n public async validateInput(input: Input): Promise<boolean> {\n if (typeof input !== \"object\" || input === null) {\n throw new TaskInvalidInputError(\"Input must be an object\");\n }\n const ctor = this.constructor as typeof Task;\n let schemaNode: SchemaNode;\n if (ctor.hasDynamicSchemas) {\n // Dynamic-schema tasks use instance inputSchema() (e.g. config.inputSchema), not the static fallback.\n // The cached getInputSchemaNode uses static inputSchema() which would reject valid instance-specific inputs.\n const instanceSchema = this.inputSchema();\n schemaNode = ctor.generateInputSchemaNode(instanceSchema);\n } else {\n schemaNode = this.getInputSchemaNode();\n }\n const result = schemaNode.validate(input);\n\n if (!result.valid) {\n const errorMessages = result.errors.map((e) => {\n const path = e.data.pointer || \"\";\n return `${e.message}${path ? ` (${path})` : \"\"}`;\n });\n const err = new TaskInvalidInputError(\n `Task \"${this.type}\" (${this.id}): Input ${JSON.stringify(Object.keys(input))} does not match schema: ${errorMessages.join(\", \")}`\n );\n err.taskType = this.type;\n err.taskId = this.id;\n throw err;\n }\n\n return true;\n }\n\n // ========================================================================\n // Serialization methods\n // ========================================================================\n\n /**\n * Strips symbol properties from an object to make it serializable\n * @param obj The object to strip symbols from\n * @returns A new object without symbol properties\n */\n private stripSymbols(obj: any): any {\n if (obj === null || obj === undefined) {\n return obj;\n }\n // Preserve TypedArrays (Float32Array, Int8Array, etc.)\n if (ArrayBuffer.isView(obj)) {\n return obj;\n }\n if (Array.isArray(obj)) {\n return obj.map((item) => this.stripSymbols(item));\n }\n if (typeof obj === \"object\") {\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) {\n return obj;\n }\n\n const result: Record<string, any> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = this.stripSymbols(obj[key]);\n }\n }\n return result;\n }\n return obj;\n }\n\n /**\n * Returns whether the task's config can be serialized to JSON.\n * Override in subclasses that store non-serializable values (functions) in config.\n * Called by toJSON — if false, toJSON throws TaskSerializationError.\n */\n public canSerializeConfig(): boolean {\n return true;\n }\n\n /**\n * Serializes the task and its subtasks into a format that can be stored\n * @param _options Options controlling serialization (used by subclasses)\n * @returns The serialized task and subtasks\n */\n public toJSON(_options?: TaskGraphJsonOptions): TaskGraphItemJson {\n const ctor = this.constructor as typeof Task;\n\n if (!this.canSerializeConfig() || !this.originalConfig) {\n throw new TaskSerializationError(this.type);\n }\n\n // Build config by extracting only serializable properties defined in the configSchema.\n // We filter through the schema to avoid accidentally including non-serializable\n // values (e.g. functions like WhileTask.condition) or internal-only properties\n // that were never part of the serialized output and that consuming applications\n // don't expect (e.g. `queue` from task-specific configs).\n const schema = ctor.configSchema();\n const schemaProperties =\n typeof schema !== \"boolean\" && schema?.properties\n ? (schema.properties as Record<string, Record<string, unknown>>)\n : {};\n\n const config: Record<string, unknown> = {};\n for (const [key, propSchema] of Object.entries(schemaProperties)) {\n if (key === \"id\") continue;\n // Skip internal properties marked as hidden (e.g. queue, compoundMerge)\n // except inputSchema/outputSchema/extras which are needed for task reconstruction\n if (\n propSchema?.[\"x-ui-hidden\"] === true &&\n key !== \"inputSchema\" &&\n key !== \"outputSchema\" &&\n key !== \"extras\"\n ) {\n continue;\n }\n const value = (this.originalConfig as Record<string, unknown>)[key];\n if (value === undefined) continue;\n // Skip non-serializable values (functions, symbols, etc.)\n if (typeof value === \"function\" || typeof value === \"symbol\") continue;\n config[key] = value;\n }\n\n // Omit title/description when they match the static class defaults\n if (config.title === ctor.title) delete config.title;\n if (config.description === ctor.description) delete config.description;\n\n // Omit empty extras\n const extras = config.extras as Record<string, unknown> | undefined;\n if (!extras || Object.keys(extras).length === 0) delete config.extras;\n\n const base: TaskGraphItemJson = {\n id: this.id,\n type: this.type,\n defaults: this.defaults,\n };\n if (Object.keys(config).length > 0) {\n base.config = config;\n }\n\n return this.stripSymbols(base) as TaskGraphItemJson;\n }\n\n /**\n * Converts the task to a JSON format suitable for dependency tracking\n * @param options Options controlling serialization (used by subclasses)\n * @returns The task and subtasks in JSON thats easier for humans to read\n */\n public toDependencyJSON(options?: TaskGraphJsonOptions): JsonTaskItem {\n const json = this.toJSON(options);\n return json;\n }\n\n // ========================================================================\n // Internal graph methods\n // ========================================================================\n\n /**\n * Checks if the task has children. Useful to gate to use of the internal subGraph\n * as this will return without creating a new graph if graph is non-existent .\n *\n * @returns True if the task has children, otherwise false\n */\n public hasChildren(): boolean {\n return (\n this._subGraph !== undefined &&\n this._subGraph !== null &&\n this._subGraph.getTasks().length > 0\n );\n }\n\n private _taskAddedListener: (taskId: TaskIdType) => void = () => {\n this.emit(\"regenerate\");\n };\n\n /**\n * The internal task graph containing subtasks\n *\n * In the base case, these may just be incidental tasks that are not part of the task graph\n * but are used to manage the task's state as part of task execution. Therefore, the graph\n * is not used by the default runner.\n */\n protected _subGraph: TaskGraph | undefined = undefined;\n\n /**\n * Sets the subtask graph for the compound task\n * @param subGraph The subtask graph to set\n */\n set subGraph(subGraph: TaskGraph) {\n if (this._subGraph) {\n this._subGraph.off(\"task_added\", this._taskAddedListener);\n }\n this._subGraph = subGraph;\n this._subGraph.on(\"task_added\", this._taskAddedListener);\n }\n\n /**\n * The internal task graph containing subtasks\n *\n * In the base case, these may just be incidental tasks that are not part of the task graph\n * but are used to manage the task's state as part of task execution. Therefore, the graph\n * is not used by the default runner.\n *\n * Creates a new graph if one doesn't exist.\n *\n * @returns The task graph\n */\n get subGraph(): TaskGraph {\n if (!this._subGraph) {\n this._subGraph = new TaskGraph();\n this._subGraph.on(\"task_added\", this._taskAddedListener);\n }\n return this._subGraph;\n }\n\n /**\n * Regenerates the task graph, which is internal state to execute() with config.own()\n *\n * This is a destructive operation that removes all dataflows and tasks from the graph.\n * It is used to reset the graph to a clean state.\n *\n * GraphAsTask and others override this and do not call super\n */\n public regenerateGraph(): void {\n if (this.hasChildren()) {\n for (const dataflow of this.subGraph.getDataflows()) {\n this.subGraph.removeDataflow(dataflow);\n }\n for (const child of this.subGraph.getTasks()) {\n this.subGraph.removeTask(child.id);\n }\n }\n this.events.emit(\"regenerate\");\n }\n}\n\n/**\n * Test helper: clear the H7 dedup Set so each test case can re-trigger the\n * one-time legacy-`cacheable` deprecation warning. Lives in production code\n * (not a __tests__ file) so it's reachable from outside the package's test\n * harness; the leading double-underscore signals \"do not rely on this in\n * application code\".\n */\nexport function __resetCacheableDeprecationWarnings(): void {\n (\n Task as unknown as { __cacheableDeprecationWarned: Set<string> }\n ).__cacheableDeprecationWarned.clear();\n}\n",
|
|
27
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n getLogger,\n getTelemetryProvider,\n globalServiceRegistry,\n ResourceScope,\n ServiceRegistry,\n SpanStatusCode,\n} from \"@workglow/util\";\nimport type { CacheRegistry } from \"../cache\";\nimport { CACHE_REGISTRY, DefaultCacheRegistry, RunPrivateCacheRepo } from \"../cache\";\nimport { TASK_OUTPUT_REPOSITORY, TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { Taskish } from \"../task-graph/Conversions\";\nimport { ensureTask } from \"../task-graph/Conversions\";\nimport { CacheCoordinator } from \"./CacheCoordinator\";\nimport { resolveSchemaInputs, schemaHasFormatAnnotations } from \"./InputResolver\";\nimport type { IRunConfig, ITask } from \"./ITask\";\nimport { ITaskRunner } from \"./ITaskRunner\";\nimport { StreamProcessor } from \"./StreamProcessor\";\nimport type { StreamEvent } from \"./StreamTypes\";\nimport { getOutputStreamMode, isTaskStreamable } from \"./StreamTypes\";\nimport { Task } from \"./Task\";\nimport {\n TaskAbortedError,\n TaskConfigurationError,\n TaskError,\n TaskFailedError,\n TaskInvalidInputError,\n TaskTimeoutError,\n} from \"./TaskError\";\nimport { TaskRunContext } from \"./TaskRunContext\";\nimport { TaskConfig, TaskInput, TaskOutput, TaskStatus } from \"./TaskTypes\";\n\n/**\n * Type guard that checks whether a value is an ITask-like object with a mutable `runConfig`.\n */\nfunction hasRunConfig(i: unknown): i is { runConfig: Partial<IRunConfig> } {\n return i !== null && typeof i === \"object\" && \"runConfig\" in (i as object);\n}\n\n/**\n * Responsible for running tasks\n * Manages the execution lifecycle of individual tasks\n */\nexport class TaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends TaskConfig = TaskConfig,\n> implements ITaskRunner<Input, Output, Config> {\n protected running = false;\n protected previewRunning = false;\n\n public readonly task: ITask<Input, Output, Config>;\n\n /**\n * Per-run state. Set by handleStart, cleared by handleComplete / handleError /\n * handleAbort / handleDisable. The only mutable per-run state on the facade —\n * exists so the public abort() and disable() methods (which take no arguments)\n * have something to act on.\n */\n protected currentCtx?: TaskRunContext;\n\n /**\n * Output cache repository resolved per-run. Set when the caller passes\n * `outputCache: repo | true` through IRunConfig; the {@link cacheRegistry}\n * deterministic slot is synthesized from it. When `outputCache` is absent\n * and a CACHE_REGISTRY is registered, that is used instead.\n */\n protected outputCache?: TaskOutputRepository;\n\n /**\n * Per-run cache registry resolved in handleStart. Replaces the legacy\n * single-repo `outputCache` field as the primary cache routing mechanism.\n * Set from CACHE_REGISTRY in the ServiceRegistry, or synthesised from the\n * legacy `config.outputCache` repo shim.\n */\n protected cacheRegistry?: CacheRegistry;\n\n /**\n * Cache coordinator for the task (key normalization, lookup, save).\n */\n protected readonly cacheCoordinator: CacheCoordinator<Input, Output>;\n\n /**\n * Stream processor for the task (handles executeStream() event loop).\n */\n protected readonly streamProcessor: StreamProcessor<Input, Output>;\n\n protected registry: ServiceRegistry = globalServiceRegistry;\n\n protected resourceScope?: ResourceScope;\n\n /**\n * True when `this.resourceScope` was auto-created by `run()` (caller did not\n * pass one in `config`). The flag is used by `own()` so that an auto-owned\n * scope is not stamped into a child task's long-lived `runConfig` — that\n * stamp would survive past the parent run's `finally`-block disposal and\n * leave the child holding a reference to a disposed scope.\n */\n protected ownsResourceScope = false;\n\n /**\n * Input streams for pass-through streaming tasks.\n * Set by the graph runner before executing a streaming task that has\n * upstream streaming edges. Keyed by input port name.\n */\n public inputStreams?: Map<string, ReadableStream<StreamEvent>>;\n\n /**\n * Stable identifier for the current graph run. Set from IRunConfig.runId by\n * handleStart; threaded into IExecuteContext so tasks can correlate their\n * work to the enclosing run.\n */\n protected runId?: string;\n\n /**\n * Tracks task types that have already received the \"private policy without\n * runId\" downgrade warning, so the warning fires only once per task type\n * across the process lifetime. Mirrors {@link Task.__cacheableDeprecationWarned}.\n */\n private static __privateWithoutRunIdWarned = new Set<string>();\n\n constructor(task: ITask<Input, Output, Config>) {\n this.task = task;\n this.own = this.own.bind(this);\n this.handleProgress = this.handleProgress.bind(this);\n this.cacheCoordinator = new CacheCoordinator(task);\n this.streamProcessor = new StreamProcessor(task);\n }\n\n // ========================================================================\n // Public methods\n // ========================================================================\n\n async run(overrides: Partial<Input> = {}, config: IRunConfig = {}): Promise<Output> {\n // Reject concurrent run() on the same TaskRunner. Mirrors\n // TaskGraphRunner.handleStart's \"Graph is already running\" check.\n // Raised before any `this.*` mutation so the in-flight run is undisturbed.\n if (this.task.status === TaskStatus.PROCESSING) {\n throw new TaskConfigurationError(\n `Task \"${this.task.type}\" is already running. Concurrent run() calls on the same TaskRunner are not supported.`\n );\n }\n\n const ownsScope = config.resourceScope === undefined;\n const effectiveConfig: IRunConfig = ownsScope\n ? { ...config, resourceScope: new ResourceScope({ strategy: config.disposeStrategy }) }\n : config;\n this.ownsResourceScope = ownsScope;\n\n // ctx is threaded through locals from here; nothing inside run() re-reads\n // this.currentCtx (which can be nulled by handleAbort firing on the abort\n // listener during an interleaved abort). Declared outside the try so the\n // finally block can run scope cleanup even if handleStart itself throws.\n let ctx: TaskRunContext | undefined;\n try {\n ctx = await this.handleStart(effectiveConfig);\n\n const proto = Object.getPrototypeOf(this.task);\n if (\n proto.execute === Task.prototype.execute &&\n typeof proto.executeStream !== \"function\" &&\n proto.executePreview !== Task.prototype.executePreview\n ) {\n throw new TaskConfigurationError(\n `Task \"${this.task.type}\" implements only executePreview() and cannot be run via run(). ` +\n `After the run/runPreview split, run() requires execute() (or executeStream()). ` +\n `See docs/technical/02-dual-mode-execution.md.`\n );\n }\n\n try {\n this.task.setInput(overrides);\n\n await this.resolveSchemas();\n\n const inputs: Input = this.task.runInputData as Input;\n const isValid = await this.task.validateInput(inputs);\n if (!isValid) {\n throw new TaskInvalidInputError(\"Invalid input data\");\n }\n\n if (ctx.abortController.signal.aborted) {\n await this.handleAbort(ctx);\n throw new TaskAbortedError(\"Promise for task created and aborted before run\");\n }\n\n const isStreamable = isTaskStreamable(this.task);\n\n // Warn if schema declares streaming but executeStream is not implemented\n if (!isStreamable && typeof this.task.executeStream !== \"function\") {\n const streamMode = getOutputStreamMode(this.task.outputSchema());\n if (streamMode !== \"none\") {\n getLogger().warn(\n `Task \"${this.task.type}\" declares streaming output (x-stream: \"${streamMode}\") ` +\n `but does not implement executeStream(). Falling back to non-streaming execute().`\n );\n }\n }\n\n let policy = this.task.getCachePolicy(inputs);\n\n // Standalone TaskRunner cannot namespace private cache writes without a\n // runId — TaskGraphRunner owns the wrap. If a standalone caller routes\n // to the private slot with no runId, downgrade to `kind: \"none\"` so the\n // task does not write directly into the shared private repo (which\n // would collide across callers). Warn once per task type so the\n // configuration mistake surfaces without flooding the log.\n if (\n policy.kind === \"private\" &&\n !this.runId &&\n this.cacheRegistry?.private !== undefined &&\n !(this.cacheRegistry.private instanceof RunPrivateCacheRepo)\n ) {\n const taskType = this.task.type;\n if (!TaskRunner.__privateWithoutRunIdWarned.has(taskType)) {\n TaskRunner.__privateWithoutRunIdWarned.add(taskType);\n getLogger().warn(\n `TaskRunner: task \"${taskType}\" has a private cache policy but no runId was ` +\n `provided. Private cache writes are skipped for this run — use TaskGraphRunner ` +\n `with runId for run-namespaced private caching, or provide an already namespaced ` +\n `private cache repo in CACHE_REGISTRY.`\n );\n }\n policy = { kind: \"none\" };\n }\n\n ctx.telemetrySpan?.setAttributes({\n \"workglow.task.cache_policy\": policy.kind,\n });\n\n const keyInputs = await this.cacheCoordinator.buildKeyForPolicy(\n inputs,\n this.cacheRegistry,\n policy\n );\n let outputs = await this.cacheCoordinator.lookupByPolicy(\n keyInputs,\n this.cacheRegistry,\n policy,\n isStreamable,\n ctx\n );\n\n if (outputs === undefined) {\n outputs = isStreamable\n ? await this.streamProcessor.run(inputs, ctx, {\n registry: this.registry,\n resourceScope: this.resourceScope,\n inputStreams: this.inputStreams,\n onProgress: this.handleProgress.bind(this),\n own: this.own,\n })\n : await this.executeTask(inputs, ctx);\n\n await this.cacheCoordinator.saveByPolicy(\n keyInputs,\n outputs as Output,\n this.cacheRegistry,\n policy\n );\n this.task.runOutputData = outputs ?? ({} as Output);\n }\n\n await this.handleComplete(ctx);\n\n return this.task.runOutputData as Output;\n } catch (err: any) {\n await this.handleError(err, ctx);\n // If a timeout triggered the abort, throw the TaskTimeoutError instead\n // of the generic TaskAbortedError that the task's execute() may have thrown.\n throw this.task.error instanceof TaskTimeoutError ? this.task.error : err;\n }\n } catch (err: any) {\n // Reachable when handleStart() throws before assigning `ctx` (e.g.,\n // resourceScope.runStart or telemetry init blows up). Without this,\n // task.status would be stuck at PROCESSING with currentCtx still set\n // and no error/event ever emitted.\n if (ctx === undefined) {\n const partial = this.currentCtx;\n if (partial) {\n await this.handleError(err, partial);\n } else {\n this.task.status = TaskStatus.FAILED;\n this.task.error =\n err instanceof TaskError\n ? err\n : new TaskFailedError(\n `Task \"${this.task.type}\" (${this.task.id}): ${err?.message || \"Task failed\"}`\n );\n if (this.task.error instanceof TaskError) {\n this.task.error.taskType ??= this.task.type;\n this.task.error.taskId ??= this.task.id;\n }\n this.task.emit(\"error\", this.task.error);\n this.task.emit(\"status\", this.task.status);\n }\n this.running = false;\n }\n throw err;\n } finally {\n if (ownsScope) {\n await effectiveConfig.resourceScope!.runComplete();\n this.resourceScope = undefined;\n }\n this.ownsResourceScope = false;\n }\n }\n\n public async runPreview(overrides: Partial<Input> = {}): Promise<Output> {\n if (this.task.status === TaskStatus.PROCESSING) {\n return this.task.runOutputData as Output;\n }\n\n this.task.setInput(overrides);\n\n await this.resolveSchemas();\n\n await this.handleStartPreview();\n\n // Build a transient context for preview overrides — preview doesn't share the\n // full lifecycle but executeTaskPreview's signature requires a ctx.\n const ctx = new TaskRunContext();\n\n try {\n const inputs: Input = this.task.runInputData as Input;\n const isValid = await this.task.validateInput(inputs);\n if (!isValid) {\n throw new TaskInvalidInputError(\"Invalid input data\");\n }\n\n const resultPreview = await this.executeTaskPreview(inputs, ctx);\n if (resultPreview !== undefined) {\n this.task.runOutputData = resultPreview;\n }\n\n await this.handleCompletePreview();\n } catch (err: any) {\n getLogger().debug(\"runPreview failed\", { taskId: this.task.config?.id, error: err });\n await this.handleErrorPreview();\n } finally {\n ctx.dispose();\n return this.task.runOutputData as Output;\n }\n }\n\n /**\n * Async iterator producing preview outputs as upstream tasks stream\n * snapshots. Yields once immediately with the current preview state, then\n * yields again whenever upstream snapshots have arrived since the last\n * yield, until all relevant upstream streams complete (or the consumer\n * breaks out of the loop).\n *\n * Backpressure is single-buffered and last-write-wins: snapshots arriving\n * while a runPreview() iteration is in flight all overwrite runInputData,\n * and the next iteration sees only the latest value. Consumers that need\n * to observe every intermediate snapshot must pace the producer (e.g.,\n * wait for each yield to be processed before emitting the next). This\n * matches live-preview UI semantics — show the latest, drop stale frames.\n *\n * Reuses runPreview() under the hood. Errors during a single iteration\n * are caught and skipped — the iterator never throws to the consumer\n * mid-loop.\n *\n * Watches direct upstream tasks only. Indirect (grandparent) snapshots\n * propagate through chained preview re-runs as upstream parents' values\n * update.\n */\n public async *runPreviewStream(overrides: Partial<Input> = {}): AsyncIterable<Output> {\n // 1. Identify direct upstream tasks and their connecting dataflows.\n // runPreviewStream calls task.runPreview() directly (not the graph\n // runner's runPreview), so it does not benefit from the graph-runner's\n // copyInputFromEdgesToNode pull. We propagate snapshot values into the\n // target task's runInputData ourselves, mirroring that pull but driven\n // by upstream stream events.\n const graph = this.task.parentGraph;\n type DataflowInfo = { upstream: ITask; sourcePort: string; targetPort: string };\n const dataflowInfos: DataflowInfo[] = [];\n if (graph) {\n for (const df of graph.getSourceDataflows(this.task.id)) {\n const upstream = graph.getTask(df.sourceTaskId);\n if (upstream) {\n dataflowInfos.push({\n upstream,\n sourcePort: df.sourceTaskPortId,\n targetPort: df.targetTaskPortId,\n });\n }\n }\n }\n\n // 2. Track upstreams that may still emit snapshots (pending, processing, or streaming).\n // An upstream is \"done\" once its stream ends or it reaches a terminal state.\n const upstreamTasks = new Set(dataflowInfos.map((d) => d.upstream));\n const pendingUpstreams = new Set<ITask>(\n [...upstreamTasks].filter(\n (u) =>\n u.status === TaskStatus.STREAMING ||\n u.status === TaskStatus.PENDING ||\n u.status === TaskStatus.PROCESSING\n )\n );\n\n // 3. Set up dirty/wake machinery.\n let dirty = true;\n let wakeResolve: (() => void) | undefined;\n const wakeNext = (): Promise<void> =>\n new Promise<void>((resolve) => {\n wakeResolve = resolve;\n });\n const wake = () => {\n const r = wakeResolve;\n wakeResolve = undefined;\n if (r) r();\n };\n\n // 4. Subscribe to all upstream tasks that could stream.\n const cleanupFns: Array<() => void> = [];\n for (const upstream of pendingUpstreams) {\n const myDataflows = dataflowInfos.filter((d) => d.upstream === upstream);\n\n const onChunk = (event: StreamEvent) => {\n if (event.type !== \"snapshot\") return;\n const snapshotData = (event as { data?: Record<string, unknown> }).data;\n if (snapshotData) {\n for (const { sourcePort, targetPort } of myDataflows) {\n const value = sourcePort === \"*\" ? snapshotData : snapshotData[sourcePort];\n if (value !== undefined) {\n (this.task.runInputData as Record<string, unknown>)[targetPort] = value;\n }\n }\n }\n dirty = true;\n wake();\n };\n const onEnd = () => {\n pendingUpstreams.delete(upstream);\n wake();\n };\n const onStatus = (status: TaskStatus) => {\n // If upstream completes without streaming, remove it from pending.\n if (\n status === TaskStatus.COMPLETED ||\n status === TaskStatus.FAILED ||\n status === TaskStatus.DISABLED\n ) {\n pendingUpstreams.delete(upstream);\n wake();\n }\n };\n upstream.on(\"stream_chunk\", onChunk);\n upstream.on(\"stream_end\", onEnd);\n upstream.on(\"status\", onStatus);\n cleanupFns.push(() => {\n upstream.off(\"stream_chunk\", onChunk);\n upstream.off(\"stream_end\", onEnd);\n upstream.off(\"status\", onStatus);\n });\n }\n\n // 4b. Re-check upstream status after subscribing. If any reached a terminal\n // state in the gap between step 2 (status read) and step 4 (listener\n // attach), prune them now — listeners attached in step 4 won't fire\n // retroactively for events that already happened. The first iteration\n // of the loop still yields a preview from whatever runInputData\n // currently holds.\n for (const upstream of [...pendingUpstreams]) {\n if (\n upstream.status === TaskStatus.COMPLETED ||\n upstream.status === TaskStatus.FAILED ||\n upstream.status === TaskStatus.DISABLED\n ) {\n pendingUpstreams.delete(upstream);\n }\n }\n\n // 5. Iterator loop.\n try {\n while (true) {\n if (dirty) {\n dirty = false;\n try {\n const out = await this.runPreview(overrides);\n yield out;\n } catch (err) {\n getLogger().debug(\"runPreviewStream iteration failed\", {\n taskId: this.task.config?.id,\n error: err,\n });\n }\n continue;\n }\n if (pendingUpstreams.size === 0) return;\n await wakeNext();\n }\n } finally {\n for (const off of cleanupFns) off();\n }\n }\n\n public abort(): void {\n this.currentCtx?.abortController.abort();\n }\n\n // ========================================================================\n // Protected methods\n // ========================================================================\n\n protected own<T extends Taskish<any, any>>(i: T): T {\n const task = ensureTask(i, { isOwned: true });\n this.task.subGraph.addTask(task);\n // Propagate parent registry and abort signal to owned ITask instances so\n // that calling task.run() on the returned value inherits this execution context.\n if (hasRunConfig(i)) {\n // Only propagate `resourceScope` if the caller owns its lifecycle. Stamping\n // an auto-created scope into a long-lived `runConfig` leaks a reference\n // past the parent run's `finally`-block disposal — the next `task.run()`\n // on the owned instance would then see a disposed scope, skip auto-create,\n // and silently drop disposers on its cleared Map. With caller-passed\n // scopes the caller controls disposal, so the propagation is safe and\n // preserves resource-sharing across owned-task runs.\n const stamp: Partial<IRunConfig> = {\n registry: this.registry,\n signal: this.currentCtx?.abortController.signal,\n };\n if (!this.ownsResourceScope) {\n stamp.resourceScope = this.resourceScope;\n }\n Object.assign(i.runConfig, stamp);\n }\n // Notify listeners that the entitlement landscape may have changed.\n // For GraphAsTask this is also handled by the subGraph subscription, but\n // non-GraphAsTask tasks with dynamic entitlements (e.g. AiTask) need it too.\n if ((this.task.constructor as typeof Task).hasDynamicEntitlements) {\n this.task.emit(\"entitlementChange\", this.task.entitlements());\n }\n return i;\n }\n\n protected async executeTask(input: Input, ctx: TaskRunContext): Promise<Output | undefined> {\n const result = await this.task.execute(input, {\n signal: ctx.abortController.signal,\n updateProgress: this.handleProgress.bind(this),\n own: this.own,\n registry: this.registry,\n resourceScope: this.resourceScope,\n runId: this.runId,\n });\n return result;\n }\n\n protected async executeTaskPreview(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.task.executePreview?.(input, { own: this.own });\n }\n\n // ========================================================================\n // Protected Handlers\n // ========================================================================\n\n /**\n * Resolves config and input schema annotations (e.g. mcp-server references)\n * by mutating task.config and task.runInputData. Always resolves config from\n * originalConfig so re-runs use the original string IDs, not previously resolved\n * objects. Shared between run() and runPreview() to avoid duplication.\n */\n private async resolveSchemas(): Promise<void> {\n const configSchema = (this.task.constructor as typeof Task).configSchema();\n if (schemaHasFormatAnnotations(configSchema)) {\n const source = (this.task as unknown as Task).originalConfig ?? this.task.config;\n const resolved = await resolveSchemaInputs(\n { ...source } as Record<string, unknown>,\n configSchema,\n { registry: this.registry }\n );\n Object.assign(this.task.config, resolved);\n }\n\n // Resolve schema-annotated inputs (models, repositories) before validation.\n // Dynamic-schema tasks (InputTask, GraphAsTask, …) store the effective schema on\n // the instance; the static schema has no format annotations and would skip hydration.\n const ctor = this.task.constructor as typeof Task;\n const schema = ctor.hasDynamicSchemas ? this.task.inputSchema() : ctor.inputSchema();\n this.task.runInputData = (await resolveSchemaInputs(\n this.task.runInputData as Record<string, unknown>,\n schema,\n { registry: this.registry }\n )) as Input;\n }\n\n /**\n * Handles task start. Concurrent-run rejection happens in {@link run} before\n * any state mutation; by the time `handleStart` runs, the task status is\n * guaranteed to be non-PROCESSING.\n *\n * Returns the per-run {@link TaskRunContext} so `run()` can thread it\n * through locals instead of re-reading `this.currentCtx` across awaits.\n * The instance field `this.currentCtx` is still set as the *external*\n * pointer used by no-arg public methods (`abort()`, `disable()`); internal\n * flow should use the returned ctx exclusively.\n */\n protected async handleStart(config: IRunConfig = {}): Promise<TaskRunContext> {\n this.running = true;\n\n this.task.startedAt = new Date();\n this.task.progress = 0;\n this.task.status = TaskStatus.PROCESSING;\n\n // Build per-run context (handles abortController + parentSignal wiring)\n const ctx = new TaskRunContext(config.signal);\n this.currentCtx = ctx;\n\n // Listener captures the local `ctx`, not `this.currentCtx`. If a later run\n // replaces the instance field before this listener fires, handleAbort still\n // operates on the ctx the listener was attached to.\n ctx.abortController.signal.addEventListener(\"abort\", () => {\n void this.handleAbort(ctx);\n });\n\n // Apply registry override first so that cache resolution below uses the\n // correct per-run ServiceRegistry rather than the stale instance field.\n if (config.registry) {\n this.registry = config.registry;\n }\n\n // Propagate run identifier for use in IExecuteContext.\n this.runId = config.runId;\n\n // Cache resolution: prefer CacheRegistry (via ServiceRegistry); honour legacy\n // config.outputCache as a back-compat shim that maps to the deterministic slot.\n const legacy = config.outputCache ?? this.task.runConfig?.outputCache;\n if (legacy === false) {\n this.cacheRegistry = undefined;\n this.outputCache = undefined;\n } else if (legacy instanceof TaskOutputRepository) {\n // Legacy repo passed directly → treat as the deterministic slot.\n this.cacheRegistry = new DefaultCacheRegistry({ deterministic: legacy });\n this.outputCache = legacy;\n } else if (legacy === true) {\n // Legacy boolean true → pull from TASK_OUTPUT_REPOSITORY in the global registry.\n const instance = globalServiceRegistry.has(TASK_OUTPUT_REPOSITORY)\n ? globalServiceRegistry.get(TASK_OUTPUT_REPOSITORY)\n : undefined;\n this.outputCache = instance;\n this.cacheRegistry = instance\n ? new DefaultCacheRegistry({ deterministic: instance })\n : undefined;\n } else {\n // No legacy override → look up CACHE_REGISTRY from the per-run ServiceRegistry.\n this.outputCache = undefined;\n this.cacheRegistry = this.registry.has(CACHE_REGISTRY)\n ? this.registry.get(CACHE_REGISTRY)\n : undefined;\n }\n\n // shouldAccumulate defaults to true (backward-compatible for standalone runs)\n ctx.shouldAccumulate = config.shouldAccumulate !== false;\n\n if (config.updateProgress) {\n this.updateProgress = config.updateProgress;\n }\n\n if (config.resourceScope) {\n this.resourceScope = config.resourceScope;\n }\n\n // Notify the disposal strategy that a new run is starting. Inactivity\n // strategies use this hook to clear any pending idle timers that were\n // armed at the previous `runComplete`, closing the race window where a\n // timer could fire mid-run and dispose a resource we are about to use.\n if (this.resourceScope) {\n await this.resourceScope.runStart();\n }\n\n // Early-out if parent signal was already aborted (TaskRunContext constructor\n // already aborted ctx.abortController in that case)\n if (ctx.abortController.signal.aborted) return ctx;\n\n // Start timeout timer if configured (timeout is a design-time config property).\n // Fire on the captured ctx's controller rather than this.abort() so a timeout\n // armed for *this* run can't accidentally abort a later run if scope-teardown\n // racing leaves the timer alive past terminal-handler.\n const timeout = (this.task.config as Record<string, unknown>).timeout as number | undefined;\n if (timeout !== undefined && timeout > 0) {\n ctx.pendingTimeoutError = new TaskTimeoutError(timeout);\n ctx.timeoutTimer = setTimeout(() => {\n ctx.abortController.abort();\n }, timeout);\n }\n\n // Start telemetry span\n const telemetry = getTelemetryProvider();\n if (telemetry.isEnabled) {\n ctx.telemetrySpan = telemetry.startSpan(\"workglow.task.run\", {\n attributes: {\n \"workglow.task.type\": this.task.type,\n \"workglow.task.id\": String(this.task.config.id),\n \"workglow.task.title\": this.task.title || undefined,\n },\n });\n }\n\n this.task.emit(\"start\");\n this.task.emit(\"status\", this.task.status);\n return ctx;\n }\n private updateProgress = async (\n _task: ITask,\n _progress: number | undefined,\n _message?: string,\n ..._args: any[]\n ) => {};\n\n protected async handleStartPreview(): Promise<void> {\n this.previewRunning = true;\n }\n\n /**\n * Clears the timeout timer on the given ctx if one is active.\n */\n protected clearTimeoutTimer(ctx: TaskRunContext): void {\n if (ctx.timeoutTimer !== undefined) {\n clearTimeout(ctx.timeoutTimer);\n ctx.timeoutTimer = undefined;\n }\n }\n\n /**\n * Handles task abort.\n *\n * Idempotent per-ctx via {@link TaskRunContext.terminated}: the abort\n * listener fires synchronously inside `controller.abort()` and may race\n * with the run flow's own catch-block; both paths can land here. The\n * `terminated` flag (set before any await) lets the second arrival fall\n * through, while `task.status` is too brittle to gate on because adjacent\n * runs on the same task can mutate it.\n */\n protected async handleAbort(ctx: TaskRunContext): Promise<void> {\n if (ctx.terminated) return;\n ctx.terminated = true;\n this.clearTimeoutTimer(ctx);\n this.task.status = TaskStatus.ABORTING;\n await this.handleProgress(100);\n // Use the pending timeout error if the abort was triggered by a timeout\n this.task.error = ctx.pendingTimeoutError ?? new TaskAbortedError();\n\n if (ctx.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.ERROR, \"aborted\");\n ctx.telemetrySpan.addEvent(\"workglow.task.aborted\", {\n \"workglow.task.error\": this.task.error.message,\n });\n ctx.telemetrySpan.end();\n }\n\n // Call optional cleanup method for resource release\n if (typeof this.task.cleanup === \"function\") {\n try {\n await this.task.cleanup();\n } catch {\n // Cleanup errors are swallowed — abort must not throw from cleanup\n }\n }\n\n ctx.dispose();\n // CAS-style clear: only release the instance pointer if it still points at\n // *this* ctx. Prevents a stale terminal handler from clobbering a newer\n // run's currentCtx.\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n\n this.task.emit(\"abort\", this.task.error);\n this.task.emit(\"status\", this.task.status);\n }\n\n protected async handleAbortPreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n /**\n * Handles task completion.\n *\n * Idempotent per-ctx — see {@link handleAbort} for the rationale on using\n * `ctx.terminated` instead of `task.status` as the guard.\n */\n protected async handleComplete(ctx: TaskRunContext): Promise<void> {\n if (ctx.terminated) return;\n ctx.terminated = true;\n this.clearTimeoutTimer(ctx);\n\n this.task.completedAt = new Date();\n this.task.status = TaskStatus.COMPLETED;\n await this.handleProgress(100);\n\n if (ctx.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.OK);\n ctx.telemetrySpan.end();\n }\n\n ctx.dispose();\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n\n this.task.emit(\"complete\");\n this.task.emit(\"status\", this.task.status);\n }\n\n protected async handleCompletePreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n protected async handleDisable(ctx: TaskRunContext | undefined): Promise<void> {\n // Idempotent per-ctx where one exists; falls back to status-based guard\n // for the no-active-run case (public disable() called with no current ctx).\n if (ctx?.terminated || this.task.status === TaskStatus.DISABLED) return;\n if (ctx) ctx.terminated = true;\n this.task.status = TaskStatus.DISABLED;\n await this.handleProgress(100);\n this.task.completedAt = new Date();\n ctx?.dispose();\n // Don't clobber a newer run's ctx if disable() was queued from a stale state.\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n this.task.emit(\"disabled\");\n this.task.emit(\"status\", this.task.status);\n }\n\n public async disable(): Promise<void> {\n await this.handleDisable(this.currentCtx);\n }\n\n /**\n * Handles task error.\n *\n * If the underlying error is an abort, delegate to {@link handleAbort} —\n * which is idempotent per-ctx, so a parallel abort-listener path is safe.\n */\n protected async handleError(err: Error, ctx: TaskRunContext): Promise<void> {\n if (err instanceof TaskAbortedError) return this.handleAbort(ctx);\n if (ctx.terminated) return;\n ctx.terminated = true;\n this.clearTimeoutTimer(ctx);\n if (this.task.hasChildren()) {\n this.task.subGraph!.abort();\n }\n\n this.task.completedAt = new Date();\n if (err instanceof TaskError) {\n this.task.error = err;\n } else {\n this.task.error = new TaskFailedError(\n `Task \"${this.task.type}\" (${this.task.id}): ${err?.message || \"Task failed\"}`\n );\n }\n // Attach task context to all TaskError instances for programmatic access\n if (this.task.error instanceof TaskError) {\n this.task.error.taskType ??= this.task.type;\n this.task.error.taskId ??= this.task.id;\n }\n this.task.status = TaskStatus.FAILED;\n await this.handleProgress(100);\n\n if (ctx.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.ERROR, this.task.error.message);\n ctx.telemetrySpan.setAttributes({ \"workglow.task.error\": this.task.error.message });\n ctx.telemetrySpan.end();\n }\n\n ctx.dispose();\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n\n this.task.emit(\"error\", this.task.error);\n this.task.emit(\"status\", this.task.status);\n }\n\n protected async handleErrorPreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n protected async handleProgress(\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ): Promise<void> {\n this.task.progress = progress;\n // Emit before graph-level work (e.g. pushOutputFromNodeToEdges) so listeners are not stalled.\n this.task.emit(\"progress\", progress, message, ...args);\n await this.updateProgress(this.task, progress, message, ...args);\n }\n}\n",
|
|
28
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getPortCodec } from \"@workglow/util\";\nimport { type CachePolicy, isPolicyCached, isPolicyPrivate } from \"../cache/CachePolicy\";\nimport type { CacheRegistry } from \"../cache/CacheRegistry\";\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { ITask } from \"./ITask\";\nimport type { StreamEvent } from \"./StreamTypes\";\nimport { Task } from \"./Task\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\n\ninterface SchemaProperties {\n properties?: Record<string, { format?: string }>;\n}\n\n/**\n * @internal\n * Cache key normalization, lookup, save, and cache-hit stream-event emission\n * for streamable tasks. The three previously module-private helpers\n * (serializeOutputPorts, deserializeOutputPorts, normalizeInputsForCacheKey)\n * are private statics here.\n *\n * outputCache is passed as a method argument (not stored as a class field)\n * because the facade resolves it per-run in handleStart and may differ\n * between runs.\n */\nexport class CacheCoordinator<Input extends TaskInput, Output extends TaskOutput> {\n constructor(private readonly task: ITask<Input, Output, any>) {}\n\n /**\n * Serializes format-annotated input properties (via their port codecs) so the\n * resulting object is a stable, serialization-equivalent representation\n * suitable for use as a cache key. Properties without a format annotation are\n * passed through unchanged. No-op when no cache is configured.\n *\n * The reserved sentinel field `__cv` (cache version) is injected into the\n * normalized object before fingerprinting so that bumping a task's `static\n * version` automatically invalidates its cached outputs. Tasks must never\n * declare an input port named `__cv`.\n */\n async buildKey(inputs: Input, outputCache: TaskOutputRepository | undefined): Promise<Input> {\n if (!outputCache) return inputs;\n const inputSchema = (this.task.constructor as typeof Task).inputSchema();\n const normalized = await CacheCoordinator.normalizeInputsForCacheKey(\n inputs as Record<string, unknown>,\n inputSchema as unknown as SchemaProperties\n );\n (normalized as Record<string, unknown>).__cv = this.task.getCacheVersion();\n return normalized as Input;\n }\n\n /**\n * Looks up a cached output. On a hit for a streaming task, also emits the\n * synthetic stream_start / stream_chunk(finish) / stream_end events so\n * downstream consumers see the same event shape as a fresh run.\n *\n * Returns the deserialized output if found, undefined otherwise.\n */\n async lookup(\n keyInputs: Input,\n outputCache: TaskOutputRepository | undefined,\n isStreamable: boolean,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (!outputCache || !this.task.cacheable) return undefined;\n\n const cached = await outputCache.getOutput(this.task.type, keyInputs);\n if (cached === undefined) return undefined;\n\n const outputSchema = (this.task.constructor as typeof Task).outputSchema();\n const outputs = (await CacheCoordinator.deserializeOutputPorts(\n cached as Record<string, unknown>,\n outputSchema as unknown as SchemaProperties\n )) as Output;\n\n ctx.telemetrySpan?.addEvent(\"workglow.task.cache_hit\");\n\n if (isStreamable) {\n this.task.runOutputData = outputs;\n this.task.emit(\"stream_start\");\n this.task.emit(\"stream_chunk\", { type: \"finish\", data: outputs } as StreamEvent);\n this.task.emit(\"stream_end\", outputs);\n } else {\n this.task.runOutputData = outputs;\n }\n\n return outputs;\n }\n\n /**\n * Serializes and saves output. No-op when no cache is configured or task is\n * not cacheable.\n */\n async save(\n keyInputs: Input,\n output: Output,\n outputCache: TaskOutputRepository | undefined\n ): Promise<void> {\n if (!outputCache || !this.task.cacheable || output === undefined) return;\n const outputSchema = (this.task.constructor as typeof Task).outputSchema();\n const wireOutputs = await CacheCoordinator.serializeOutputPorts(\n output as Record<string, unknown>,\n outputSchema as unknown as SchemaProperties\n );\n await outputCache.saveOutput(this.task.type, keyInputs, wireOutputs as Output);\n }\n\n // ========================================================================\n // Policy-aware routing methods\n // ========================================================================\n\n /**\n * Resolve the repository slot to use given a registry and policy. Returns\n * `undefined` if the registry is missing, the policy is `kind: \"none\"`, or\n * the relevant slot is unregistered. All callers treat `undefined` as \"skip\n * caching\" — no errors, no warnings.\n */\n private repoFor(\n registry: CacheRegistry | undefined,\n policy: CachePolicy\n ): TaskOutputRepository | undefined {\n if (!registry || !isPolicyCached(policy)) return undefined;\n return isPolicyPrivate(policy) ? registry.private : registry.deterministic;\n }\n\n public async buildKeyForPolicy(\n inputs: Input,\n registry: CacheRegistry | undefined,\n policy: CachePolicy\n ): Promise<Input> {\n return this.buildKey(inputs, this.repoFor(registry, policy));\n }\n\n public async lookupByPolicy(\n keyInputs: Input,\n registry: CacheRegistry | undefined,\n policy: CachePolicy,\n isStreamable: boolean,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.lookup(keyInputs, this.repoFor(registry, policy), isStreamable, ctx);\n }\n\n public async saveByPolicy(\n keyInputs: Input,\n output: Output,\n registry: CacheRegistry | undefined,\n policy: CachePolicy\n ): Promise<void> {\n return this.save(keyInputs, output, this.repoFor(registry, policy));\n }\n\n // ========================================================================\n // Private static helpers (lifted from current module-private functions in\n // TaskRunner.ts)\n // ========================================================================\n\n private static async serializeOutputPorts(\n output: Record<string, unknown>,\n schema: SchemaProperties\n ): Promise<Record<string, unknown>> {\n if (!schema?.properties) return output;\n const out: Record<string, unknown> = { ...output };\n for (const [key, prop] of Object.entries(schema.properties)) {\n const codec = prop.format ? getPortCodec(prop.format) : undefined;\n if (codec && out[key] !== undefined) {\n out[key] = await codec.serialize(out[key]);\n }\n }\n return out;\n }\n\n private static async deserializeOutputPorts(\n output: Record<string, unknown>,\n schema: SchemaProperties\n ): Promise<Record<string, unknown>> {\n if (!schema?.properties) return output;\n const out: Record<string, unknown> = { ...output };\n for (const [key, prop] of Object.entries(schema.properties)) {\n const codec = prop.format ? getPortCodec(prop.format) : undefined;\n if (codec && out[key] !== undefined) {\n out[key] = await codec.deserialize(out[key]);\n }\n }\n return out;\n }\n\n private static async normalizeInputsForCacheKey(\n inputs: Record<string, unknown>,\n schema: SchemaProperties\n ): Promise<Record<string, unknown>> {\n if (!schema?.properties) return inputs;\n const out: Record<string, unknown> = { ...inputs };\n for (const [key, prop] of Object.entries(schema.properties)) {\n const codec = prop.format ? getPortCodec(prop.format) : undefined;\n if (codec && out[key] !== undefined) {\n out[key] = await codec.serialize(out[key]);\n }\n }\n return out;\n }\n}\n",
|
|
29
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ResourceScope, ServiceRegistry } from \"@workglow/util\";\nimport type { Taskish } from \"../task-graph/Conversions\";\nimport type { ITask } from \"./ITask\";\nimport type { StreamEvent, StreamMode } from \"./StreamTypes\";\nimport { getOutputStreamMode, getStreamingPorts } from \"./StreamTypes\";\nimport { TaskAbortedError, TaskError } from \"./TaskError\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\nimport { TaskStatus } from \"./TaskTypes\";\n\n/**\n * Per-call run-state inputs shared by StreamProcessor.run. Bundles facade\n * state pulled at call time (registry, resourceScope, inputStreams) and\n * facade methods bound to the facade instance (onProgress, own).\n *\n * @internal\n */\nexport interface StreamProcessorDeps {\n readonly registry: ServiceRegistry;\n readonly resourceScope: ResourceScope | undefined;\n readonly inputStreams: Map<string, ReadableStream<StreamEvent>> | undefined;\n readonly onProgress: (\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ) => Promise<void>;\n readonly own: <T extends Taskish<any, any>>(i: T) => T;\n}\n\n/**\n * @internal\n * Streaming event loop. Consumes a task's executeStream() output, manages\n * text/object delta accumulators, mode switching (append/object/replace),\n * and finish-event enrichment. Honors ctx.shouldAccumulate and\n * ctx.abortController.signal.\n */\nexport class StreamProcessor<Input extends TaskInput, Output extends TaskOutput> {\n constructor(private readonly task: ITask<Input, Output, any>) {}\n\n async run(\n input: Input,\n ctx: TaskRunContext,\n deps: StreamProcessorDeps\n ): Promise<Output | undefined> {\n const streamMode: StreamMode = getOutputStreamMode(this.task.outputSchema());\n if (streamMode === \"append\") {\n const ports = getStreamingPorts(this.task.outputSchema());\n if (ports.length === 0) {\n throw new TaskError(\n `Task ${this.task.type} declares append streaming but no output port has x-stream: \"append\"`\n );\n }\n }\n if (streamMode === \"object\") {\n const ports = getStreamingPorts(this.task.outputSchema());\n if (ports.length === 0) {\n throw new TaskError(\n `Task ${this.task.type} declares object streaming but no output port has x-stream: \"object\"`\n );\n }\n }\n\n const accumulated = ctx.shouldAccumulate ? new Map<string, string>() : undefined;\n const accumulatedObjects = ctx.shouldAccumulate\n ? new Map<string, Record<string, unknown> | unknown[]>()\n : undefined;\n let streamingStarted = false;\n let finalOutput: Output | undefined;\n\n this.task.emit(\"stream_start\");\n\n const stream = this.task.executeStream!(input, {\n signal: ctx.abortController.signal,\n updateProgress: deps.onProgress,\n own: deps.own,\n registry: deps.registry,\n resourceScope: deps.resourceScope,\n inputStreams: deps.inputStreams,\n });\n\n for await (const event of stream) {\n // For snapshot events, update runOutputData BEFORE emitting stream_chunk\n // so listeners see the latest snapshot when they handle the event.\n if (event.type === \"snapshot\") {\n this.task.runOutputData = event.data as Output;\n }\n\n switch (event.type) {\n case \"phase\": {\n // Phase events are metadata: emit for observability, translate to a\n // progress event with optional progress + message, do NOT mutate\n // accumulators or runOutputData, do NOT flip status to STREAMING.\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n await deps.onProgress(event.progress, event.message);\n break;\n }\n case \"text-delta\": {\n if (!streamingStarted) {\n streamingStarted = true;\n this.task.status = TaskStatus.STREAMING;\n this.task.emit(\"status\", this.task.status);\n }\n if (accumulated) {\n accumulated.set(event.port, (accumulated.get(event.port) ?? \"\") + event.textDelta);\n }\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n break;\n }\n case \"object-delta\": {\n if (!streamingStarted) {\n streamingStarted = true;\n this.task.status = TaskStatus.STREAMING;\n this.task.emit(\"status\", this.task.status);\n }\n if (accumulatedObjects) {\n const existing = accumulatedObjects.get(event.port);\n if (Array.isArray(event.objectDelta)) {\n // Array delta: upsert items by `id` into accumulated array\n const arr: unknown[] = Array.isArray(existing) ? [...existing] : [];\n for (const item of event.objectDelta) {\n const itemObj = item as Record<string, unknown>;\n if (itemObj && typeof itemObj === \"object\" && \"id\" in itemObj) {\n const idx = arr.findIndex(\n (e) => (e as Record<string, unknown>).id === itemObj.id\n );\n if (idx >= 0) arr[idx] = item;\n else arr.push(item);\n } else {\n arr.push(item);\n }\n }\n accumulatedObjects.set(event.port, arr);\n } else {\n // Non-array (e.g. structured generation): replace semantics\n accumulatedObjects.set(event.port, event.objectDelta);\n }\n }\n // Update runOutputData with accumulated state so listeners see growing state\n this.task.runOutputData = {\n ...this.task.runOutputData,\n [event.port]: accumulatedObjects?.get(event.port) ?? event.objectDelta,\n } as Output;\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n break;\n }\n case \"snapshot\": {\n if (!streamingStarted) {\n streamingStarted = true;\n this.task.status = TaskStatus.STREAMING;\n this.task.emit(\"status\", this.task.status);\n }\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n break;\n }\n case \"finish\": {\n if (accumulated || accumulatedObjects) {\n // Emit an enriched finish event: merge accumulated deltas into\n // the finish payload so downstream dataflows get complete port data\n // without needing to re-accumulate themselves.\n const merged: Record<string, unknown> = { ...(event.data || {}) };\n if (accumulated) {\n for (const [port, text] of accumulated) {\n if (text.length > 0) merged[port] = text;\n }\n }\n if (accumulatedObjects) {\n for (const [port, obj] of accumulatedObjects) {\n merged[port] = obj;\n }\n }\n // For replace-mode streams, finish carries data: {} by convention.\n // Fall back to the last snapshot (runOutputData) so the final output\n // is not silently cleared when the finish payload is empty.\n if (streamMode === \"replace\" && Object.keys(merged).length === 0) {\n const lastSnapshot = this.task.runOutputData;\n if (lastSnapshot && Object.keys(lastSnapshot).length > 0) {\n finalOutput = lastSnapshot as Output;\n this.task.emit(\"stream_chunk\", {\n type: \"finish\",\n data: lastSnapshot,\n } as StreamEvent);\n break;\n }\n }\n finalOutput = merged as unknown as Output;\n this.task.emit(\"stream_chunk\", { type: \"finish\", data: merged } as StreamEvent);\n } else {\n // No accumulation. For replace-mode streams the provider's finish\n // event carries `data: {}` by convention — the snapshots already\n // delivered the value, so the finish payload is intentionally\n // empty. Fall back to `runOutputData` (set on every snapshot above)\n // so we don't clobber the last snapshot with an empty object. This\n // mirrors the same fallback in the accumulation branch.\n const finishData = (event.data ?? {}) as Record<string, unknown>;\n if (streamMode === \"replace\" && Object.keys(finishData).length === 0) {\n const lastSnapshot = this.task.runOutputData;\n if (lastSnapshot && Object.keys(lastSnapshot).length > 0) {\n finalOutput = lastSnapshot as Output;\n this.task.emit(\"stream_chunk\", {\n type: \"finish\",\n data: lastSnapshot,\n } as StreamEvent);\n break;\n }\n }\n finalOutput = event.data as Output;\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n }\n break;\n }\n case \"error\": {\n throw event.error;\n }\n }\n }\n\n // Check if the task was aborted during streaming\n if (ctx.abortController.signal.aborted) {\n throw new TaskAbortedError(\"Task aborted during streaming\");\n }\n\n if (finalOutput !== undefined) {\n this.task.runOutputData = finalOutput;\n }\n\n this.task.emit(\"stream_end\", this.task.runOutputData as Output);\n\n return this.task.runOutputData as Output;\n }\n}\n",
|
|
30
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ISpan } from \"@workglow/util\";\nimport type { TaskTimeoutError } from \"./TaskError\";\n\n/**\n * @internal\n * Per-run mutable state for a single TaskRunner.run() / runPreview() invocation.\n * Built by TaskRunner.handleStart, discarded by handleComplete / handleError / handleAbort.\n *\n * Long-lived state (task, registry, resourceScope, outputCache default, accumulateLeafOutputs)\n * stays on the facade. TaskRunContext only holds state created at run start and torn down\n * at run end.\n */\nexport class TaskRunContext {\n readonly abortController: AbortController;\n\n shouldAccumulate: boolean = true;\n telemetrySpan?: ISpan;\n timeoutTimer?: ReturnType<typeof setTimeout>;\n pendingTimeoutError?: TaskTimeoutError;\n\n /**\n * Set by the first terminal handler (handleAbort / handleComplete / handleError /\n * handleDisable) that runs for this ctx. Lets handlers be idempotent per-ctx\n * without leaning on `task.status`, which is externally observable and can be\n * mutated by adjacent runs.\n */\n terminated: boolean = false;\n\n // Removes the parentSignal abort listener; set in the constructor when\n // parentSignal is provided. Idempotent dispose().\n private parentSignalCleanup?: () => void;\n\n constructor(parentSignal?: AbortSignal) {\n this.abortController = new AbortController();\n if (parentSignal) {\n // Listen first, then check — addEventListener on an already-aborted signal\n // does not fire, so checking .aborted after ensures we never miss an abort.\n const onParentAbort = () => this.abortController.abort();\n parentSignal.addEventListener(\"abort\", onParentAbort, { once: true });\n this.parentSignalCleanup = () => parentSignal.removeEventListener(\"abort\", onParentAbort);\n if (parentSignal.aborted) {\n this.parentSignalCleanup();\n this.parentSignalCleanup = undefined;\n this.abortController.abort();\n }\n }\n }\n\n /**\n * Releases external listeners (parentSignal abort handler). Idempotent.\n * Called by terminal handlers (handleComplete / handleError / handleAbort)\n * so a parent abort fired after this run completes does not re-trigger our\n * abort path and emit a duplicate terminal event.\n */\n dispose(): void {\n this.parentSignalCleanup?.();\n this.parentSignalCleanup = undefined;\n }\n}\n",
|
|
31
32
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport type { ImageValue } from \"@workglow/util/media\";\nimport { previewSource } from \"@workglow/util/media\";\nimport type { ITask } from \"../task/ITask\";\nimport type { TaskInput, TaskOutput } from \"../task/TaskTypes\";\nimport { TaskStatus } from \"../task/TaskTypes\";\nimport { DATAFLOW_ALL_PORTS, DATAFLOW_ERROR_PORT } from \"./Dataflow\";\nimport type { TaskGraph } from \"./TaskGraph\";\nimport type { TaskGraphRunner } from \"./TaskGraphRunner\";\n\n/**\n * @internal\n * Reads inputs from incoming dataflows, writes outputs/errors to outgoing dataflows.\n * Owns dataflow transforms and error-port routing.\n *\n * Methods take the task they operate on. None take a RunContext — the caller\n * (TaskGraphRunner.runTask or RunScheduler.runLoop) is responsible for routing\n * any errors that bubble out of these methods into ctx.failedTaskErrors.\n *\n * Holds a back-reference to the facade so it can read facade-owned long-lived\n * state (`registry`, `previewRunning`) and route through the facade's\n * `runScheduler` for status push and disabled cascade.\n */\nexport class EdgeMaterializer {\n constructor(\n private readonly graph: TaskGraph,\n private readonly runner: TaskGraphRunner\n ) {}\n\n /**\n * Filters graph-level input to only include properties that are not connected via dataflows for a given task\n * @param task The task to filter input for\n * @param input The graph-level input\n * @returns Filtered input containing only unconnected properties\n */\n public filterInputForTask(task: ITask, input: TaskInput): TaskInput {\n // Get all inputs that are connected to this task via dataflows\n const sourceDataflows = this.graph.getSourceDataflows(task.id);\n const connectedInputs = new Set(sourceDataflows.map((df) => df.targetTaskPortId));\n\n // If DATAFLOW_ALL_PORTS (\"*\") is in the set, all inputs are connected\n const allPortsConnected = connectedInputs.has(DATAFLOW_ALL_PORTS);\n\n // Filter out connected inputs from the graph input\n const filteredInput: TaskInput = {};\n for (const [key, value] of Object.entries(input)) {\n // Skip this input if it's explicitly connected OR if all ports are connected\n if (!connectedInputs.has(key) && !allPortsConnected) {\n filteredInput[key] = value;\n }\n }\n\n return filteredInput;\n }\n\n /**\n * Copies input data from edges to a task\n * @param task The task to copy input data to\n */\n public copyInputFromEdgesToNode(task: ITask) {\n const dataflows = this.graph.getSourceDataflows(task.id);\n // Sort by dataflow id for deterministic input merging regardless of insertion order\n dataflows.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n for (const dataflow of dataflows) {\n // Use getCurrentValue() to pick up latestSnapshot when the edge is\n // mid-stream (i.e. value is undefined but latestSnapshot is populated).\n // We re-implement getPortData()'s wrapping with the live value.\n const live = dataflow.getCurrentValue();\n const port = dataflow.targetTaskPortId;\n let portData: TaskOutput;\n if (port === DATAFLOW_ALL_PORTS) {\n portData = live as TaskOutput;\n } else if (port === DATAFLOW_ERROR_PORT) {\n portData = { [DATAFLOW_ERROR_PORT]: dataflow.error } as unknown as TaskOutput;\n } else {\n portData = { [port]: live } as TaskOutput;\n }\n this.runner.addInputData(task, portData);\n }\n }\n\n /**\n * Pushes the output of a task to its target tasks\n * @param node The task that produced the output\n * @param results The output of the task\n */\n public async pushOutputFromNodeToEdges(node: ITask, results: TaskOutput) {\n const dataflows = this.graph.getTargetDataflows(node.id);\n\n // Preview-mode chain-head downscale: apply `previewSource` to any\n // image-shaped output before it's pushed downstream. This relocates the\n // per-task `executePreview` invocation of `previewSource` to the engine,\n // where it fires once per chain head and is idempotent on already-small\n // images (returns the input unchanged when within budget).\n // Bracket access — previewRunning stays protected on the facade.\n if (this.runner[\"previewRunning\"] && Object.keys(results).length > 0) {\n for (const port of Object.keys(results)) {\n const value = (results as Record<string, unknown>)[port];\n if (EdgeMaterializer.isImageValueShape(value)) {\n (results as Record<string, unknown>)[port] = await previewSource(value as ImageValue);\n }\n }\n }\n\n for (const dataflow of dataflows) {\n // Edges with an active stream have their final value materialised by the\n // downstream task's awaitStreamInputs (which uses Dataflow.awaitStreamValue\n // to read the raw snapshot/finish data and then applies transforms).\n // Setting port data here would be overwritten by the finish event, and\n // applying transforms again on this path would double-apply\n // non-idempotent transforms, so skip the whole post-materialisation step.\n if (dataflow.stream !== undefined) continue;\n // Bracket access — registry stays protected on the facade.\n const registry = this.runner[\"registry\"];\n const compatibility = dataflow.semanticallyCompatible(this.graph, dataflow, registry);\n if (compatibility === \"static\") {\n dataflow.setPortData(results);\n await dataflow.applyTransforms(registry);\n } else if (compatibility === \"runtime\") {\n const task = this.graph.getTask(dataflow.targetTaskId)!;\n const narrowed = await task.narrowInput({ ...results }, registry);\n dataflow.setPortData(narrowed);\n await dataflow.applyTransforms(registry);\n } else {\n // Warn only when we had data to push; empty results (e.g. progress mid-run) are expected\n const resultsKeys = Object.keys(results);\n if (resultsKeys.length > 0) {\n getLogger().warn(\"pushOutputFromNodeToEdge not compatible, not setting port data\", {\n dataflowId: dataflow.id,\n compatibility,\n resultsKeys,\n });\n }\n }\n }\n }\n\n /**\n * Pushes the error of a task to its target edges\n * @param node The task that produced the error\n */\n public pushErrorFromNodeToEdges(node: ITask): void {\n if (!node?.config?.id) return;\n this.graph.getTargetDataflows(node.id).forEach((dataflow) => {\n dataflow.error = node.error;\n });\n }\n\n /**\n * Returns true if the task has any outgoing dataflow edges that use the\n * error output port (`[error]`). These edges indicate that the task's\n * errors should be routed to downstream handler tasks instead of failing\n * the entire graph.\n */\n public hasErrorOutputEdges(task: ITask): boolean {\n const dataflows = this.graph.getTargetDataflows(task.id);\n return dataflows.some((df) => df.sourceTaskPortId === DATAFLOW_ERROR_PORT);\n }\n\n /**\n * Routes a failed task's error through its error-port dataflow edges.\n *\n * For each outgoing dataflow:\n * - Error-port edges (`[error]`) receive the error data and get COMPLETED status\n * - Non-error-port edges get DISABLED status (the task didn't produce normal output)\n *\n * After setting edge statuses, propagateDisabledStatus() cascades DISABLED\n * through any downstream tasks that only had non-error inputs from this task.\n */\n public pushErrorOutputToEdges(task: ITask): void {\n const taskError = task.error;\n const errorData = {\n error: taskError?.message ?? \"Unknown error\",\n errorType: (taskError?.constructor as { type?: string })?.type ?? \"TaskError\",\n };\n\n const dataflows = this.graph.getTargetDataflows(task.id);\n for (const df of dataflows) {\n if (df.sourceTaskPortId === DATAFLOW_ERROR_PORT) {\n // Route error data to the error-port edge\n df.value = errorData;\n df.setStatus(TaskStatus.COMPLETED);\n } else {\n // Normal output edges are disabled — this task didn't produce output\n df.setStatus(TaskStatus.DISABLED);\n }\n }\n\n // Cascade disabled status to downstream tasks whose ALL inputs are now disabled.\n // Bracket access — runScheduler and currentCtx stay protected on the facade.\n this.runner[\"runScheduler\"].propagateDisabledStatus(this.runner[\"currentCtx\"]);\n }\n\n /**\n * Resets a task. Takes an explicit `graph` because `resetGraph` recurses\n * into `node.subGraph` for nested tasks and the EdgeMaterializer's own\n * `this.graph` reference is bound to the top-level graph only.\n *\n * @param graph The task graph that owns the task being reset\n * @param task The task to reset\n * @param runId The run ID\n */\n public resetTask(graph: TaskGraph, task: ITask, runId: string) {\n task.status = TaskStatus.PENDING;\n task.resetInputData();\n task.runOutputData = {};\n task.error = undefined;\n task.progress = 0;\n task.runConfig = { ...task.runConfig, runnerId: runId };\n // Bracket access — runScheduler and currentCtx stay protected on the facade.\n this.runner[\"runScheduler\"].pushStatusFromNodeToEdges(\n task,\n this.runner[\"currentCtx\"],\n undefined,\n graph\n );\n // Inline the error-edge reset using the per-call graph (this.pushErrorFromNodeToEdges\n // would use this.graph, which is wrong for recursive subgraph resets).\n if (task?.config?.id) {\n graph.getTargetDataflows(task.id).forEach((dataflow) => {\n dataflow.error = task.error;\n });\n }\n task.emit(\"reset\");\n task.emit(\"status\", task.status);\n }\n\n /**\n * Duck-typed predicate for an `ImageValue`-shaped output, used by the engine\n * to decide whether to apply `previewSource` during `runPreview`. Unlike\n * `isImageValue` from `@workglow/util/media`, this predicate does not check\n * `instanceof ImageBitmap` / `Buffer.isBuffer`, so it remains correct across\n * realm boundaries (e.g. bundle copies in test harnesses) where those identity\n * checks can spuriously fail.\n */\n private static isImageValueShape(\n v: unknown\n ): v is { width: number; height: number; previewScale: number } {\n if (v === null || typeof v !== \"object\") return false;\n const o = v as Record<string, unknown>;\n return (\n typeof o.width === \"number\" &&\n typeof o.height === \"number\" &&\n typeof o.previewScale === \"number\"\n );\n }\n}\n",
|
|
32
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ISpan } from \"@workglow/util\";\nimport { uuid4 } from \"@workglow/util\";\nimport type { IEntitlementEnforcer } from \"../task/EntitlementEnforcer\";\nimport type { TaskError, TaskGraphTimeoutError } from \"../task/TaskError\";\nimport type { TaskOutput } from \"../task/TaskTypes\";\n\n/**\n * @internal\n * Per-run mutable state for a single TaskGraphRunner.runGraph() invocation.\n * Built by TaskGraphRunner.handleStart(), discarded by handleComplete/Error/Abort.\n *\n * All long-lived state (graph, schedulers, registry, resourceScope, outputCache,\n * accumulateLeafOutputs) stays on the facade. RunContext only holds state that is\n * created at the start of a run and torn down when the run terminates.\n */\nexport class RunContext {\n readonly runId: string;\n readonly abortController: AbortController;\n readonly inProgressTasks: Map<unknown, Promise<TaskOutput>> = new Map();\n readonly inProgressFunctions: Map<unknown, Promise<void>> = new Map();\n readonly failedTaskErrors: Map<unknown, TaskError> = new Map();\n\n telemetrySpan?: ISpan;\n graphTimeoutTimer?: ReturnType<typeof setTimeout>;\n pendingGraphTimeoutError?: TaskGraphTimeoutError;\n activeEnforcer?: IEntitlementEnforcer;\n\n // Removes the parentSignal abort listener, if one was registered. Set in the\n // constructor when parentSignal is provided; called from dispose().\n private parentSignalCleanup?: () => void;\n\n constructor(parentSignal?: AbortSignal) {\n this.runId = uuid4();\n this.abortController = new AbortController();\n if (parentSignal) {\n // Listen first, then check — addEventListener on an already-aborted signal\n // does not fire, so checking .aborted after ensures we never miss an abort.\n // Pattern preserved from commit 4e50c99e.\n const onParentAbort = () => this.abortController.abort();\n parentSignal.addEventListener(\"abort\", onParentAbort, { once: true });\n this.parentSignalCleanup = () => parentSignal.removeEventListener(\"abort\", onParentAbort);\n if (parentSignal.aborted) {\n this.parentSignalCleanup();\n this.parentSignalCleanup = undefined;\n this.abortController.abort();\n }\n }\n }\n\n /**\n * Releases external listeners (parentSignal abort handler). Idempotent.\n * Called by terminal handlers (handleComplete/Error/Abort) so a parent abort\n * fired after this run completes does not re-trigger our abort path and emit\n * a duplicate terminal event.\n */\n dispose(): void {\n this.parentSignalCleanup?.();\n this.parentSignalCleanup = undefined;\n }\n}\n",
|
|
33
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport { ConditionalTask } from \"../task/ConditionalTask\";\nimport type { ITask } from \"../task/ITask\";\nimport { TaskError, TaskGraphTimeoutError } from \"../task/TaskError\";\nimport type { TaskInput, TaskOutput } from \"../task/TaskTypes\";\nimport { TaskStatus } from \"../task/TaskTypes\";\nimport type { EdgeMaterializer } from \"./EdgeMaterializer\";\nimport type { RunContext } from \"./RunContext\";\nimport type { TaskGraph, TaskGraphRunConfig } from \"./TaskGraph\";\nimport type { GraphResultArray, GraphSingleTaskResult, TaskGraphRunner } from \"./TaskGraphRunner\";\nimport { taskPrototypeHasOwnExecute } from \"./TaskGraphRunner\";\nimport type { ITaskGraphScheduler } from \"./TaskGraphScheduler\";\n\n/**\n * @internal\n * Run-loop coordinator. Drives task selection via processScheduler,\n * arms graph-level timeout, propagates disabled cascade, aggregates progress,\n * and pushes status to outgoing edges.\n *\n * Stateless across runs — all per-run state arrives via `ctx`.\n *\n * Holds a back-reference to the facade so runLoop can call facade.runTask().\n * This keeps runTask as the single per-task choreography point that wires\n * EdgeMaterializer + StreamPump + the integration with TaskRunner.\n */\nexport class RunScheduler {\n constructor(\n private readonly graph: TaskGraph,\n private readonly processScheduler: ITaskGraphScheduler,\n private readonly facade: TaskGraphRunner\n ) {}\n\n /**\n * Pushes the status of a task to its target edges\n * @param node The task that produced the status\n *\n * For ConditionalTask, this method handles selective dataflow status:\n * - Active branch dataflows get COMPLETED status\n * - Inactive branch dataflows get DISABLED status\n */\n pushStatusFromNodeToEdges(\n node: ITask,\n ctx: RunContext | undefined,\n status?: TaskStatus,\n graph: TaskGraph = this.graph\n ): void {\n if (!node?.config?.id) return;\n\n const dataflows = graph.getTargetDataflows(node.id);\n const effectiveStatus = status ?? node.status;\n\n // Check if this is a ConditionalTask with selective branching\n if (node instanceof ConditionalTask && effectiveStatus === TaskStatus.COMPLETED) {\n // Build a map of output port -> branch ID for lookup\n const branches = node.config.branches ?? [];\n const portToBranch = new Map<string, string>();\n for (const branch of branches) {\n portToBranch.set(branch.outputPort, branch.id);\n }\n\n const activeBranches = node.getActiveBranches();\n\n for (const dataflow of dataflows) {\n // Preserve FAILED edges (e.g. transform chain failure) rather than\n // overwriting with the source task's completion status.\n if (dataflow.status === TaskStatus.FAILED) continue;\n const branchId = portToBranch.get(dataflow.sourceTaskPortId);\n if (branchId !== undefined) {\n // This dataflow is from a branch port\n if (activeBranches.has(branchId)) {\n // Branch is active - dataflow gets completed status\n dataflow.setStatus(TaskStatus.COMPLETED);\n } else {\n // Branch is inactive - dataflow gets disabled status\n dataflow.setStatus(TaskStatus.DISABLED);\n }\n } else {\n // Not a branch port (e.g., _activeBranches metadata) - use normal status\n dataflow.setStatus(effectiveStatus);\n }\n }\n\n // Cascade disabled status to downstream tasks\n this.propagateDisabledStatus(ctx, graph);\n return;\n }\n\n // Default behavior for non-conditional tasks\n dataflows.forEach((dataflow) => {\n // Preserve FAILED edges (e.g. transform chain failure) rather than\n // overwriting with the source task's completion status.\n if (dataflow.status === TaskStatus.FAILED) return;\n dataflow.setStatus(effectiveStatus);\n });\n }\n\n /**\n * Propagates DISABLED status through the graph.\n *\n * When a task's ALL incoming dataflows are DISABLED, that task becomes unreachable\n * and should also be disabled. This cascades through the graph until no more\n * tasks can be disabled.\n *\n * This is used by ConditionalTask to disable downstream tasks on inactive branches.\n *\n * `_ctx` is accepted for symmetry with other RunScheduler methods (which thread\n * per-run state through the RunContext) and to leave room for future per-run\n * scheduling state without a signature change. Currently unused — the cascade\n * operates on graph-level task status alone.\n */\n propagateDisabledStatus(_ctx: RunContext | undefined, graph: TaskGraph = this.graph): void {\n let changed = true;\n\n // Keep iterating until no more changes (fixed-point iteration)\n while (changed) {\n changed = false;\n\n for (const task of graph.getTasks()) {\n // Only consider tasks that are still pending\n if (task.status !== TaskStatus.PENDING) {\n continue;\n }\n\n const incomingDataflows = graph.getSourceDataflows(task.id);\n\n // Skip tasks with no incoming dataflows (root tasks)\n if (incomingDataflows.length === 0) {\n continue;\n }\n\n // Check if ALL incoming dataflows are DISABLED\n const allDisabled = incomingDataflows.every((df) => df.status === TaskStatus.DISABLED);\n\n if (allDisabled) {\n // This task is unreachable - disable it synchronously\n // Set status directly to avoid async issues\n task.status = TaskStatus.DISABLED;\n task.progress = 100;\n task.completedAt = new Date();\n task.emit(\"disabled\");\n task.emit(\"status\", task.status);\n\n // Propagate disabled status to its outgoing dataflows\n graph.getTargetDataflows(task.id).forEach((dataflow) => {\n dataflow.setStatus(TaskStatus.DISABLED);\n });\n\n // Mark as completed in scheduler so it doesn't wait for this task\n this.processScheduler.onTaskCompleted(task.id);\n\n changed = true;\n }\n }\n }\n }\n\n /**\n * Handles progress updates for the task graph by averaging `progress` across tasks whose class\n * declares its own `execute` (see {@link taskPrototypeHasOwnExecute}). Other nodes are ignored.\n */\n async handleProgress(\n ctx: RunContext,\n task: ITask,\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ): Promise<void> {\n const contributors = this.graph.getTasks().filter(taskPrototypeHasOwnExecute);\n if (contributors.length > 1) {\n const determinate = contributors.filter((t) => t.progress !== undefined);\n if (determinate.length === 0) {\n progress = undefined;\n } else {\n const sum = determinate.reduce((acc, t) => acc + t.progress!, 0);\n progress = Math.round(sum / determinate.length);\n }\n } else if (contributors.length === 1) {\n const [only] = contributors;\n progress = only.progress;\n }\n this.pushStatusFromNodeToEdges(task, ctx);\n // Emit aggregate progress before awaiting output push so UIs (and task `emit(\"progress\")` in\n // TaskRunner) are not blocked when pushOutput/narrowInput is slow or stalls mid-run.\n this.graph.emit(\"graph_progress\", progress, message, args);\n // Only push output for mid-run progress ticks while the task is actively executing.\n // Terminal-state handlers (complete, abort, error, disable) set task.status to their\n // terminal value before calling handleProgress(100), so the output push is skipped here —\n // the graph runner's own post-run pushOutputFromNodeToEdges handles the completed case.\n const isActive = task.status === TaskStatus.PROCESSING || task.status === TaskStatus.STREAMING;\n if (isActive && task.runOutputData && Object.keys(task.runOutputData).length > 0) {\n // Bracket access keeps `edgeMaterializer` protected on the facade — only `runScheduler` was widened to public.\n await this.facade[\"edgeMaterializer\"].pushOutputFromNodeToEdges(task, task.runOutputData);\n }\n }\n\n /**\n * Arms the graph-level timeout. The timer fires `pendingGraphTimeoutError`\n * and aborts the run when elapsed. No-op when `timeoutMs <= 0`.\n *\n * @remarks Treats `timeoutMs <= 0` as \"no timeout\" (silent no-op), not as\n * \"fire immediately\". Callers that want immediate cancellation should call\n * `ctx.abortController.abort()` directly.\n */\n armGraphTimeout(timeoutMs: number, ctx: RunContext): void {\n if (timeoutMs <= 0) return;\n ctx.pendingGraphTimeoutError = undefined;\n ctx.graphTimeoutTimer = setTimeout(() => {\n ctx.pendingGraphTimeoutError = new TaskGraphTimeoutError(timeoutMs);\n ctx.abortController.abort();\n }, timeoutMs);\n }\n\n /**\n * Clears the graph-level timeout timer if active.\n */\n clearGraphTimeout(ctx: RunContext): void {\n if (ctx.graphTimeoutTimer !== undefined) {\n clearTimeout(ctx.graphTimeoutTimer);\n ctx.graphTimeoutTimer = undefined;\n }\n }\n\n /**\n * Inner for-await loop body of {@link TaskGraphRunner.runGraph}. Drives the\n * processScheduler, dispatches tasks via `facade.runTask`, routes errors,\n * and pushes status/error to outgoing edges. Returns the per-leaf results\n * (terminal-state precedence is the facade's responsibility).\n */\n async runLoop<O extends TaskOutput>(\n input: TaskInput,\n config: TaskGraphRunConfig | undefined,\n ctx: RunContext,\n edgeMat: EdgeMaterializer\n ): Promise<GraphResultArray<O>> {\n const results: GraphResultArray<O> = [];\n\n try {\n // TODO: A different graph runner may chunk tasks that are in parallel\n // rather them all currently available\n for await (const task of this.processScheduler.tasks()) {\n if (ctx.abortController.signal.aborted) {\n break;\n }\n\n if (ctx.failedTaskErrors.size > 0) {\n break;\n }\n\n const isRootTask = this.graph.getSourceDataflows(task.id).length === 0;\n\n const runAsync = async () => {\n let errorRouted = false;\n try {\n // Root tasks (no incoming dataflows) receive the graph run input so e.g.\n // InputTask can seed the graph. Downstream tasks rely only on dataflow\n // edges plus task defaults — unless matchAllEmptyInputs is true, in which case\n // we filter the input to only include properties that are not connected via dataflows.\n const taskInput = isRootTask\n ? input\n : config?.matchAllEmptyInputs\n ? edgeMat.filterInputForTask(task, input)\n : {};\n\n // Bracket access — runTask stays protected on purpose; this is the back-ref entry point.\n const taskPromise = this.facade[\"runTask\"](task, taskInput);\n ctx.inProgressTasks.set(task.id, taskPromise);\n const taskResult = await taskPromise;\n\n if (this.graph.getTargetDataflows(task.id).length === 0) {\n // we save the results of all the leaves\n results.push(taskResult as GraphSingleTaskResult<O>);\n }\n } catch (error) {\n if (edgeMat.hasErrorOutputEdges(task)) {\n // Route the error through error-port dataflows instead of failing the graph.\n // pushErrorOutputToEdges sets edge statuses directly (COMPLETED for error\n // edges, DISABLED for normal edges), so we skip the normal status push.\n errorRouted = true;\n edgeMat.pushErrorOutputToEdges(task);\n } else {\n ctx.failedTaskErrors.set(task.id, error as TaskError);\n }\n } finally {\n // IMPORTANT: Push status to edges BEFORE notifying scheduler\n // This ensures dataflow statuses (including DISABLED) are set\n // before the scheduler checks which tasks are ready.\n // Skip normal status push when error routing already set edge statuses.\n if (!errorRouted) {\n this.pushStatusFromNodeToEdges(task, ctx);\n edgeMat.pushErrorFromNodeToEdges(task);\n }\n this.processScheduler.onTaskCompleted(task.id);\n }\n };\n\n // Start task execution without awaiting\n // so we can have many tasks running in parallel\n // but keep track of them to make sure they get awaited\n // otherwise, things will finish after this promise is resolved\n ctx.inProgressFunctions.set(Symbol(task.id as string), runAsync());\n }\n } catch (err) {\n getLogger().error(\"Error running graph\", { error: err });\n }\n\n // Wait for all tasks to complete since we did not await runAsync()/this.runTaskWithProvenance()\n await Promise.allSettled(Array.from(ctx.inProgressTasks.values()));\n // Clean up stragglers to avoid unhandled promise rejections\n await Promise.allSettled(Array.from(ctx.inProgressFunctions.values()));\n\n return results;\n }\n}\n",
|
|
34
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport type { UIConditionConfig } from \"./ConditionUtils\";\nimport { evaluateCondition, getNestedValue } from \"./ConditionUtils\";\nimport type { IExecuteContext } from \"./ITask\";\nimport { Task } from \"./Task\";\nimport type { TaskConfig, TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\nimport { TaskConfigSchema } from \"./TaskTypes\";\n\n/**\n * A predicate function that evaluates whether a branch condition is met.\n * Returns true if the branch should be active.\n */\nexport type ConditionFn<Input> = (input: Input) => boolean;\n\n/**\n * Configuration for a single branch in a ConditionalTask. When `condition`\n * returns true, the branch becomes active and its output port receives the\n * task's input data.\n */\nexport interface BranchConfig<Input> {\n readonly id: string;\n readonly condition: ConditionFn<Input>;\n /** Name of the output port that will receive data when this branch is active */\n readonly outputPort: string;\n}\n\nexport const conditionalTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...TaskConfigSchema[\"properties\"],\n branches: { type: \"array\", items: {} },\n defaultBranch: { type: \"string\" },\n exclusive: { type: \"boolean\" },\n conditionConfig: { type: \"object\", additionalProperties: true },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type ConditionalTaskConfig = TaskConfig & {\n /** Branches may contain ConditionFn functions — not JSON-schema-representable */\n readonly branches?: BranchConfig<any>[];\n readonly defaultBranch?: string;\n readonly exclusive?: boolean;\n /** Serializable UI condition configuration used to build branches at runtime. */\n readonly conditionConfig?: UIConditionConfig;\n};\n\n/**\n * A task that evaluates conditions to determine which downstream paths are active.\n *\n * Implements conditional branching within a task graph (if/then/else or switch/case).\n * In exclusive mode (default), branches are evaluated in order and only the first\n * match activates. In multi-path mode, all matching branches activate simultaneously.\n * Inactive branches DISABLE their outgoing dataflows, cascading to downstream tasks\n * with no other active inputs.\n */\nexport class ConditionalTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends ConditionalTaskConfig = ConditionalTaskConfig,\n> extends Task<Input, Output, Config> {\n static override type: TaskTypeName = \"ConditionalTask\";\n static override category = \"Flow Control\";\n static override title = \"Condition\";\n static override description = \"Route data based on conditions\";\n static override hasDynamicSchemas: boolean = true;\n\n public static override configSchema(): DataPortSchema {\n return conditionalTaskConfigSchema;\n }\n\n public override canSerializeConfig(): boolean {\n if (!this.config.branches) return true;\n return !this.config.branches.some((b) => typeof b.condition === \"function\");\n }\n\n /**\n * Set of branch IDs that are currently active after execution.\n * Populated during execute() and used by the graph runner to\n * determine which dataflows should be enabled vs disabled.\n */\n public activeBranches: Set<string> = new Set();\n\n // ========================================================================\n // Execution methods\n // ========================================================================\n\n /**\n * Builds runtime branch configs from serialized UI condition config.\n */\n private buildBranchesFromConditionConfig(\n conditionConfig: UIConditionConfig\n ): BranchConfig<Input>[] {\n if (!conditionConfig?.branches || conditionConfig.branches.length === 0) {\n return [\n {\n id: \"default\",\n condition: () => true,\n outputPort: \"1\",\n },\n ];\n }\n\n return conditionConfig.branches.map((branch, index) => ({\n id: branch.id,\n outputPort: String(index + 1),\n condition: (inputData: Input): boolean => {\n const fieldValue = getNestedValue(inputData as Record<string, unknown>, branch.field);\n return evaluateCondition(fieldValue, branch.operator, branch.value);\n },\n }));\n }\n\n /**\n * Resolves the effective branches to evaluate.\n * Uses config.branches if they have condition functions,\n * otherwise falls back to conditionConfig from input or extras.\n */\n private resolveBranches(input: Input): {\n branches: BranchConfig<Input>[];\n isExclusive: boolean;\n defaultBranch: string | undefined;\n fromConditionConfig: boolean;\n } {\n const configBranches = this.config.branches ?? [];\n\n // If config branches have condition functions, use them directly\n if (configBranches.length > 0 && typeof configBranches[0].condition === \"function\") {\n return {\n branches: configBranches,\n isExclusive: this.config.exclusive ?? true,\n defaultBranch: this.config.defaultBranch,\n fromConditionConfig: false,\n };\n }\n\n // Try to find serialized conditionConfig from input or config\n const conditionConfig =\n ((input as Record<string, unknown>).conditionConfig as UIConditionConfig | undefined) ??\n this.config.conditionConfig;\n\n if (conditionConfig) {\n return {\n branches: this.buildBranchesFromConditionConfig(conditionConfig),\n isExclusive: conditionConfig.exclusive ?? true,\n defaultBranch: conditionConfig.defaultBranch,\n fromConditionConfig: true,\n };\n }\n\n // Fallback: use config branches even if they lack conditions\n return {\n branches: configBranches,\n isExclusive: this.config.exclusive ?? true,\n defaultBranch: this.config.defaultBranch,\n fromConditionConfig: false,\n };\n }\n\n public override async execute(\n input: Input,\n context: IExecuteContext\n ): Promise<Output | undefined> {\n if (context.signal?.aborted) {\n return undefined;\n }\n\n // Clear previous branch activation state\n this.activeBranches.clear();\n\n const { branches, isExclusive, defaultBranch, fromConditionConfig } =\n this.resolveBranches(input);\n\n // Evaluate each branch condition\n for (const branch of branches) {\n try {\n const isActive = branch.condition(input);\n if (isActive) {\n this.activeBranches.add(branch.id);\n if (isExclusive) {\n // In exclusive mode, stop at first match\n break;\n }\n }\n } catch (error) {\n // If condition throws, treat it as false (branch not taken)\n getLogger().error(`Condition evaluation failed for branch \"${branch.id}\":`, { error });\n }\n }\n\n // If no branch matched and there's a default, use it\n if (this.activeBranches.size === 0 && defaultBranch) {\n const defaultBranchExists = branches.some((b) => b.id === defaultBranch);\n if (defaultBranchExists) {\n this.activeBranches.add(defaultBranch);\n }\n }\n\n // Build output: if from conditionConfig, use the UI-style output building\n if (fromConditionConfig) {\n return this.buildConditionConfigOutput(input, branches, isExclusive);\n }\n\n // Build output: pass through input to active branch ports\n return this.buildOutput(input);\n }\n\n /**\n * Builds output in the UI-style format where inputs are passed through\n * with numbered suffixes based on matched branches.\n */\n protected buildConditionConfigOutput(\n input: Input,\n branches: BranchConfig<Input>[],\n isExclusive: boolean\n ): Output {\n const output: Record<string, unknown> = {};\n\n // Remove conditionConfig from pass-through data\n const { conditionConfig, ...passThrough } = input as Record<string, unknown>;\n const inputKeys = Object.keys(passThrough);\n\n // Find matched branch number\n let matchedBranchNumber: number | null = null;\n for (let i = 0; i < branches.length; i++) {\n if (this.activeBranches.has(branches[i].id)) {\n if (matchedBranchNumber === null) {\n matchedBranchNumber = i + 1;\n }\n }\n }\n\n if (isExclusive) {\n if (matchedBranchNumber !== null) {\n for (const key of inputKeys) {\n output[`${key}_${matchedBranchNumber}`] = passThrough[key];\n }\n } else {\n for (const key of inputKeys) {\n output[`${key}_else`] = passThrough[key];\n }\n }\n } else {\n for (let i = 0; i < branches.length; i++) {\n if (this.activeBranches.has(branches[i].id)) {\n for (const key of inputKeys) {\n output[`${key}_${i + 1}`] = passThrough[key];\n }\n }\n }\n }\n\n return output as Output;\n }\n\n /**\n * Builds the output object with data routed to active branch ports.\n * Each active branch's output port receives the full input data.\n *\n * @param input - The input data to pass through to active branches\n * @returns Output object with active branch ports populated\n */\n protected buildOutput(input: Input): Output {\n const output: Record<string, unknown> = {\n _activeBranches: Array.from(this.activeBranches),\n };\n\n const branches = this.config.branches ?? [];\n\n // For each active branch, populate its output port with the input data\n for (const branch of branches) {\n if (this.activeBranches.has(branch.id)) {\n // Pass through all input properties to the active branch's output port\n output[branch.outputPort] = { ...input };\n }\n }\n\n return output as Output;\n }\n\n // ========================================================================\n // Branch information methods\n // ========================================================================\n\n public isBranchActive(branchId: string): boolean {\n return this.activeBranches.has(branchId);\n }\n\n /** Returns a copy to prevent external modification. */\n public getActiveBranches(): Set<string> {\n return new Set(this.activeBranches);\n }\n\n public getPortActiveStatus(): Map<string, boolean> {\n const status = new Map<string, boolean>();\n const branches = this.config.branches ?? [];\n\n for (const branch of branches) {\n status.set(branch.outputPort, this.activeBranches.has(branch.id));\n }\n\n return status;\n }\n\n // ========================================================================\n // Schema methods\n // ========================================================================\n\n static override outputSchema(): DataPortSchema {\n // Base schema - actual properties are determined by branch configuration\n return {\n type: \"object\",\n properties: {\n _activeBranches: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"List of active branch IDs after condition evaluation\",\n },\n },\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n }\n\n override outputSchema(): DataPortSchema {\n const branches = this.config?.branches ?? [];\n const properties: Record<string, any> = {\n _activeBranches: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"List of active branch IDs after condition evaluation\",\n },\n };\n\n // Add each branch's output port to the schema\n for (const branch of branches) {\n properties[branch.outputPort] = {\n type: \"object\",\n description: `Output for branch \"${branch.id}\" when active`,\n additionalProperties: true,\n };\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: false,\n } as DataPortSchema;\n }\n\n static override inputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n }\n\n override inputSchema(): DataPortSchema {\n return {\n type: \"object\",\n properties: {},\n additionalProperties: true,\n } as const satisfies DataPortSchema;\n }\n}\n",
|
|
35
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Comparison operators supported by the UI condition builder.\n */\nexport type ComparisonOperator =\n | \"equals\"\n | \"not_equals\"\n | \"greater_than\"\n | \"greater_or_equal\"\n | \"less_than\"\n | \"less_or_equal\"\n | \"contains\"\n | \"starts_with\"\n | \"ends_with\"\n | \"is_empty\"\n | \"is_not_empty\"\n | \"is_true\"\n | \"is_false\";\n\n/**\n * Serialized condition branch configuration from the UI builder.\n * Used by ConditionalTask to auto-build runtime condition functions.\n */\nexport interface UIConditionBranch {\n id: string;\n field: string;\n operator: ComparisonOperator;\n value: string;\n}\n\n/**\n * Serialized condition configuration from the UI builder.\n * Used by ConditionalTask to auto-build runtime branch configs.\n */\nexport interface UIConditionConfig {\n branches: UIConditionBranch[];\n exclusive: boolean;\n defaultBranch?: string;\n}\n\n/**\n * Evaluates a condition based on operator type.\n *\n * @param fieldValue - The value of the field being tested\n * @param operator - The comparison operator to apply\n * @param compareValue - The value to compare against (always a string from the UI)\n * @returns true if the condition is met, false otherwise\n */\nexport function evaluateCondition(\n fieldValue: unknown,\n operator: ComparisonOperator,\n compareValue: string\n): boolean {\n // Handle null/undefined\n if (fieldValue === null || fieldValue === undefined) {\n switch (operator) {\n case \"is_empty\":\n return true;\n case \"is_not_empty\":\n return false;\n case \"is_true\":\n return false;\n case \"is_false\":\n return true;\n default:\n return false;\n }\n }\n\n const strValue = String(fieldValue);\n const numValue = Number(fieldValue);\n\n switch (operator) {\n case \"equals\":\n // Try numeric comparison first, then string\n if (!isNaN(numValue) && !isNaN(Number(compareValue))) {\n return numValue === Number(compareValue);\n }\n return strValue === compareValue;\n\n case \"not_equals\":\n if (!isNaN(numValue) && !isNaN(Number(compareValue))) {\n return numValue !== Number(compareValue);\n }\n return strValue !== compareValue;\n\n case \"greater_than\":\n return numValue > Number(compareValue);\n\n case \"greater_or_equal\":\n return numValue >= Number(compareValue);\n\n case \"less_than\":\n return numValue < Number(compareValue);\n\n case \"less_or_equal\":\n return numValue <= Number(compareValue);\n\n case \"contains\":\n return strValue.toLowerCase().includes(compareValue.toLowerCase());\n\n case \"starts_with\":\n return strValue.toLowerCase().startsWith(compareValue.toLowerCase());\n\n case \"ends_with\":\n return strValue.toLowerCase().endsWith(compareValue.toLowerCase());\n\n case \"is_empty\":\n return strValue === \"\" || (Array.isArray(fieldValue) && fieldValue.length === 0);\n\n case \"is_not_empty\":\n return strValue !== \"\" && !(Array.isArray(fieldValue) && fieldValue.length === 0);\n\n case \"is_true\":\n return Boolean(fieldValue) === true;\n\n case \"is_false\":\n return Boolean(fieldValue) === false;\n\n default:\n return false;\n }\n}\n\n/**\n * Get a value from a nested object using dot notation.\n * e.g., \"user.name\" would get obj.user.name\n *\n * @param obj - The object to read from\n * @param path - Dot-separated path to the value\n * @returns The value at the path, or undefined if any segment is missing\n */\nexport function getNestedValue(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || current === undefined || typeof current !== \"object\") {\n return undefined;\n }\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n",
|
|
36
33
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ResourceScope, ServiceRegistry } from \"@workglow/util\";\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { ITask } from \"../task/ITask\";\nimport type { StreamEvent, StreamMode } from \"../task/StreamTypes\";\nimport { edgeNeedsAccumulation, getOutputStreamMode, getStreamingPorts } from \"../task/StreamTypes\";\nimport type { TaskInput } from \"../task/TaskTypes\";\nimport { TaskStatus } from \"../task/TaskTypes\";\nimport { Dataflow, DATAFLOW_ALL_PORTS } from \"./Dataflow\";\nimport type { EdgeMaterializer } from \"./EdgeMaterializer\";\nimport type { RunContext } from \"./RunContext\";\nimport type { RunScheduler } from \"./RunScheduler\";\nimport type { TaskGraph } from \"./TaskGraph\";\nimport type { GraphSingleTaskResult } from \"./TaskGraphRunner\";\nimport type { ITaskGraphScheduler } from \"./TaskGraphScheduler\";\n\n/**\n * Per-call run-state inputs shared between {@link StreamPump.runStreamingTask}\n * and the helpers it calls. Keeps StreamPump stateless beyond `graph`,\n * `processScheduler`, and `edgeMaterializer` so the facade's mutable per-run\n * state (`registry`, `outputCache`, `resourceScope`, `accumulateLeafOutputs`)\n * is read at call time rather than captured at construction.\n *\n * @internal\n */\nexport interface StreamingRunOptions {\n readonly registry: ServiceRegistry;\n readonly outputCache: TaskOutputRepository | undefined;\n readonly resourceScope: ResourceScope | undefined;\n readonly accumulateLeafOutputs: boolean;\n readonly updateProgress: (\n task: ITask,\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ) => Promise<void>;\n /** Stable identifier for the current graph run; threaded into each task's IRunConfig. */\n readonly runId?: string;\n /**\n * True when the caller explicitly disabled caching (outputCache: false). When\n * set, `false` is passed to task.runner.run() so TaskRunner clears any stale\n * cacheRegistry rather than falling through to CACHE_REGISTRY resolution.\n */\n readonly legacyCacheExplicitlyDisabled?: boolean;\n}\n\n/**\n * @internal\n * Streaming bridge. Awaits upstream streaming inputs, runs streaming tasks,\n * tees stream events to downstream edges, decides accumulation policy.\n *\n * `awaitStreamInputs` and `runStreamingTask` take per-call run-state as\n * arguments rather than holding references, because the facade's per-run\n * state (`registry`, `outputCache`, `resourceScope`, `accumulateLeafOutputs`)\n * is mutable and may be reassigned between runs. Method-arg injection lets the\n * facade pass the current values at call time.\n *\n * The {@link RunScheduler} back-reference is wired post-construction via\n * {@link setRunScheduler} to break the StreamPump <-> RunScheduler import\n * cycle (StreamPump calls RunScheduler for status pushes; RunScheduler\n * dispatches into StreamPump indirectly via facade.runTask).\n */\nexport class StreamPump {\n // Set after construction (mutual reference) — see setRunScheduler.\n private runScheduler!: RunScheduler;\n\n constructor(\n private readonly graph: TaskGraph,\n private readonly processScheduler: ITaskGraphScheduler,\n private readonly edgeMaterializer: EdgeMaterializer\n ) {}\n\n /**\n * Wires the {@link RunScheduler} back-reference. Must be called once after\n * construction, before any call to {@link runStreamingTask}.\n */\n setRunScheduler(rs: RunScheduler): void {\n this.runScheduler = rs;\n }\n\n /**\n * Tees streaming inputs for a streamable task — one copy goes to the task's\n * executeStream() (via inputStreams), one stays on the edge for materialization\n * by awaitStreamInputs.\n */\n prepareStreamingInputs(task: ITask): void {\n const dataflows = this.graph.getSourceDataflows(task.id);\n const streamingEdges = dataflows.filter((df) => df.stream !== undefined);\n if (streamingEdges.length === 0) return;\n const inputStreams = new Map<string, ReadableStream<StreamEvent>>();\n for (const df of streamingEdges) {\n const stream = df.stream!;\n const [forwardCopy, materializeCopy] = stream.tee();\n inputStreams.set(df.targetTaskPortId, forwardCopy);\n df.setStream(materializeCopy);\n }\n task.runner.inputStreams = inputStreams;\n }\n\n /**\n * For non-streaming downstream tasks, awaits completion of any active\n * streams on input dataflow edges, materializing their values.\n *\n * Streaming upstream tasks set a ReadableStream on outgoing edges.\n * Non-streaming downstream tasks cannot consume streams directly, so\n * this method reads each stream to completion and accumulates the\n * value (via Dataflow.awaitStreamValue) before the task reads its\n * inputs through the normal getPortData() path.\n */\n async awaitStreamInputs(task: ITask, registry: ServiceRegistry): Promise<void> {\n const dataflows = this.graph.getSourceDataflows(task.id);\n const streamingDataflows = dataflows.filter((df) => df.stream !== undefined);\n if (streamingDataflows.length === 0) return;\n await Promise.all(\n streamingDataflows.map(async (df) => {\n await df.awaitStreamValue();\n // awaitStreamValue sets port data from the raw finish/snapshot event.\n // Apply the edge's transform chain over the materialised value so the\n // downstream task receives the transformed result. This is the sole\n // transform application for streaming edges (pushOutputFromNodeToEdges\n // deliberately skips them to avoid double-apply).\n await df.applyTransforms(registry);\n })\n );\n }\n\n /**\n * Runs a streaming task within the DAG.\n * Listens for stream events to:\n * - Notify the scheduler when streaming begins (unblocking downstream streamable tasks)\n * - Push stream data to outgoing dataflow edges\n * - Have the source task accumulate and emit enriched finish events for\n * non-streaming downstream tasks (when taskNeedsAccumulation() is true)\n */\n async runStreamingTask<T>(\n task: ITask,\n input: TaskInput,\n ctx: RunContext,\n options: StreamingRunOptions\n ): Promise<GraphSingleTaskResult<T>> {\n if (!this.runScheduler) {\n throw new Error(\n \"StreamPump.runStreamingTask called before setRunScheduler — facade construction is incomplete.\"\n );\n }\n const streamMode = getOutputStreamMode(task.outputSchema());\n const shouldAccumulate = this.taskNeedsAccumulation(\n task,\n options.outputCache,\n options.accumulateLeafOutputs\n );\n\n let streamingNotified = false;\n\n const onStatus = (status: TaskStatus) => {\n if (status === TaskStatus.STREAMING && !streamingNotified) {\n streamingNotified = true;\n this.runScheduler.pushStatusFromNodeToEdges(task, ctx, TaskStatus.STREAMING);\n this.pushStreamToEdges(task, streamMode);\n this.processScheduler.onTaskStreaming(task.id);\n }\n };\n\n const onStreamStart = () => {\n this.graph.emit(\"task_stream_start\", task.id);\n };\n\n const onStreamChunk = (event: StreamEvent) => {\n this.graph.emit(\"task_stream_chunk\", task.id, event);\n };\n\n const onStreamEnd = (output: Record<string, any>) => {\n this.graph.emit(\"task_stream_end\", task.id, output);\n };\n\n task.on(\"status\", onStatus);\n task.on(\"stream_start\", onStreamStart);\n task.on(\"stream_chunk\", onStreamChunk);\n task.on(\"stream_end\", onStreamEnd);\n\n try {\n const results = await task.runner.run(input, {\n // Pass false when explicitly disabled so TaskRunner clears stale state;\n // otherwise pass the legacy repo (or undefined to use CACHE_REGISTRY).\n outputCache: options.legacyCacheExplicitlyDisabled ? false : options.outputCache,\n shouldAccumulate,\n updateProgress: options.updateProgress,\n registry: options.registry,\n resourceScope: options.resourceScope,\n runId: options.runId,\n });\n\n await this.edgeMaterializer.pushOutputFromNodeToEdges(task, results);\n\n return {\n id: task.id,\n type: (task.constructor as any).runtype || (task.constructor as any).type,\n data: results as T,\n };\n } finally {\n task.off(\"status\", onStatus);\n task.off(\"stream_start\", onStreamStart);\n task.off(\"stream_chunk\", onStreamChunk);\n task.off(\"stream_end\", onStreamEnd);\n }\n }\n\n /**\n * Determines whether a streaming task needs to accumulate its text-delta\n * chunks into an enriched finish event. Accumulation is needed when:\n *\n * 1. Output caching is active (the cached value must be fully materialised).\n * 2. Any outgoing dataflow edge connects a streaming output port to an input\n * port that is not streaming with the same mode (i.e. the downstream task\n * cannot consume a raw stream and needs a completed value).\n *\n * When accumulation is required the source task runs with shouldAccumulate=true,\n * emitting an enriched finish event that carries all accumulated port text.\n * All downstream dataflow edges share that event via tee'd streams so no\n * edge needs to re-accumulate independently.\n */\n private taskNeedsAccumulation(\n task: ITask,\n outputCache: TaskOutputRepository | undefined,\n accumulateLeafOutputs: boolean\n ): boolean {\n if (outputCache) return true;\n\n const outEdges = this.graph.getTargetDataflows(task.id);\n if (outEdges.length === 0) return accumulateLeafOutputs;\n\n const outSchema = task.outputSchema();\n\n for (const df of outEdges) {\n if (df.sourceTaskPortId === DATAFLOW_ALL_PORTS) {\n // Conservative: if any streaming output port exists, accumulate.\n // This covers the case where all-ports edges fan into non-streaming tasks.\n if (getStreamingPorts(outSchema).length > 0) return true;\n continue;\n }\n\n const targetTask = this.graph.getTask(df.targetTaskId);\n if (!targetTask) continue;\n const inSchema = targetTask.inputSchema();\n\n if (edgeNeedsAccumulation(outSchema, df.sourceTaskPortId, inSchema, df.targetTaskPortId)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if an event carries a port-specific delta (text-delta or object-delta).\n */\n private static isPortDelta(event: StreamEvent): event is StreamEvent & { port: string } {\n return event.type === \"text-delta\" || event.type === \"object-delta\";\n }\n\n /**\n * Creates a ReadableStream from task streaming events, optionally filtered\n * to a single port. When `portId` is undefined (DATAFLOW_ALL_PORTS), all\n * events pass through. When set, only delta events matching the port plus\n * control events (finish, error, snapshot) are enqueued.\n *\n * Also taps snapshot events to write per-port data into each edge's\n * `latestSnapshot` slot for downstream peek-during-streaming.\n */\n private createStreamFromTaskEvents(\n task: ITask,\n portId: string | undefined,\n edgesForGroup: ReadonlyArray<Dataflow>\n ): ReadableStream<StreamEvent> {\n return new ReadableStream<StreamEvent>({\n start: (controller) => {\n const onChunk = (event: StreamEvent) => {\n try {\n if (portId !== undefined && StreamPump.isPortDelta(event) && event.port !== portId) {\n return;\n }\n // Tap: on snapshot events, write per-port data into each edge's\n // latestSnapshot slot.\n if (event.type === \"snapshot\") {\n const data = event.data as Record<string, unknown> | undefined;\n if (data) {\n for (const edge of edgesForGroup) {\n const portValue =\n edge.sourceTaskPortId === DATAFLOW_ALL_PORTS\n ? data\n : data[edge.sourceTaskPortId];\n edge.latestSnapshot = portValue;\n }\n }\n }\n controller.enqueue(event);\n } catch {\n // Stream may be closed\n }\n };\n const onEnd = () => {\n try {\n controller.close();\n } catch {\n // Stream may already be closed\n }\n task.off(\"stream_chunk\", onChunk);\n task.off(\"stream_end\", onEnd);\n };\n task.on(\"stream_chunk\", onChunk);\n task.on(\"stream_end\", onEnd);\n },\n });\n }\n\n /**\n * Pushes stream events from a streaming task to its outgoing dataflow edges.\n * Creates per-port filtered ReadableStreams for specific-port edges and\n * unfiltered streams for DATAFLOW_ALL_PORTS edges. Within each port group,\n * uses tee() for fan-out to multiple consumers.\n */\n private pushStreamToEdges(task: ITask, _streamMode: StreamMode): void {\n const targetDataflows = this.graph.getTargetDataflows(task.id);\n if (targetDataflows.length === 0) return;\n\n // Group edges by their source port\n const groups = new Map<string, typeof targetDataflows>();\n for (const df of targetDataflows) {\n const key = df.sourceTaskPortId;\n let group = groups.get(key);\n if (!group) {\n group = [];\n groups.set(key, group);\n }\n group.push(df);\n }\n\n for (const [portKey, edges] of groups) {\n const filterPort = portKey === DATAFLOW_ALL_PORTS ? undefined : portKey;\n const stream = this.createStreamFromTaskEvents(task, filterPort, edges);\n\n if (edges.length === 1) {\n edges[0].setStream(stream);\n } else {\n let currentStream = stream;\n for (let i = 0; i < edges.length; i++) {\n if (i === edges.length - 1) {\n edges[i].setStream(currentStream);\n } else {\n const [s1, s2] = currentStream.tee();\n edges[i].setStream(s1);\n currentStream = s2;\n }\n }\n }\n }\n }\n}\n",
|
|
37
34
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { ITask } from \"../task/ITask\";\nimport { getPortStreamMode } from \"../task/StreamTypes\";\nimport { TaskStatus } from \"../task/TaskTypes\";\nimport { TaskGraph } from \"./TaskGraph\";\n\n/**\n * Interface for task graph schedulers\n */\nexport interface ITaskGraphScheduler {\n /**\n * Gets an async iterator of tasks that can be executed\n * @returns AsyncIterator of tasks that resolves to each task when it's ready\n */\n tasks(): AsyncIterableIterator<ITask>;\n\n /**\n * Notifies the scheduler that a task has completed\n * @param taskId The ID of the completed task\n */\n onTaskCompleted(taskId: unknown): void;\n\n /**\n * Notifies the scheduler that a task has begun streaming output.\n * Streaming tasks may unblock downstream streamable tasks early.\n * @param taskId The ID of the streaming task\n */\n onTaskStreaming(taskId: unknown): void;\n\n /**\n * Resets the scheduler state\n */\n reset(): void;\n}\n\n/**\n * Sequential scheduler that executes one task at a time in topological order\n * Useful for debugging and understanding task execution flow\n */\nexport class TopologicalScheduler implements ITaskGraphScheduler {\n private sortedNodes: ITask[];\n private currentIndex: number;\n\n constructor(private dag: TaskGraph) {\n this.sortedNodes = [];\n this.currentIndex = 0;\n this.reset();\n }\n\n async *tasks(): AsyncIterableIterator<ITask> {\n while (this.currentIndex < this.sortedNodes.length) {\n yield this.sortedNodes[this.currentIndex++];\n }\n }\n\n onTaskCompleted(_taskId: unknown): void {\n // Topological scheduler doesn't need to track individual task completion\n }\n\n onTaskStreaming(_taskId: unknown): void {\n // Topological scheduler doesn't support streaming-aware scheduling\n }\n\n reset(): void {\n this.sortedNodes = this.dag.topologicallySortedNodes();\n this.currentIndex = 0;\n }\n}\n\n/**\n * Event-driven scheduler that executes tasks as soon as their dependencies are satisfied\n * Most efficient for parallel execution but requires completion notifications\n */\nexport class DependencyBasedScheduler implements ITaskGraphScheduler {\n private completedTasks: Set<unknown>;\n private streamingTasks: Set<unknown>;\n private pendingTasks: Set<ITask>;\n private nextResolver: ((task: ITask | null) => void) | null = null;\n\n constructor(private dag: TaskGraph) {\n this.completedTasks = new Set();\n this.streamingTasks = new Set();\n this.pendingTasks = new Set();\n this.reset();\n }\n\n private isTaskReady(task: ITask): boolean {\n // DISABLED tasks are never ready - they should be skipped\n if (task.status === TaskStatus.DISABLED) {\n return false;\n }\n\n const sourceDataflows = this.dag.getSourceDataflows(task.id);\n\n // If task has incoming dataflows, check if all are DISABLED\n // (In that case, task will be disabled by propagateDisabledStatus, not ready to run)\n if (sourceDataflows.length > 0) {\n const allIncomingDisabled = sourceDataflows.every((df) => df.status === TaskStatus.DISABLED);\n if (allIncomingDisabled) {\n return false;\n }\n }\n\n // A task is ready if all its non-disabled dependencies are completed.\n // DISABLED dataflows are considered \"satisfied\" (their branch was not taken).\n //\n // Per-edge streaming: when the source output port AND the target input port\n // both declare matching `x-stream`, the dependency can be satisfied by\n // STREAMING status (not just COMPLETED). Edges where the target port does\n // NOT accept streams still require full completion.\n const activeDataflows = sourceDataflows.filter((df) => df.status !== TaskStatus.DISABLED);\n\n return activeDataflows.every((df) => {\n const depId = df.sourceTaskId;\n if (this.completedTasks.has(depId)) return true;\n\n // Check if this specific edge supports stream pass-through\n if (this.streamingTasks.has(depId)) {\n const sourceTask = this.dag.getTask(depId);\n if (sourceTask) {\n const sourceMode = getPortStreamMode(sourceTask.outputSchema(), df.sourceTaskPortId);\n const targetMode = getPortStreamMode(task.inputSchema(), df.targetTaskPortId);\n if (sourceMode !== \"none\" && sourceMode === targetMode) {\n return true;\n }\n }\n }\n\n return false;\n });\n }\n\n private async waitForNextTask(): Promise<ITask | null> {\n if (this.pendingTasks.size === 0) return null;\n\n // Remove any disabled tasks from pending (they were disabled by propagateDisabledStatus)\n for (const task of Array.from(this.pendingTasks)) {\n if (task.status === TaskStatus.DISABLED) {\n this.pendingTasks.delete(task);\n }\n }\n\n if (this.pendingTasks.size === 0) return null;\n\n const readyTask = Array.from(this.pendingTasks).find((task) => this.isTaskReady(task));\n if (readyTask) {\n this.pendingTasks.delete(readyTask);\n return readyTask;\n }\n\n // If there are pending tasks but none are ready, wait for task completion\n if (this.pendingTasks.size > 0) {\n return new Promise((resolve) => {\n this.nextResolver = resolve;\n });\n }\n\n return null;\n }\n\n async *tasks(): AsyncIterableIterator<ITask> {\n while (this.pendingTasks.size > 0) {\n const task = await this.waitForNextTask();\n if (task) {\n yield task;\n } else {\n break;\n }\n }\n }\n\n onTaskCompleted(taskId: unknown): void {\n this.completedTasks.add(taskId);\n\n // Remove any disabled tasks from pending\n for (const task of Array.from(this.pendingTasks)) {\n if (task.status === TaskStatus.DISABLED) {\n this.pendingTasks.delete(task);\n }\n }\n\n // Check if any pending tasks are now ready\n if (this.nextResolver) {\n const readyTask = Array.from(this.pendingTasks).find((task) => this.isTaskReady(task));\n if (readyTask) {\n this.pendingTasks.delete(readyTask);\n const resolver = this.nextResolver;\n this.nextResolver = null;\n resolver(readyTask);\n } else if (this.pendingTasks.size === 0) {\n // No more pending tasks - resolve with null to signal completion\n const resolver = this.nextResolver;\n this.nextResolver = null;\n resolver(null);\n }\n }\n }\n\n onTaskStreaming(taskId: unknown): void {\n this.streamingTasks.add(taskId);\n\n // Remove any disabled tasks from pending\n for (const task of Array.from(this.pendingTasks)) {\n if (task.status === TaskStatus.DISABLED) {\n this.pendingTasks.delete(task);\n }\n }\n\n // Check if any pending streamable tasks are now ready\n // (they can start when deps are STREAMING, not just COMPLETED)\n if (this.nextResolver) {\n const readyTask = Array.from(this.pendingTasks).find((task) => this.isTaskReady(task));\n if (readyTask) {\n this.pendingTasks.delete(readyTask);\n const resolver = this.nextResolver;\n this.nextResolver = null;\n resolver(readyTask);\n }\n }\n }\n\n reset(): void {\n this.completedTasks.clear();\n this.streamingTasks.clear();\n this.pendingTasks = new Set(this.dag.topologicallySortedNodes());\n this.nextResolver = null;\n }\n}\n",
|
|
38
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GraphResultArray } from \"../task-graph/TaskGraphRunner\";\nimport type { GraphAsTaskConfig } from \"./GraphAsTask\";\nimport { GraphAsTask } from \"./GraphAsTask\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport { TaskRunner } from \"./TaskRunner\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\n\nexport class GraphAsTaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends GraphAsTaskConfig<Input> = GraphAsTaskConfig<Input>,\n> extends TaskRunner<Input, Output, Config> {\n declare task: GraphAsTask<Input, Output, Config>;\n\n /**\n * Protected method to execute a task subgraph by delegating back to the task itself.\n */\n protected async executeTaskChildren(input: Input): Promise<GraphResultArray<Output>> {\n // Route inner graph_progress through handleProgress so the outer graph's\n // updateProgress callback fires (updating task.progress and re-emitting\n // graph_progress up the chain). A bare emit on the task was silently\n // dropped by the outer TaskGraphRunner, leaving parent progress stuck at\n // the value from whichever task ran before this one. Mirrors the pattern\n // used by FallbackTaskRunner, IteratorTaskRunner, and WhileTask.\n const unsubscribe = this.task.subGraph!.subscribe(\n \"graph_progress\",\n (progress: number | undefined, message?: string, ...args: any[]) => {\n void this.handleProgress(progress, message, ...args);\n }\n );\n const results = await this.task.subGraph!.run<Output>(input, {\n parentSignal: this.currentCtx?.abortController.signal,\n outputCache: this.outputCache,\n registry: this.registry,\n resourceScope: this.resourceScope,\n });\n unsubscribe();\n return results;\n }\n /**\n * Protected method for preview execution delegation\n *\n * For GraphAsTask, we pass the parent's runInputData to the subgraph's runPreview.\n * This ensures that root tasks in the subgraph (like InputTask) receive the\n * parent's input values after resetInputData() is called.\n */\n protected async executeTaskChildrenPreview(): Promise<GraphResultArray<Output>> {\n return this.task.subGraph!.runPreview<Output>(this.task.runInputData, {\n registry: this.registry,\n resourceScope: this.resourceScope,\n });\n }\n\n protected override async handleDisable(ctx: TaskRunContext | undefined): Promise<void> {\n if (this.task.hasChildren()) {\n await this.task.subGraph!.disable();\n }\n await super.handleDisable(ctx);\n }\n\n // ========================================================================\n // TaskRunner method overrides and helpers\n // ========================================================================\n\n /**\n * Execute the task\n */\n protected override async executeTask(\n input: Input,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (this.task.hasChildren()) {\n const runExecuteOutputData = await this.executeTaskChildren(input);\n this.task.runOutputData = this.task.subGraph.mergeExecuteOutputsToRunOutput(\n runExecuteOutputData,\n this.task.compoundMerge\n );\n } else {\n const result = await super.executeTask(input, ctx);\n this.task.runOutputData = result ?? ({} as Output);\n }\n return this.task.runOutputData as Output;\n }\n\n /**\n * Execute the task in preview mode\n */\n public override async executeTaskPreview(\n input: Input,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (this.task.hasChildren()) {\n const previewResults = await this.executeTaskChildrenPreview();\n this.task.runOutputData = this.task.subGraph.mergeExecuteOutputsToRunOutput(\n previewResults,\n this.task.compoundMerge\n );\n return this.task.runOutputData as Output;\n } else {\n const previewResult = await super.executeTaskPreview(input, ctx);\n if (previewResult !== undefined) {\n this.task.runOutputData = previewResult;\n }\n return this.task.runOutputData as Output;\n }\n }\n}\n",
|
|
39
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport
|
|
40
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {
|
|
35
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n getLogger,\n getTelemetryProvider,\n globalServiceRegistry,\n ResourceScope,\n ServiceRegistry,\n SpanStatusCode,\n} from \"@workglow/util\";\nimport type { CacheRegistry } from \"../cache\";\nimport { CACHE_REGISTRY, DefaultCacheRegistry, RunPrivateCacheRepo } from \"../cache\";\nimport { TASK_OUTPUT_REPOSITORY, TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { Taskish } from \"../task-graph/Conversions\";\nimport { ensureTask } from \"../task-graph/Conversions\";\nimport { CacheCoordinator } from \"./CacheCoordinator\";\nimport { resolveSchemaInputs, schemaHasFormatAnnotations } from \"./InputResolver\";\nimport type { IRunConfig, ITask } from \"./ITask\";\nimport { ITaskRunner } from \"./ITaskRunner\";\nimport { StreamProcessor } from \"./StreamProcessor\";\nimport type { StreamEvent } from \"./StreamTypes\";\nimport { getOutputStreamMode, isTaskStreamable } from \"./StreamTypes\";\nimport { Task } from \"./Task\";\nimport {\n TaskAbortedError,\n TaskConfigurationError,\n TaskError,\n TaskFailedError,\n TaskInvalidInputError,\n TaskTimeoutError,\n} from \"./TaskError\";\nimport { TaskRunContext } from \"./TaskRunContext\";\nimport { TaskConfig, TaskInput, TaskOutput, TaskStatus } from \"./TaskTypes\";\n\n/**\n * Type guard that checks whether a value is an ITask-like object with a mutable `runConfig`.\n */\nfunction hasRunConfig(i: unknown): i is { runConfig: Partial<IRunConfig> } {\n return i !== null && typeof i === \"object\" && \"runConfig\" in (i as object);\n}\n\n/**\n * Responsible for running tasks\n * Manages the execution lifecycle of individual tasks\n */\nexport class TaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends TaskConfig = TaskConfig,\n> implements ITaskRunner<Input, Output, Config> {\n protected running = false;\n protected previewRunning = false;\n\n public readonly task: ITask<Input, Output, Config>;\n\n /**\n * Per-run state. Set by handleStart, cleared by handleComplete / handleError /\n * handleAbort / handleDisable. The only mutable per-run state on the facade —\n * exists so the public abort() and disable() methods (which take no arguments)\n * have something to act on.\n */\n protected currentCtx?: TaskRunContext;\n\n /**\n * Output cache repository resolved per-run. Set when the caller passes\n * `outputCache: repo | true` through IRunConfig; the {@link cacheRegistry}\n * deterministic slot is synthesized from it. When `outputCache` is absent\n * and a CACHE_REGISTRY is registered, that is used instead.\n */\n protected outputCache?: TaskOutputRepository;\n\n /**\n * Per-run cache registry resolved in handleStart. Replaces the legacy\n * single-repo `outputCache` field as the primary cache routing mechanism.\n * Set from CACHE_REGISTRY in the ServiceRegistry, or synthesised from the\n * legacy `config.outputCache` repo shim.\n */\n protected cacheRegistry?: CacheRegistry;\n\n /**\n * Cache coordinator for the task (key normalization, lookup, save).\n */\n protected readonly cacheCoordinator: CacheCoordinator<Input, Output>;\n\n /**\n * Stream processor for the task (handles executeStream() event loop).\n */\n protected readonly streamProcessor: StreamProcessor<Input, Output>;\n\n protected registry: ServiceRegistry = globalServiceRegistry;\n\n protected resourceScope?: ResourceScope;\n\n /**\n * True when `this.resourceScope` was auto-created by `run()` (caller did not\n * pass one in `config`). The flag is used by `own()` so that an auto-owned\n * scope is not stamped into a child task's long-lived `runConfig` — that\n * stamp would survive past the parent run's `finally`-block disposal and\n * leave the child holding a reference to a disposed scope.\n */\n protected ownsResourceScope = false;\n\n /**\n * Input streams for pass-through streaming tasks.\n * Set by the graph runner before executing a streaming task that has\n * upstream streaming edges. Keyed by input port name.\n */\n public inputStreams?: Map<string, ReadableStream<StreamEvent>>;\n\n /**\n * Stable identifier for the current graph run. Set from IRunConfig.runId by\n * handleStart; threaded into IExecuteContext so tasks can correlate their\n * work to the enclosing run.\n */\n protected runId?: string;\n\n /**\n * Tracks task types that have already received the \"private policy without\n * runId\" downgrade warning, so the warning fires only once per task type\n * across the process lifetime. Mirrors {@link Task.__cacheableDeprecationWarned}.\n */\n private static __privateWithoutRunIdWarned = new Set<string>();\n\n constructor(task: ITask<Input, Output, Config>) {\n this.task = task;\n this.own = this.own.bind(this);\n this.handleProgress = this.handleProgress.bind(this);\n this.cacheCoordinator = new CacheCoordinator(task);\n this.streamProcessor = new StreamProcessor(task);\n }\n\n // ========================================================================\n // Public methods\n // ========================================================================\n\n async run(overrides: Partial<Input> = {}, config: IRunConfig = {}): Promise<Output> {\n // Reject concurrent run() on the same TaskRunner. Mirrors\n // TaskGraphRunner.handleStart's \"Graph is already running\" check.\n // Raised before any `this.*` mutation so the in-flight run is undisturbed.\n if (this.task.status === TaskStatus.PROCESSING) {\n throw new TaskConfigurationError(\n `Task \"${this.task.type}\" is already running. Concurrent run() calls on the same TaskRunner are not supported.`\n );\n }\n\n const ownsScope = config.resourceScope === undefined;\n const effectiveConfig: IRunConfig = ownsScope\n ? { ...config, resourceScope: new ResourceScope({ strategy: config.disposeStrategy }) }\n : config;\n this.ownsResourceScope = ownsScope;\n\n // ctx is threaded through locals from here; nothing inside run() re-reads\n // this.currentCtx (which can be nulled by handleAbort firing on the abort\n // listener during an interleaved abort). Declared outside the try so the\n // finally block can run scope cleanup even if handleStart itself throws.\n let ctx: TaskRunContext | undefined;\n try {\n ctx = await this.handleStart(effectiveConfig);\n\n const proto = Object.getPrototypeOf(this.task);\n if (\n proto.execute === Task.prototype.execute &&\n typeof proto.executeStream !== \"function\" &&\n proto.executePreview !== Task.prototype.executePreview\n ) {\n throw new TaskConfigurationError(\n `Task \"${this.task.type}\" implements only executePreview() and cannot be run via run(). ` +\n `After the run/runPreview split, run() requires execute() (or executeStream()). ` +\n `See docs/technical/02-dual-mode-execution.md.`\n );\n }\n\n try {\n this.task.setInput(overrides);\n\n await this.resolveSchemas();\n\n const inputs: Input = this.task.runInputData as Input;\n const isValid = await this.task.validateInput(inputs);\n if (!isValid) {\n throw new TaskInvalidInputError(\"Invalid input data\");\n }\n\n if (ctx.abortController.signal.aborted) {\n await this.handleAbort(ctx);\n throw new TaskAbortedError(\"Promise for task created and aborted before run\");\n }\n\n const isStreamable = isTaskStreamable(this.task);\n\n // Warn if schema declares streaming but executeStream is not implemented\n if (!isStreamable && typeof this.task.executeStream !== \"function\") {\n const streamMode = getOutputStreamMode(this.task.outputSchema());\n if (streamMode !== \"none\") {\n getLogger().warn(\n `Task \"${this.task.type}\" declares streaming output (x-stream: \"${streamMode}\") ` +\n `but does not implement executeStream(). Falling back to non-streaming execute().`\n );\n }\n }\n\n let policy = this.task.getCachePolicy(inputs);\n\n // Standalone TaskRunner cannot namespace private cache writes without a\n // runId — TaskGraphRunner owns the wrap. If a standalone caller routes\n // to the private slot with no runId, downgrade to `kind: \"none\"` so the\n // task does not write directly into the shared private repo (which\n // would collide across callers). Warn once per task type so the\n // configuration mistake surfaces without flooding the log.\n if (\n policy.kind === \"private\" &&\n !this.runId &&\n this.cacheRegistry?.private !== undefined &&\n !(this.cacheRegistry.private instanceof RunPrivateCacheRepo)\n ) {\n const taskType = this.task.type;\n if (!TaskRunner.__privateWithoutRunIdWarned.has(taskType)) {\n TaskRunner.__privateWithoutRunIdWarned.add(taskType);\n getLogger().warn(\n `TaskRunner: task \"${taskType}\" has a private cache policy but no runId was ` +\n `provided. Private cache writes are skipped for this run — use TaskGraphRunner ` +\n `with runId for run-namespaced private caching, or provide an already namespaced ` +\n `private cache repo in CACHE_REGISTRY.`\n );\n }\n policy = { kind: \"none\" };\n }\n\n ctx.telemetrySpan?.setAttributes({\n \"workglow.task.cache_policy\": policy.kind,\n });\n\n const keyInputs = await this.cacheCoordinator.buildKeyForPolicy(\n inputs,\n this.cacheRegistry,\n policy\n );\n let outputs = await this.cacheCoordinator.lookupByPolicy(\n keyInputs,\n this.cacheRegistry,\n policy,\n isStreamable,\n ctx\n );\n\n if (outputs === undefined) {\n outputs = isStreamable\n ? await this.streamProcessor.run(inputs, ctx, {\n registry: this.registry,\n resourceScope: this.resourceScope,\n inputStreams: this.inputStreams,\n onProgress: this.handleProgress.bind(this),\n own: this.own,\n })\n : await this.executeTask(inputs, ctx);\n\n await this.cacheCoordinator.saveByPolicy(\n keyInputs,\n outputs as Output,\n this.cacheRegistry,\n policy\n );\n this.task.runOutputData = outputs ?? ({} as Output);\n }\n\n await this.handleComplete(ctx);\n\n return this.task.runOutputData as Output;\n } catch (err: any) {\n await this.handleError(err, ctx);\n // If a timeout triggered the abort, throw the TaskTimeoutError instead\n // of the generic TaskAbortedError that the task's execute() may have thrown.\n throw this.task.error instanceof TaskTimeoutError ? this.task.error : err;\n }\n } catch (err: any) {\n // Reachable when handleStart() throws before assigning `ctx` (e.g.,\n // resourceScope.runStart or telemetry init blows up). Without this,\n // task.status would be stuck at PROCESSING with currentCtx still set\n // and no error/event ever emitted.\n if (ctx === undefined) {\n const partial = this.currentCtx;\n if (partial) {\n await this.handleError(err, partial);\n } else {\n this.task.status = TaskStatus.FAILED;\n this.task.error =\n err instanceof TaskError\n ? err\n : new TaskFailedError(\n `Task \"${this.task.type}\" (${this.task.id}): ${err?.message || \"Task failed\"}`\n );\n if (this.task.error instanceof TaskError) {\n this.task.error.taskType ??= this.task.type;\n this.task.error.taskId ??= this.task.id;\n }\n this.task.emit(\"error\", this.task.error);\n this.task.emit(\"status\", this.task.status);\n }\n this.running = false;\n }\n throw err;\n } finally {\n if (ownsScope) {\n await effectiveConfig.resourceScope!.runComplete();\n this.resourceScope = undefined;\n }\n this.ownsResourceScope = false;\n }\n }\n\n public async runPreview(overrides: Partial<Input> = {}): Promise<Output> {\n if (this.task.status === TaskStatus.PROCESSING) {\n return this.task.runOutputData as Output;\n }\n\n this.task.setInput(overrides);\n\n await this.resolveSchemas();\n\n await this.handleStartPreview();\n\n // Build a transient context for preview overrides — preview doesn't share the\n // full lifecycle but executeTaskPreview's signature requires a ctx.\n const ctx = new TaskRunContext();\n\n try {\n const inputs: Input = this.task.runInputData as Input;\n const isValid = await this.task.validateInput(inputs);\n if (!isValid) {\n throw new TaskInvalidInputError(\"Invalid input data\");\n }\n\n const resultPreview = await this.executeTaskPreview(inputs, ctx);\n if (resultPreview !== undefined) {\n this.task.runOutputData = resultPreview;\n }\n\n await this.handleCompletePreview();\n } catch (err: any) {\n getLogger().debug(\"runPreview failed\", { taskId: this.task.config?.id, error: err });\n await this.handleErrorPreview();\n } finally {\n ctx.dispose();\n return this.task.runOutputData as Output;\n }\n }\n\n /**\n * Async iterator producing preview outputs as upstream tasks stream\n * snapshots. Yields once immediately with the current preview state, then\n * yields again whenever upstream snapshots have arrived since the last\n * yield, until all relevant upstream streams complete (or the consumer\n * breaks out of the loop).\n *\n * Backpressure is single-buffered and last-write-wins: snapshots arriving\n * while a runPreview() iteration is in flight all overwrite runInputData,\n * and the next iteration sees only the latest value. Consumers that need\n * to observe every intermediate snapshot must pace the producer (e.g.,\n * wait for each yield to be processed before emitting the next). This\n * matches live-preview UI semantics — show the latest, drop stale frames.\n *\n * Reuses runPreview() under the hood. Errors during a single iteration\n * are caught and skipped — the iterator never throws to the consumer\n * mid-loop.\n *\n * Watches direct upstream tasks only. Indirect (grandparent) snapshots\n * propagate through chained preview re-runs as upstream parents' values\n * update.\n */\n public async *runPreviewStream(overrides: Partial<Input> = {}): AsyncIterable<Output> {\n // 1. Identify direct upstream tasks and their connecting dataflows.\n // runPreviewStream calls task.runPreview() directly (not the graph\n // runner's runPreview), so it does not benefit from the graph-runner's\n // copyInputFromEdgesToNode pull. We propagate snapshot values into the\n // target task's runInputData ourselves, mirroring that pull but driven\n // by upstream stream events.\n const graph = this.task.parentGraph;\n type DataflowInfo = { upstream: ITask; sourcePort: string; targetPort: string };\n const dataflowInfos: DataflowInfo[] = [];\n if (graph) {\n for (const df of graph.getSourceDataflows(this.task.id)) {\n const upstream = graph.getTask(df.sourceTaskId);\n if (upstream) {\n dataflowInfos.push({\n upstream,\n sourcePort: df.sourceTaskPortId,\n targetPort: df.targetTaskPortId,\n });\n }\n }\n }\n\n // 2. Track upstreams that may still emit snapshots (pending, processing, or streaming).\n // An upstream is \"done\" once its stream ends or it reaches a terminal state.\n const upstreamTasks = new Set(dataflowInfos.map((d) => d.upstream));\n const pendingUpstreams = new Set<ITask>(\n [...upstreamTasks].filter(\n (u) =>\n u.status === TaskStatus.STREAMING ||\n u.status === TaskStatus.PENDING ||\n u.status === TaskStatus.PROCESSING\n )\n );\n\n // 3. Set up dirty/wake machinery.\n let dirty = true;\n let wakeResolve: (() => void) | undefined;\n const wakeNext = (): Promise<void> =>\n new Promise<void>((resolve) => {\n wakeResolve = resolve;\n });\n const wake = () => {\n const r = wakeResolve;\n wakeResolve = undefined;\n if (r) r();\n };\n\n // 4. Subscribe to all upstream tasks that could stream.\n const cleanupFns: Array<() => void> = [];\n for (const upstream of pendingUpstreams) {\n const myDataflows = dataflowInfos.filter((d) => d.upstream === upstream);\n\n const onChunk = (event: StreamEvent) => {\n if (event.type !== \"snapshot\") return;\n const snapshotData = (event as { data?: Record<string, unknown> }).data;\n if (snapshotData) {\n for (const { sourcePort, targetPort } of myDataflows) {\n const value = sourcePort === \"*\" ? snapshotData : snapshotData[sourcePort];\n if (value !== undefined) {\n (this.task.runInputData as Record<string, unknown>)[targetPort] = value;\n }\n }\n }\n dirty = true;\n wake();\n };\n const onEnd = () => {\n pendingUpstreams.delete(upstream);\n wake();\n };\n const onStatus = (status: TaskStatus) => {\n // If upstream completes without streaming, remove it from pending.\n if (\n status === TaskStatus.COMPLETED ||\n status === TaskStatus.FAILED ||\n status === TaskStatus.DISABLED\n ) {\n pendingUpstreams.delete(upstream);\n wake();\n }\n };\n upstream.on(\"stream_chunk\", onChunk);\n upstream.on(\"stream_end\", onEnd);\n upstream.on(\"status\", onStatus);\n cleanupFns.push(() => {\n upstream.off(\"stream_chunk\", onChunk);\n upstream.off(\"stream_end\", onEnd);\n upstream.off(\"status\", onStatus);\n });\n }\n\n // 4b. Re-check upstream status after subscribing. If any reached a terminal\n // state in the gap between step 2 (status read) and step 4 (listener\n // attach), prune them now — listeners attached in step 4 won't fire\n // retroactively for events that already happened. The first iteration\n // of the loop still yields a preview from whatever runInputData\n // currently holds.\n for (const upstream of [...pendingUpstreams]) {\n if (\n upstream.status === TaskStatus.COMPLETED ||\n upstream.status === TaskStatus.FAILED ||\n upstream.status === TaskStatus.DISABLED\n ) {\n pendingUpstreams.delete(upstream);\n }\n }\n\n // 5. Iterator loop.\n try {\n while (true) {\n if (dirty) {\n dirty = false;\n try {\n const out = await this.runPreview(overrides);\n yield out;\n } catch (err) {\n getLogger().debug(\"runPreviewStream iteration failed\", {\n taskId: this.task.config?.id,\n error: err,\n });\n }\n continue;\n }\n if (pendingUpstreams.size === 0) return;\n await wakeNext();\n }\n } finally {\n for (const off of cleanupFns) off();\n }\n }\n\n public abort(): void {\n this.currentCtx?.abortController.abort();\n }\n\n // ========================================================================\n // Protected methods\n // ========================================================================\n\n protected own<T extends Taskish<any, any>>(i: T): T {\n const task = ensureTask(i, { isOwned: true });\n this.task.subGraph.addTask(task);\n // Propagate parent registry and abort signal to owned ITask instances so\n // that calling task.run() on the returned value inherits this execution context.\n if (hasRunConfig(i)) {\n // Only propagate `resourceScope` if the caller owns its lifecycle. Stamping\n // an auto-created scope into a long-lived `runConfig` leaks a reference\n // past the parent run's `finally`-block disposal — the next `task.run()`\n // on the owned instance would then see a disposed scope, skip auto-create,\n // and silently drop disposers on its cleared Map. With caller-passed\n // scopes the caller controls disposal, so the propagation is safe and\n // preserves resource-sharing across owned-task runs.\n const stamp: Partial<IRunConfig> = {\n registry: this.registry,\n signal: this.currentCtx?.abortController.signal,\n };\n if (!this.ownsResourceScope) {\n stamp.resourceScope = this.resourceScope;\n }\n Object.assign(i.runConfig, stamp);\n }\n // Notify listeners that the entitlement landscape may have changed.\n // For GraphAsTask this is also handled by the subGraph subscription, but\n // non-GraphAsTask tasks with dynamic entitlements (e.g. AiTask) need it too.\n if ((this.task.constructor as typeof Task).hasDynamicEntitlements) {\n this.task.emit(\"entitlementChange\", this.task.entitlements());\n }\n return i;\n }\n\n protected async executeTask(input: Input, ctx: TaskRunContext): Promise<Output | undefined> {\n const result = await this.task.execute(input, {\n signal: ctx.abortController.signal,\n updateProgress: this.handleProgress.bind(this),\n own: this.own,\n registry: this.registry,\n resourceScope: this.resourceScope,\n runId: this.runId,\n });\n return result;\n }\n\n protected async executeTaskPreview(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.task.executePreview?.(input, { own: this.own });\n }\n\n // ========================================================================\n // Protected Handlers\n // ========================================================================\n\n /**\n * Resolves config and input schema annotations (e.g. mcp-server references)\n * by mutating task.config and task.runInputData. Always resolves config from\n * originalConfig so re-runs use the original string IDs, not previously resolved\n * objects. Shared between run() and runPreview() to avoid duplication.\n */\n private async resolveSchemas(): Promise<void> {\n const configSchema = (this.task.constructor as typeof Task).configSchema();\n if (schemaHasFormatAnnotations(configSchema)) {\n const source = (this.task as unknown as Task).originalConfig ?? this.task.config;\n const resolved = await resolveSchemaInputs(\n { ...source } as Record<string, unknown>,\n configSchema,\n { registry: this.registry }\n );\n Object.assign(this.task.config, resolved);\n }\n\n // Resolve schema-annotated inputs (models, repositories) before validation.\n // Dynamic-schema tasks (InputTask, GraphAsTask, …) store the effective schema on\n // the instance; the static schema has no format annotations and would skip hydration.\n const ctor = this.task.constructor as typeof Task;\n const schema = ctor.hasDynamicSchemas ? this.task.inputSchema() : ctor.inputSchema();\n this.task.runInputData = (await resolveSchemaInputs(\n this.task.runInputData as Record<string, unknown>,\n schema,\n { registry: this.registry }\n )) as Input;\n }\n\n /**\n * Handles task start. Concurrent-run rejection happens in {@link run} before\n * any state mutation; by the time `handleStart` runs, the task status is\n * guaranteed to be non-PROCESSING.\n *\n * Returns the per-run {@link TaskRunContext} so `run()` can thread it\n * through locals instead of re-reading `this.currentCtx` across awaits.\n * The instance field `this.currentCtx` is still set as the *external*\n * pointer used by no-arg public methods (`abort()`, `disable()`); internal\n * flow should use the returned ctx exclusively.\n */\n protected async handleStart(config: IRunConfig = {}): Promise<TaskRunContext> {\n this.running = true;\n\n this.task.startedAt = new Date();\n this.task.progress = 0;\n this.task.status = TaskStatus.PROCESSING;\n\n // Build per-run context (handles abortController + parentSignal wiring)\n const ctx = new TaskRunContext(config.signal);\n this.currentCtx = ctx;\n\n // Listener captures the local `ctx`, not `this.currentCtx`. If a later run\n // replaces the instance field before this listener fires, handleAbort still\n // operates on the ctx the listener was attached to.\n ctx.abortController.signal.addEventListener(\"abort\", () => {\n void this.handleAbort(ctx);\n });\n\n // Apply registry override first so that cache resolution below uses the\n // correct per-run ServiceRegistry rather than the stale instance field.\n if (config.registry) {\n this.registry = config.registry;\n }\n\n // Propagate run identifier for use in IExecuteContext.\n this.runId = config.runId;\n\n // Cache resolution: prefer CacheRegistry (via ServiceRegistry); honour legacy\n // config.outputCache as a back-compat shim that maps to the deterministic slot.\n const legacy = config.outputCache ?? this.task.runConfig?.outputCache;\n if (legacy === false) {\n this.cacheRegistry = undefined;\n this.outputCache = undefined;\n } else if (legacy instanceof TaskOutputRepository) {\n // Legacy repo passed directly → treat as the deterministic slot.\n this.cacheRegistry = new DefaultCacheRegistry({ deterministic: legacy });\n this.outputCache = legacy;\n } else if (legacy === true) {\n // Legacy boolean true → pull from TASK_OUTPUT_REPOSITORY in the global registry.\n const instance = globalServiceRegistry.has(TASK_OUTPUT_REPOSITORY)\n ? globalServiceRegistry.get(TASK_OUTPUT_REPOSITORY)\n : undefined;\n this.outputCache = instance;\n this.cacheRegistry = instance\n ? new DefaultCacheRegistry({ deterministic: instance })\n : undefined;\n } else {\n // No legacy override → look up CACHE_REGISTRY from the per-run ServiceRegistry.\n this.outputCache = undefined;\n this.cacheRegistry = this.registry.has(CACHE_REGISTRY)\n ? this.registry.get(CACHE_REGISTRY)\n : undefined;\n }\n\n // shouldAccumulate defaults to true (backward-compatible for standalone runs)\n ctx.shouldAccumulate = config.shouldAccumulate !== false;\n\n if (config.updateProgress) {\n this.updateProgress = config.updateProgress;\n }\n\n if (config.resourceScope) {\n this.resourceScope = config.resourceScope;\n }\n\n // Notify the disposal strategy that a new run is starting. Inactivity\n // strategies use this hook to clear any pending idle timers that were\n // armed at the previous `runComplete`, closing the race window where a\n // timer could fire mid-run and dispose a resource we are about to use.\n if (this.resourceScope) {\n await this.resourceScope.runStart();\n }\n\n // Early-out if parent signal was already aborted (TaskRunContext constructor\n // already aborted ctx.abortController in that case)\n if (ctx.abortController.signal.aborted) return ctx;\n\n // Start timeout timer if configured (timeout is a design-time config property).\n // Fire on the captured ctx's controller rather than this.abort() so a timeout\n // armed for *this* run can't accidentally abort a later run if scope-teardown\n // racing leaves the timer alive past terminal-handler.\n const timeout = (this.task.config as Record<string, unknown>).timeout as number | undefined;\n if (timeout !== undefined && timeout > 0) {\n ctx.pendingTimeoutError = new TaskTimeoutError(timeout);\n ctx.timeoutTimer = setTimeout(() => {\n ctx.abortController.abort();\n }, timeout);\n }\n\n // Start telemetry span\n const telemetry = getTelemetryProvider();\n if (telemetry.isEnabled) {\n ctx.telemetrySpan = telemetry.startSpan(\"workglow.task.run\", {\n attributes: {\n \"workglow.task.type\": this.task.type,\n \"workglow.task.id\": String(this.task.config.id),\n \"workglow.task.title\": this.task.title || undefined,\n },\n });\n }\n\n this.task.emit(\"start\");\n this.task.emit(\"status\", this.task.status);\n return ctx;\n }\n private updateProgress = async (\n _task: ITask,\n _progress: number | undefined,\n _message?: string,\n ..._args: any[]\n ) => {};\n\n protected async handleStartPreview(): Promise<void> {\n this.previewRunning = true;\n }\n\n /**\n * Clears the timeout timer on the given ctx if one is active.\n */\n protected clearTimeoutTimer(ctx: TaskRunContext): void {\n if (ctx.timeoutTimer !== undefined) {\n clearTimeout(ctx.timeoutTimer);\n ctx.timeoutTimer = undefined;\n }\n }\n\n /**\n * Handles task abort.\n *\n * Idempotent per-ctx via {@link TaskRunContext.terminated}: the abort\n * listener fires synchronously inside `controller.abort()` and may race\n * with the run flow's own catch-block; both paths can land here. The\n * `terminated` flag (set before any await) lets the second arrival fall\n * through, while `task.status` is too brittle to gate on because adjacent\n * runs on the same task can mutate it.\n */\n protected async handleAbort(ctx: TaskRunContext): Promise<void> {\n if (ctx.terminated) return;\n ctx.terminated = true;\n this.clearTimeoutTimer(ctx);\n this.task.status = TaskStatus.ABORTING;\n await this.handleProgress(100);\n // Use the pending timeout error if the abort was triggered by a timeout\n this.task.error = ctx.pendingTimeoutError ?? new TaskAbortedError();\n\n if (ctx.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.ERROR, \"aborted\");\n ctx.telemetrySpan.addEvent(\"workglow.task.aborted\", {\n \"workglow.task.error\": this.task.error.message,\n });\n ctx.telemetrySpan.end();\n }\n\n // Call optional cleanup method for resource release\n if (typeof this.task.cleanup === \"function\") {\n try {\n await this.task.cleanup();\n } catch {\n // Cleanup errors are swallowed — abort must not throw from cleanup\n }\n }\n\n ctx.dispose();\n // CAS-style clear: only release the instance pointer if it still points at\n // *this* ctx. Prevents a stale terminal handler from clobbering a newer\n // run's currentCtx.\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n\n this.task.emit(\"abort\", this.task.error);\n this.task.emit(\"status\", this.task.status);\n }\n\n protected async handleAbortPreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n /**\n * Handles task completion.\n *\n * Idempotent per-ctx — see {@link handleAbort} for the rationale on using\n * `ctx.terminated` instead of `task.status` as the guard.\n */\n protected async handleComplete(ctx: TaskRunContext): Promise<void> {\n if (ctx.terminated) return;\n ctx.terminated = true;\n this.clearTimeoutTimer(ctx);\n\n this.task.completedAt = new Date();\n this.task.status = TaskStatus.COMPLETED;\n await this.handleProgress(100);\n\n if (ctx.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.OK);\n ctx.telemetrySpan.end();\n }\n\n ctx.dispose();\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n\n this.task.emit(\"complete\");\n this.task.emit(\"status\", this.task.status);\n }\n\n protected async handleCompletePreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n protected async handleDisable(ctx: TaskRunContext | undefined): Promise<void> {\n // Idempotent per-ctx where one exists; falls back to status-based guard\n // for the no-active-run case (public disable() called with no current ctx).\n if (ctx?.terminated || this.task.status === TaskStatus.DISABLED) return;\n if (ctx) ctx.terminated = true;\n this.task.status = TaskStatus.DISABLED;\n await this.handleProgress(100);\n this.task.completedAt = new Date();\n ctx?.dispose();\n // Don't clobber a newer run's ctx if disable() was queued from a stale state.\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n this.task.emit(\"disabled\");\n this.task.emit(\"status\", this.task.status);\n }\n\n public async disable(): Promise<void> {\n await this.handleDisable(this.currentCtx);\n }\n\n /**\n * Handles task error.\n *\n * If the underlying error is an abort, delegate to {@link handleAbort} —\n * which is idempotent per-ctx, so a parallel abort-listener path is safe.\n */\n protected async handleError(err: Error, ctx: TaskRunContext): Promise<void> {\n if (err instanceof TaskAbortedError) return this.handleAbort(ctx);\n if (ctx.terminated) return;\n ctx.terminated = true;\n this.clearTimeoutTimer(ctx);\n if (this.task.hasChildren()) {\n this.task.subGraph!.abort();\n }\n\n this.task.completedAt = new Date();\n if (err instanceof TaskError) {\n this.task.error = err;\n } else {\n this.task.error = new TaskFailedError(\n `Task \"${this.task.type}\" (${this.task.id}): ${err?.message || \"Task failed\"}`\n );\n }\n // Attach task context to all TaskError instances for programmatic access\n if (this.task.error instanceof TaskError) {\n this.task.error.taskType ??= this.task.type;\n this.task.error.taskId ??= this.task.id;\n }\n this.task.status = TaskStatus.FAILED;\n await this.handleProgress(100);\n\n if (ctx.telemetrySpan) {\n ctx.telemetrySpan.setStatus(SpanStatusCode.ERROR, this.task.error.message);\n ctx.telemetrySpan.setAttributes({ \"workglow.task.error\": this.task.error.message });\n ctx.telemetrySpan.end();\n }\n\n ctx.dispose();\n if (this.currentCtx === ctx) this.currentCtx = undefined;\n\n this.task.emit(\"error\", this.task.error);\n this.task.emit(\"status\", this.task.status);\n }\n\n protected async handleErrorPreview(): Promise<void> {\n this.previewRunning = false;\n }\n\n protected async handleProgress(\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ): Promise<void> {\n this.task.progress = progress;\n // Emit before graph-level work (e.g. pushOutputFromNodeToEdges) so listeners are not stalled.\n this.task.emit(\"progress\", progress, message, ...args);\n await this.updateProgress(this.task, progress, message, ...args);\n }\n}\n",
|
|
36
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getPortCodec } from \"@workglow/util\";\nimport { type CachePolicy, isPolicyCached, isPolicyPrivate } from \"../cache/CachePolicy\";\nimport type { CacheRegistry } from \"../cache/CacheRegistry\";\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { ITask } from \"./ITask\";\nimport type { StreamEvent } from \"./StreamTypes\";\nimport { Task } from \"./Task\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\n\ninterface SchemaProperties {\n properties?: Record<string, { format?: string }>;\n}\n\n/**\n * @internal\n * Cache key normalization, lookup, save, and cache-hit stream-event emission\n * for streamable tasks. The three previously module-private helpers\n * (serializeOutputPorts, deserializeOutputPorts, normalizeInputsForCacheKey)\n * are private statics here.\n *\n * outputCache is passed as a method argument (not stored as a class field)\n * because the facade resolves it per-run in handleStart and may differ\n * between runs.\n */\nexport class CacheCoordinator<Input extends TaskInput, Output extends TaskOutput> {\n constructor(private readonly task: ITask<Input, Output, any>) {}\n\n /**\n * Serializes format-annotated input properties (via their port codecs) so the\n * resulting object is a stable, serialization-equivalent representation\n * suitable for use as a cache key. Properties without a format annotation are\n * passed through unchanged. No-op when no cache is configured.\n *\n * The reserved sentinel field `__cv` (cache version) is injected into the\n * normalized object before fingerprinting so that bumping a task's `static\n * version` automatically invalidates its cached outputs. Tasks must never\n * declare an input port named `__cv`.\n */\n async buildKey(inputs: Input, outputCache: TaskOutputRepository | undefined): Promise<Input> {\n if (!outputCache) return inputs;\n const inputSchema = (this.task.constructor as typeof Task).inputSchema();\n const normalized = await CacheCoordinator.normalizeInputsForCacheKey(\n inputs as Record<string, unknown>,\n inputSchema as unknown as SchemaProperties\n );\n (normalized as Record<string, unknown>).__cv = this.task.getCacheVersion();\n return normalized as Input;\n }\n\n /**\n * Looks up a cached output. On a hit for a streaming task, also emits the\n * synthetic stream_start / stream_chunk(finish) / stream_end events so\n * downstream consumers see the same event shape as a fresh run.\n *\n * Returns the deserialized output if found, undefined otherwise.\n */\n /**\n * Cache identity for the `taskType` axis of {@link TaskOutputRepository}.\n * Deterministic entries key by task class; private (run-resume) entries key by\n * task instance id so two nodes of the same type in one graph do not collide.\n */\n private cacheIdentityKey(policy: CachePolicy): string {\n return isPolicyPrivate(policy) ? String(this.task.id) : this.task.type;\n }\n\n async lookup(\n keyInputs: Input,\n outputCache: TaskOutputRepository | undefined,\n policy: CachePolicy,\n isStreamable: boolean,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (!outputCache || !this.task.cacheable) return undefined;\n\n const cached = await outputCache.getOutput(this.cacheIdentityKey(policy), keyInputs);\n if (cached === undefined) return undefined;\n\n const outputSchema = (this.task.constructor as typeof Task).outputSchema();\n const outputs = (await CacheCoordinator.deserializeOutputPorts(\n cached as Record<string, unknown>,\n outputSchema as unknown as SchemaProperties\n )) as Output;\n\n ctx.telemetrySpan?.addEvent(\"workglow.task.cache_hit\");\n\n if (isStreamable) {\n this.task.runOutputData = outputs;\n this.task.emit(\"stream_start\");\n this.task.emit(\"stream_chunk\", { type: \"finish\", data: outputs } as StreamEvent);\n this.task.emit(\"stream_end\", outputs);\n } else {\n this.task.runOutputData = outputs;\n }\n\n return outputs;\n }\n\n /**\n * Serializes and saves output. No-op when no cache is configured or task is\n * not cacheable.\n */\n async save(\n keyInputs: Input,\n output: Output,\n outputCache: TaskOutputRepository | undefined,\n policy: CachePolicy\n ): Promise<void> {\n if (!outputCache || !this.task.cacheable || output === undefined) return;\n const outputSchema = (this.task.constructor as typeof Task).outputSchema();\n const wireOutputs = await CacheCoordinator.serializeOutputPorts(\n output as Record<string, unknown>,\n outputSchema as unknown as SchemaProperties\n );\n await outputCache.saveOutput(this.cacheIdentityKey(policy), keyInputs, wireOutputs as Output);\n }\n\n // ========================================================================\n // Policy-aware routing methods\n // ========================================================================\n\n /**\n * Resolve the repository slot to use given a registry and policy. Returns\n * `undefined` if the registry is missing, the policy is `kind: \"none\"`, or\n * the relevant slot is unregistered. All callers treat `undefined` as \"skip\n * caching\" — no errors, no warnings.\n */\n private repoFor(\n registry: CacheRegistry | undefined,\n policy: CachePolicy\n ): TaskOutputRepository | undefined {\n if (!registry || !isPolicyCached(policy)) return undefined;\n return isPolicyPrivate(policy) ? registry.private : registry.deterministic;\n }\n\n public async buildKeyForPolicy(\n inputs: Input,\n registry: CacheRegistry | undefined,\n policy: CachePolicy\n ): Promise<Input> {\n return this.buildKey(inputs, this.repoFor(registry, policy));\n }\n\n public async lookupByPolicy(\n keyInputs: Input,\n registry: CacheRegistry | undefined,\n policy: CachePolicy,\n isStreamable: boolean,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.lookup(keyInputs, this.repoFor(registry, policy), policy, isStreamable, ctx);\n }\n\n public async saveByPolicy(\n keyInputs: Input,\n output: Output,\n registry: CacheRegistry | undefined,\n policy: CachePolicy\n ): Promise<void> {\n return this.save(keyInputs, output, this.repoFor(registry, policy), policy);\n }\n\n // ========================================================================\n // Private static helpers (lifted from current module-private functions in\n // TaskRunner.ts)\n // ========================================================================\n\n private static async serializeOutputPorts(\n output: Record<string, unknown>,\n schema: SchemaProperties\n ): Promise<Record<string, unknown>> {\n if (!schema?.properties) return output;\n const out: Record<string, unknown> = { ...output };\n for (const [key, prop] of Object.entries(schema.properties)) {\n const codec = prop.format ? getPortCodec(prop.format) : undefined;\n if (codec && out[key] !== undefined) {\n out[key] = await codec.serialize(out[key]);\n }\n }\n return out;\n }\n\n private static async deserializeOutputPorts(\n output: Record<string, unknown>,\n schema: SchemaProperties\n ): Promise<Record<string, unknown>> {\n if (!schema?.properties) return output;\n const out: Record<string, unknown> = { ...output };\n for (const [key, prop] of Object.entries(schema.properties)) {\n const codec = prop.format ? getPortCodec(prop.format) : undefined;\n if (codec && out[key] !== undefined) {\n out[key] = await codec.deserialize(out[key]);\n }\n }\n return out;\n }\n\n private static async normalizeInputsForCacheKey(\n inputs: Record<string, unknown>,\n schema: SchemaProperties\n ): Promise<Record<string, unknown>> {\n if (!schema?.properties) return inputs;\n const out: Record<string, unknown> = { ...inputs };\n for (const [key, prop] of Object.entries(schema.properties)) {\n const codec = prop.format ? getPortCodec(prop.format) : undefined;\n if (codec && out[key] !== undefined) {\n out[key] = await codec.serialize(out[key]);\n }\n }\n return out;\n }\n}\n",
|
|
37
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ResourceScope, ServiceRegistry } from \"@workglow/util\";\nimport type { Taskish } from \"../task-graph/Conversions\";\nimport type { ITask } from \"./ITask\";\nimport type { StreamEvent, StreamMode } from \"./StreamTypes\";\nimport { getOutputStreamMode, getStreamingPorts } from \"./StreamTypes\";\nimport { TaskAbortedError, TaskError } from \"./TaskError\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\nimport { TaskStatus } from \"./TaskTypes\";\n\n/**\n * Per-call run-state inputs shared by StreamProcessor.run. Bundles facade\n * state pulled at call time (registry, resourceScope, inputStreams) and\n * facade methods bound to the facade instance (onProgress, own).\n *\n * @internal\n */\nexport interface StreamProcessorDeps {\n readonly registry: ServiceRegistry;\n readonly resourceScope: ResourceScope | undefined;\n readonly inputStreams: Map<string, ReadableStream<StreamEvent>> | undefined;\n readonly onProgress: (\n progress: number | undefined,\n message?: string,\n ...args: any[]\n ) => Promise<void>;\n readonly own: <T extends Taskish<any, any>>(i: T) => T;\n}\n\n/**\n * @internal\n * Streaming event loop. Consumes a task's executeStream() output, manages\n * text/object delta accumulators, mode switching (append/object/replace),\n * and finish-event enrichment. Honors ctx.shouldAccumulate and\n * ctx.abortController.signal.\n */\nexport class StreamProcessor<Input extends TaskInput, Output extends TaskOutput> {\n constructor(private readonly task: ITask<Input, Output, any>) {}\n\n async run(\n input: Input,\n ctx: TaskRunContext,\n deps: StreamProcessorDeps\n ): Promise<Output | undefined> {\n const streamMode: StreamMode = getOutputStreamMode(this.task.outputSchema());\n if (streamMode === \"append\") {\n const ports = getStreamingPorts(this.task.outputSchema());\n if (ports.length === 0) {\n throw new TaskError(\n `Task ${this.task.type} declares append streaming but no output port has x-stream: \"append\"`\n );\n }\n }\n if (streamMode === \"object\") {\n const ports = getStreamingPorts(this.task.outputSchema());\n if (ports.length === 0) {\n throw new TaskError(\n `Task ${this.task.type} declares object streaming but no output port has x-stream: \"object\"`\n );\n }\n }\n\n const accumulated = ctx.shouldAccumulate ? new Map<string, string>() : undefined;\n const accumulatedObjects = ctx.shouldAccumulate\n ? new Map<string, Record<string, unknown> | unknown[]>()\n : undefined;\n let streamingStarted = false;\n let finalOutput: Output | undefined;\n\n this.task.emit(\"stream_start\");\n\n const stream = this.task.executeStream!(input, {\n signal: ctx.abortController.signal,\n updateProgress: deps.onProgress,\n own: deps.own,\n registry: deps.registry,\n resourceScope: deps.resourceScope,\n inputStreams: deps.inputStreams,\n });\n\n for await (const event of stream) {\n // For snapshot events, update runOutputData BEFORE emitting stream_chunk\n // so listeners see the latest snapshot when they handle the event.\n if (event.type === \"snapshot\") {\n this.task.runOutputData = event.data as Output;\n }\n\n switch (event.type) {\n case \"phase\": {\n // Phase events are metadata: emit for observability, translate to a\n // progress event with optional progress + message, do NOT mutate\n // accumulators or runOutputData, do NOT flip status to STREAMING.\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n await deps.onProgress(event.progress, event.message);\n break;\n }\n case \"text-delta\": {\n if (!streamingStarted) {\n streamingStarted = true;\n this.task.status = TaskStatus.STREAMING;\n this.task.emit(\"status\", this.task.status);\n }\n if (accumulated) {\n accumulated.set(event.port, (accumulated.get(event.port) ?? \"\") + event.textDelta);\n }\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n break;\n }\n case \"object-delta\": {\n if (!streamingStarted) {\n streamingStarted = true;\n this.task.status = TaskStatus.STREAMING;\n this.task.emit(\"status\", this.task.status);\n }\n if (accumulatedObjects) {\n const existing = accumulatedObjects.get(event.port);\n if (Array.isArray(event.objectDelta)) {\n // Array delta: upsert items by `id` into accumulated array\n const arr: unknown[] = Array.isArray(existing) ? [...existing] : [];\n for (const item of event.objectDelta) {\n const itemObj = item as Record<string, unknown>;\n if (itemObj && typeof itemObj === \"object\" && \"id\" in itemObj) {\n const idx = arr.findIndex(\n (e) => (e as Record<string, unknown>).id === itemObj.id\n );\n if (idx >= 0) arr[idx] = item;\n else arr.push(item);\n } else {\n arr.push(item);\n }\n }\n accumulatedObjects.set(event.port, arr);\n } else {\n // Non-array (e.g. structured generation): replace semantics\n accumulatedObjects.set(event.port, event.objectDelta);\n }\n }\n // Update runOutputData with accumulated state so listeners see growing state\n this.task.runOutputData = {\n ...this.task.runOutputData,\n [event.port]: accumulatedObjects?.get(event.port) ?? event.objectDelta,\n } as Output;\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n break;\n }\n case \"snapshot\": {\n if (!streamingStarted) {\n streamingStarted = true;\n this.task.status = TaskStatus.STREAMING;\n this.task.emit(\"status\", this.task.status);\n }\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n break;\n }\n case \"finish\": {\n if (accumulated || accumulatedObjects) {\n // Emit an enriched finish event: merge accumulated deltas into\n // the finish payload so downstream dataflows get complete port data\n // without needing to re-accumulate themselves.\n const merged: Record<string, unknown> = { ...(event.data || {}) };\n if (accumulated) {\n for (const [port, text] of accumulated) {\n if (text.length > 0) merged[port] = text;\n }\n }\n if (accumulatedObjects) {\n for (const [port, obj] of accumulatedObjects) {\n merged[port] = obj;\n }\n }\n // For replace-mode streams, finish carries data: {} by convention.\n // Fall back to the last snapshot (runOutputData) so the final output\n // is not silently cleared when the finish payload is empty.\n if (streamMode === \"replace\" && Object.keys(merged).length === 0) {\n const lastSnapshot = this.task.runOutputData;\n if (lastSnapshot && Object.keys(lastSnapshot).length > 0) {\n finalOutput = lastSnapshot as Output;\n this.task.emit(\"stream_chunk\", {\n type: \"finish\",\n data: lastSnapshot,\n } as StreamEvent);\n break;\n }\n }\n finalOutput = merged as unknown as Output;\n this.task.emit(\"stream_chunk\", { type: \"finish\", data: merged } as StreamEvent);\n } else {\n // No accumulation. For replace-mode streams the provider's finish\n // event carries `data: {}` by convention — the snapshots already\n // delivered the value, so the finish payload is intentionally\n // empty. Fall back to `runOutputData` (set on every snapshot above)\n // so we don't clobber the last snapshot with an empty object. This\n // mirrors the same fallback in the accumulation branch.\n const finishData = (event.data ?? {}) as Record<string, unknown>;\n if (streamMode === \"replace\" && Object.keys(finishData).length === 0) {\n const lastSnapshot = this.task.runOutputData;\n if (lastSnapshot && Object.keys(lastSnapshot).length > 0) {\n finalOutput = lastSnapshot as Output;\n this.task.emit(\"stream_chunk\", {\n type: \"finish\",\n data: lastSnapshot,\n } as StreamEvent);\n break;\n }\n }\n finalOutput = event.data as Output;\n this.task.emit(\"stream_chunk\", event as StreamEvent);\n }\n break;\n }\n case \"error\": {\n throw event.error;\n }\n }\n }\n\n // Check if the task was aborted during streaming\n if (ctx.abortController.signal.aborted) {\n throw new TaskAbortedError(\"Task aborted during streaming\");\n }\n\n if (finalOutput !== undefined) {\n this.task.runOutputData = finalOutput;\n }\n\n this.task.emit(\"stream_end\", this.task.runOutputData as Output);\n\n return this.task.runOutputData as Output;\n }\n}\n",
|
|
38
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ISpan } from \"@workglow/util\";\nimport type { TaskTimeoutError } from \"./TaskError\";\n\n/**\n * @internal\n * Per-run mutable state for a single TaskRunner.run() / runPreview() invocation.\n * Built by TaskRunner.handleStart, discarded by handleComplete / handleError / handleAbort.\n *\n * Long-lived state (task, registry, resourceScope, outputCache default, accumulateLeafOutputs)\n * stays on the facade. TaskRunContext only holds state created at run start and torn down\n * at run end.\n */\nexport class TaskRunContext {\n readonly abortController: AbortController;\n\n shouldAccumulate: boolean = true;\n telemetrySpan?: ISpan;\n timeoutTimer?: ReturnType<typeof setTimeout>;\n pendingTimeoutError?: TaskTimeoutError;\n\n /**\n * Set by the first terminal handler (handleAbort / handleComplete / handleError /\n * handleDisable) that runs for this ctx. Lets handlers be idempotent per-ctx\n * without leaning on `task.status`, which is externally observable and can be\n * mutated by adjacent runs.\n */\n terminated: boolean = false;\n\n // Removes the parentSignal abort listener; set in the constructor when\n // parentSignal is provided. Idempotent dispose().\n private parentSignalCleanup?: () => void;\n\n constructor(parentSignal?: AbortSignal) {\n this.abortController = new AbortController();\n if (parentSignal) {\n // Listen first, then check — addEventListener on an already-aborted signal\n // does not fire, so checking .aborted after ensures we never miss an abort.\n const onParentAbort = () => this.abortController.abort();\n parentSignal.addEventListener(\"abort\", onParentAbort, { once: true });\n this.parentSignalCleanup = () => parentSignal.removeEventListener(\"abort\", onParentAbort);\n if (parentSignal.aborted) {\n this.parentSignalCleanup();\n this.parentSignalCleanup = undefined;\n this.abortController.abort();\n }\n }\n }\n\n /**\n * Releases external listeners (parentSignal abort handler). Idempotent.\n * Called by terminal handlers (handleComplete / handleError / handleAbort)\n * so a parent abort fired after this run completes does not re-trigger our\n * abort path and emit a duplicate terminal event.\n */\n dispose(): void {\n this.parentSignalCleanup?.();\n this.parentSignalCleanup = undefined;\n }\n}\n",
|
|
41
39
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { EventParameters } from \"@workglow/util\";\nimport { EventEmitter, ServiceRegistry } from \"@workglow/util\";\nimport type { TaskOutputRepository } from \"../storage/TaskOutputRepository\";\nimport type { ConditionFn } from \"../task/ConditionalTask\";\nimport { GraphAsTask } from \"../task/GraphAsTask\";\nimport type { IRunConfig, ITask, ITaskConstructor } from \"../task/ITask\";\nimport type { StreamEvent } from \"../task/StreamTypes\";\nimport { Task } from \"../task/Task\";\nimport type { TaskEntitlements } from \"../task/TaskEntitlements\";\nimport { WorkflowError } from \"../task/TaskError\";\nimport type { JsonTaskItem, TaskGraphJson, TaskGraphJsonOptions } from \"../task/TaskJSON\";\nimport type { DataPorts, TaskConfig, TaskIdType, TaskInput } from \"../task/TaskTypes\";\nimport { autoConnect } from \"./autoConnect\";\nimport type { ConditionalBuilder } from \"./ConditionalBuilder\";\nimport type { PipeFunction, Taskish } from \"./Conversions\";\nimport type { GraphEntitlementOptions } from \"./GraphEntitlementUtils\";\nimport { computeGraphEntitlements } from \"./GraphEntitlementUtils\";\nimport type { IWorkflow, WorkflowRunConfig } from \"./IWorkflow\";\nimport { LoopBuilderContext, runLoopAutoConnect } from \"./LoopBuilderContext\";\nimport { TaskGraph } from \"./TaskGraph\";\nimport type { PropertyArrayGraphResult } from \"./TaskGraphRunner\";\nimport { CompoundMergeStrategy, PROPERTY_ARRAY } from \"./TaskGraphRunner\";\nimport type { ITransformStep } from \"./TransformTypes\";\nimport type { IWorkflowBuilderHandle } from \"./WorkflowBuilder\";\nimport { WorkflowBuilder } from \"./WorkflowBuilder\";\nimport { WorkflowCacheAdapter } from \"./WorkflowCacheAdapter\";\nimport { WorkflowEventBridge } from \"./WorkflowEventBridge\";\nimport type { CreateWorkflow } from \"./WorkflowFactories\";\nimport { CreateEndLoopWorkflow, CreateLoopWorkflow } from \"./WorkflowFactories\";\nimport { parallel, pipe } from \"./WorkflowPipe\";\nimport { WorkflowRunContext } from \"./WorkflowRunContext\";\nimport { WorkflowTask } from \"./WorkflowTask\";\n\n/** Options accepted by {@link Workflow.rename}. */\nexport interface RenameOptions {\n /** Index of the task whose output is renamed (defaults to the last task, `-1`). */\n readonly index?: number;\n /** Transform chain applied to the dataflow edge this rename creates. */\n readonly transforms?: ReadonlyArray<ITransformStep>;\n}\n\nexport type WorkflowEventListeners = {\n changed: (id: unknown) => void;\n reset: () => void;\n error: (error: string) => void;\n start: () => void;\n complete: () => void;\n abort: (error: string) => void;\n /** Fired when a task in the workflow starts streaming */\n stream_start: (taskId: TaskIdType) => void;\n /** Fired for each stream chunk produced by a task in the workflow */\n stream_chunk: (taskId: TaskIdType, event: StreamEvent) => void;\n /** Fired when a task in the workflow finishes streaming */\n stream_end: (taskId: TaskIdType, output: Record<string, any>) => void;\n /** Fired when the aggregated entitlements of the workflow change */\n entitlementChange: (entitlements: TaskEntitlements) => void;\n};\n\nexport type WorkflowEvents = keyof WorkflowEventListeners;\nexport type WorkflowEventListener<Event extends WorkflowEvents> = WorkflowEventListeners[Event];\nexport type WorkflowEventParameters<Event extends WorkflowEvents> = EventParameters<\n WorkflowEventListeners,\n Event\n>;\n\n/**\n * Class for building and managing a task graph\n * Provides methods for adding tasks, connecting outputs to inputs, and running the task graph\n *\n * When used with a parent workflow (loop builder mode), this class redirects task additions\n * to the iterator task's template graph until an end method (endMap, endBatch, etc.) is called.\n */\nexport class Workflow<\n Input extends DataPorts = DataPorts,\n Output extends DataPorts = DataPorts,\n> implements IWorkflow<Input, Output> {\n constructor(\n cache?: TaskOutputRepository,\n parent?: Workflow,\n iteratorTask?: GraphAsTask,\n registry?: ServiceRegistry\n ) {\n this._cache = new WorkflowCacheAdapter(cache);\n this._graph = new TaskGraph({ outputCache: this._cache.outputCache() });\n\n const loopContext =\n parent && iteratorTask ? new LoopBuilderContext(parent, iteratorTask) : undefined;\n\n this._builder = new WorkflowBuilder(this, registry ?? parent?.builderRegistry, loopContext);\n\n if (!parent) {\n this._bridge = new WorkflowEventBridge(this.events);\n this._bridge.attach(this._graph);\n }\n }\n\n private _graph: TaskGraph;\n private _cache: WorkflowCacheAdapter;\n private _bridge?: WorkflowEventBridge;\n private _builder: WorkflowBuilder;\n\n // Per-run state. Single field — concurrent run() calls overwrite (last-run-\n // wins for abort), matching pre-refactor behavior of `_abortController`.\n // Mirrors RunContext on the TaskGraphRunner side.\n private _currentRun?: WorkflowRunContext;\n\n /** @internal — exposes the parent's registry so a child loop-builder can inherit it */\n private get builderRegistry(): ServiceRegistry | undefined {\n return this._builder.registry;\n }\n\n /**\n * Internal cross-instance handle for loop-builder wiring and error\n * propagation. Returns a NARROWED interface — only the two members the\n * package actually needs externally — so consumers cannot reach\n * `_dataFlows`, `_registry`, or other builder internals through `wf.builder`.\n * @internal\n */\n public get builder(): IWorkflowBuilderHandle {\n return this._builder;\n }\n\n public outputCache(): TaskOutputRepository | undefined {\n return this._cache.outputCache();\n }\n\n /**\n * Whether this workflow is in loop builder mode.\n * When true, tasks are added to the template graph for an iterator task.\n */\n public get isLoopBuilder(): boolean {\n return this._builder.loopContext !== undefined;\n }\n\n public readonly events = new EventEmitter<WorkflowEventListeners>();\n\n /**\n * Creates a helper function for adding specific task types to a Workflow\n *\n * @param taskClass - The task class to create a helper for\n * @returns A function that adds the specified task type to a Workflow\n */\n public static createWorkflow<\n I extends DataPorts,\n O extends DataPorts,\n C extends TaskConfig<I> = TaskConfig<I>,\n >(taskClass: ITaskConstructor<I, O, C>): CreateWorkflow<I, O, C> {\n const helper = function (\n this: Workflow<any, any>,\n input: Partial<I> = {},\n config: Partial<C> = {},\n runConfig?: Partial<IRunConfig>\n ) {\n this._builder.addTaskWithAutoConnect<I, O, C>(taskClass, input, config, runConfig);\n return this as any;\n };\n\n helper.type = (taskClass as unknown as { runtype?: string }).runtype ?? taskClass.type;\n helper.category = taskClass.category;\n helper.inputSchema = taskClass.inputSchema;\n helper.outputSchema = taskClass.outputSchema;\n helper.cacheable = taskClass.cacheable;\n helper.workflowCreate = true;\n\n return helper as CreateWorkflow<I, O, C>;\n }\n\n public get graph(): TaskGraph {\n return this._graph;\n }\n\n public set graph(value: TaskGraph) {\n this._builder.resetState();\n this._bridge?.detach();\n this._graph = value;\n this._bridge?.attach(this._graph);\n this.events.emit(\"reset\");\n }\n\n public get error(): string {\n return this._builder.error;\n }\n\n public on<Event extends WorkflowEvents>(name: Event, fn: WorkflowEventListener<Event>): void {\n this.events.on(name, fn);\n }\n\n public off<Event extends WorkflowEvents>(name: Event, fn: WorkflowEventListener<Event>): void {\n this.events.off(name, fn);\n }\n\n public once<Event extends WorkflowEvents>(name: Event, fn: WorkflowEventListener<Event>): void {\n this.events.once(name, fn);\n }\n\n public waitOn<Event extends WorkflowEvents>(\n name: Event\n ): Promise<WorkflowEventParameters<Event>> {\n return this.events.waitOn(name) as Promise<WorkflowEventParameters<Event>>;\n }\n\n public async run(\n input: Partial<Input> = {},\n config?: WorkflowRunConfig\n ): Promise<PropertyArrayGraphResult<Output>> {\n const loopContext = this._builder.loopContext;\n if (loopContext) {\n loopContext.finalizeTemplate(this._graph);\n const error = loopContext.consumePendingConnect();\n if (error) loopContext.parent.builder.setError(error);\n return loopContext.parent.run(input as any, config) as Promise<\n PropertyArrayGraphResult<Output>\n >;\n }\n\n this.events.emit(\"start\");\n const ctx = new WorkflowRunContext();\n this._currentRun = ctx;\n // Streaming unsub lives on the context (not the bridge) so concurrent\n // run() calls don't clobber each other's subscriptions.\n ctx.unsubStreaming = this._bridge?.beginRun();\n\n try {\n const output = await this.graph.run<Output>(input, {\n parentSignal: ctx.abortController.signal,\n outputCache: this._cache.outputCache(),\n registry: config?.registry ?? this._builder.registry,\n resourceScope: config?.resourceScope,\n });\n const results = this.graph.mergeExecuteOutputsToRunOutput<Output, typeof PROPERTY_ARRAY>(\n output,\n PROPERTY_ARRAY\n );\n this.events.emit(\"complete\");\n return results;\n } catch (error) {\n this.events.emit(\"error\", String(error));\n throw error;\n } finally {\n ctx.dispose();\n // Only clear the field if THIS run's context is still the current one.\n // Concurrent run() may have reseated it; clobbering would orphan that run.\n if (this._currentRun === ctx) this._currentRun = undefined;\n }\n }\n\n public async abort(): Promise<void> {\n const loopContext = this._builder.loopContext;\n if (loopContext) {\n return loopContext.parent.abort();\n }\n this._currentRun?.abortController.abort();\n }\n\n /**\n * Removes the last task from the task graph.\n */\n public pop(): Workflow {\n this._builder.pop();\n return this;\n }\n\n public toJSON(options: TaskGraphJsonOptions = { withBoundaryNodes: true }): TaskGraphJson {\n return this._graph.toJSON(options);\n }\n\n public toDependencyJSON(\n options: TaskGraphJsonOptions = { withBoundaryNodes: true }\n ): JsonTaskItem[] {\n return this._graph.toDependencyJSON(options);\n }\n\n /**\n * Returns the aggregated entitlements required by all tasks in this workflow.\n * @param options Options for controlling aggregation (e.g., conditional branch handling)\n */\n public entitlements(options?: GraphEntitlementOptions): TaskEntitlements {\n return computeGraphEntitlements(this._graph, options);\n }\n\n public pipe<A extends DataPorts, B extends DataPorts>(fn1: Taskish<A, B>): IWorkflow<A, B>;\n public pipe<A extends DataPorts, B extends DataPorts, C extends DataPorts>(\n fn1: Taskish<A, B>,\n fn2: Taskish<B, C>\n ): IWorkflow<A, C>;\n public pipe<A extends DataPorts, B extends DataPorts, C extends DataPorts, D extends DataPorts>(\n fn1: Taskish<A, B>,\n fn2: Taskish<B, C>,\n fn3: Taskish<C, D>\n ): IWorkflow<A, D>;\n public pipe<\n A extends DataPorts,\n B extends DataPorts,\n C extends DataPorts,\n D extends DataPorts,\n E extends DataPorts,\n >(\n fn1: Taskish<A, B>,\n fn2: Taskish<B, C>,\n fn3: Taskish<C, D>,\n fn4: Taskish<D, E>\n ): IWorkflow<A, E>;\n public pipe<\n A extends DataPorts,\n B extends DataPorts,\n C extends DataPorts,\n D extends DataPorts,\n E extends DataPorts,\n F extends DataPorts,\n >(\n fn1: Taskish<A, B>,\n fn2: Taskish<B, C>,\n fn3: Taskish<C, D>,\n fn4: Taskish<D, E>,\n fn5: Taskish<E, F>\n ): IWorkflow<A, F>;\n public pipe(...args: Taskish<DataPorts, DataPorts>[]): IWorkflow {\n return pipe(args as any, this);\n }\n\n public static pipe<A extends DataPorts, B extends DataPorts>(\n fn1: PipeFunction<A, B> | ITask<A, B>\n ): IWorkflow;\n public static pipe<A extends DataPorts, B extends DataPorts, C extends DataPorts>(\n fn1: PipeFunction<A, B> | ITask<A, B>,\n fn2: PipeFunction<B, C> | ITask<B, C>\n ): IWorkflow;\n public static pipe<\n A extends DataPorts,\n B extends DataPorts,\n C extends DataPorts,\n D extends DataPorts,\n >(\n fn1: PipeFunction<A, B> | ITask<A, B>,\n fn2: PipeFunction<B, C> | ITask<B, C>,\n fn3: PipeFunction<C, D> | ITask<C, D>\n ): IWorkflow;\n public static pipe<\n A extends DataPorts,\n B extends DataPorts,\n C extends DataPorts,\n D extends DataPorts,\n E extends DataPorts,\n >(\n fn1: PipeFunction<A, B> | ITask<A, B>,\n fn2: PipeFunction<B, C> | ITask<B, C>,\n fn3: PipeFunction<C, D> | ITask<C, D>,\n fn4: PipeFunction<D, E> | ITask<D, E>\n ): IWorkflow;\n public static pipe<\n A extends DataPorts,\n B extends DataPorts,\n C extends DataPorts,\n D extends DataPorts,\n E extends DataPorts,\n F extends DataPorts,\n >(\n fn1: PipeFunction<A, B> | ITask<A, B>,\n fn2: PipeFunction<B, C> | ITask<B, C>,\n fn3: PipeFunction<C, D> | ITask<C, D>,\n fn4: PipeFunction<D, E> | ITask<D, E>,\n fn5: PipeFunction<E, F> | ITask<E, F>\n ): IWorkflow;\n public static pipe(...args: (PipeFunction | ITask)[]): IWorkflow {\n return pipe(args as any, new Workflow());\n }\n\n public parallel(\n args: (PipeFunction<any, any> | Task)[],\n mergeFn?: CompoundMergeStrategy\n ): IWorkflow {\n return parallel(args, mergeFn ?? PROPERTY_ARRAY, this);\n }\n\n public static parallel(\n args: (PipeFunction<any, any> | ITask)[],\n mergeFn?: CompoundMergeStrategy\n ): IWorkflow {\n return parallel(args, mergeFn ?? PROPERTY_ARRAY, new Workflow());\n }\n\n /**\n * Renames an output of a task to a new target input.\n *\n * @param source - The id of the output to rename\n * @param target - The id of the input to rename to\n * @param indexOrOptions - Either the numeric task index (defaults to `-1`,\n * the last task) or a {@link RenameOptions} bag with `index` and/or\n * `transforms` to apply to the pending dataflow.\n * @returns The current task graph workflow\n */\n public rename(source: string, target: string, index?: number): Workflow;\n public rename(source: string, target: string, options: RenameOptions): Workflow;\n public rename(\n source: string,\n target: string,\n indexOrOptions: number | RenameOptions = -1\n ): Workflow {\n this._builder.rename(source, target, indexOrOptions);\n return this;\n }\n\n /**\n * Adds an error handler task that receives errors from the previous task.\n *\n * When the previous task fails, instead of failing the entire workflow, the\n * error is routed to the handler task via the `[error]` output port. The\n * handler task receives `{ error, errorType }` as input and can produce\n * output that flows to subsequent tasks in the pipeline.\n *\n * @param handler - A task, task class, or pipe function to handle the error\n * @returns The current workflow for chaining\n */\n public onError(handler: Taskish): Workflow {\n this._builder.onError(handler);\n return this;\n }\n\n toTaskGraph(): TaskGraph {\n return this._graph;\n }\n\n toTask(): GraphAsTask {\n const task = new WorkflowTask();\n task.subGraph = this.toTaskGraph();\n return task;\n }\n\n public reset(): Workflow {\n if (this._builder.loopContext) {\n throw new WorkflowError(\"Cannot reset a loop workflow. Call reset() on the parent workflow.\");\n }\n\n this._bridge?.detach();\n this._graph = new TaskGraph({\n outputCache: this._cache.outputCache(),\n });\n this._builder.resetState();\n this._bridge?.attach(this._graph);\n this.events.emit(\"changed\", undefined);\n this.events.emit(\"reset\");\n return this;\n }\n\n public connect(\n sourceTaskId: unknown,\n sourceTaskPortId: string,\n targetTaskId: unknown,\n targetTaskPortId: string\n ): Workflow {\n this._builder.connect(sourceTaskId, sourceTaskPortId, targetTaskId, targetTaskPortId);\n return this;\n }\n\n public addTaskToGraph<\n I extends DataPorts,\n O extends DataPorts,\n C extends TaskConfig<I> = TaskConfig<I>,\n >(taskClass: ITaskConstructor<I, O, C>, config: C): ITask<I, O, C> {\n return this._builder.addTaskInstance<I, O, C>(taskClass, config);\n }\n\n /**\n * Adds a task to the workflow using the same logic as createWorkflow() helpers.\n * Auto-generates an ID, processes pending dataflows, and auto-connects to previous tasks.\n *\n * @param taskClass - The task class to instantiate and add\n * @param input - Optional input values for the task\n * @param config - Optional configuration (id will be auto-generated if not provided)\n * @returns The workflow for chaining\n */\n public addTask<I extends DataPorts, O extends DataPorts, C extends TaskConfig<I> = TaskConfig<I>>(\n taskClass: ITaskConstructor<I, O, C>,\n input?: Partial<I>,\n config?: Partial<C>,\n runConfig?: Partial<IRunConfig>\n ): Workflow<Input, Output> {\n return this._builder.addTaskWithAutoConnect<I, O, C>(\n taskClass,\n input,\n config,\n runConfig\n ) as Workflow<Input, Output>;\n }\n\n // ========================================================================\n // Loop Builder Methods\n // ========================================================================\n\n /**\n * Adds an iterator/loop task to the workflow using the same auto-connect logic\n * as regular task addition (createWorkflow), then returns a new loop builder Workflow.\n *\n * @param taskClass - The iterator task class (MapTask, ReduceTask, etc.)\n * @param config - Optional configuration for the iterator task\n * @returns A new loop builder Workflow for adding tasks inside the loop\n */\n public addLoopTask<\n I extends DataPorts,\n O extends DataPorts,\n C extends TaskConfig<I> = TaskConfig<I>,\n >(\n taskClass: ITaskConstructor<I, O, C>,\n config: Partial<C> = {},\n runConfig?: Partial<IRunConfig>\n ): Workflow<I, O> {\n return this._builder.addLoopTask<I, O, C>(taskClass, config, runConfig);\n }\n\n /**\n * Opens a conditional branch. Returns a {@link ConditionalBuilder} that\n * accepts `.then(taskClass)` and optional `.else(taskClass)` arms and is\n * closed via `.endIf()` to return to this workflow.\n *\n * @example\n * ```ts\n * workflow\n * .if((input) => input.kind === \"text\")\n * .then(TextTask)\n * .else(ImageTask)\n * .endIf();\n * ```\n */\n public if(condition: ConditionFn<TaskInput>): ConditionalBuilder {\n return this._builder.createConditional(condition);\n }\n\n /**\n * Runs deferred auto-connect for a loop task on this (parent) workflow's graph.\n * Called after finalizeTemplate() populates the iterator task's template graph,\n * so that the iterator task's dynamic inputSchema() is available for matching.\n */\n public autoConnectLoopTask(pending?: { parent: ITask; iteratorTask: ITask }): void {\n if (!pending) return;\n const error = runLoopAutoConnect(this._graph, pending);\n if (error) this._builder.setError(error);\n }\n\n public static readonly AutoConnectOptions: unique symbol = Symbol(\"AutoConnectOptions\");\n\n /**\n * Auto-connects two tasks based on their schemas.\n * Uses multiple matching strategies:\n * 1. Match by type AND port name (highest priority)\n * 2. Match by specific type only (format, $id) for unmatched ports\n * 3. Look back through earlier tasks for unmatched required inputs\n *\n * @param graph - The task graph to add dataflows to\n * @param sourceTask - The source task to connect from\n * @param targetTask - The target task to connect to\n * @param options - Optional configuration for the auto-connect operation\n * @returns Result containing matches made, any errors, and unmatched required inputs\n */\n public static autoConnect(\n graph: TaskGraph,\n sourceTask: ITask,\n targetTask: ITask,\n options?: {\n /** Keys of inputs that are already provided and don't need connection */\n readonly providedInputKeys?: Set<string>;\n /** Keys of inputs that are already connected via dataflow (e.g., from rename) and must not be re-matched */\n readonly connectedInputKeys?: Set<string>;\n /** Earlier tasks to search for unmatched required inputs (in reverse chronological order) */\n readonly earlierTasks?: readonly ITask[];\n }\n ): {\n readonly matches: Map<string, string>;\n readonly error?: string;\n readonly unmatchedRequired: readonly string[];\n } {\n return autoConnect(graph, sourceTask, targetTask, options);\n }\n\n /**\n * Finalizes the template graph and sets it on the iterator task.\n * Only applicable in loop builder mode.\n */\n public finalizeTemplate(): void {\n const ctx = this._builder.loopContext;\n if (!ctx) return;\n ctx.finalizeTemplate(this._graph);\n }\n\n /**\n * Finalizes the template graph and returns the parent workflow.\n * Only applicable in loop builder mode.\n *\n * @returns The parent workflow\n * @throws WorkflowError if not in loop builder mode\n */\n public finalizeAndReturn(): Workflow {\n const ctx = this._builder.loopContext;\n if (!ctx) {\n throw new WorkflowError(\"finalizeAndReturn() can only be called on loop workflows\");\n }\n return ctx.finalizeAndReturn(this._graph);\n }\n}\n\n// Placed here (not in WorkflowFactories.ts) so they run after the Workflow class\n// declaration. Static imports in ESM are hoisted and evaluated depth-first, so a\n// side-effect tail import would run before the class binding initializes.\nWorkflow.prototype.group = CreateLoopWorkflow(GraphAsTask);\nWorkflow.prototype.endGroup = CreateEndLoopWorkflow(\"endGroup\");\n",
|
|
40
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport { CycleError } from \"@workglow/util/graph\";\nimport type { DataPortSchema, SchemaNode } from \"@workglow/util/schema\";\nimport { compileSchema } from \"@workglow/util/schema\";\nimport { registerGraphWrapperFactory } from \"../task-graph/Conversions\";\nimport { computeGraphEntitlements } from \"../task-graph/GraphEntitlementUtils\";\nimport { computeGraphInputSchema, computeGraphOutputSchema } from \"../task-graph/GraphSchemaUtils\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport { CompoundMergeStrategy, PROPERTY_ARRAY } from \"../task-graph/TaskGraphRunner\";\nimport type { CreateLoopWorkflow } from \"../task-graph/WorkflowFactories\";\nimport { GraphAsTaskRunner } from \"./GraphAsTaskRunner\";\nimport type { IExecuteContext, IRunConfig } from \"./ITask\";\nimport type { StreamEvent, StreamFinish } from \"./StreamTypes\";\nimport { Task } from \"./Task\";\nimport type { TaskEntitlements } from \"./TaskEntitlements\";\nimport type { TaskEventListener, TaskEvents } from \"./TaskEvents\";\nimport type { JsonTaskItem, TaskGraphItemJson, TaskGraphJsonOptions } from \"./TaskJSON\";\nimport type { TaskConfig, TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\nimport { TaskConfigSchema } from \"./TaskTypes\";\n\nexport const graphAsTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...TaskConfigSchema[\"properties\"],\n compoundMerge: { type: \"string\", \"x-ui-hidden\": true },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type GraphAsTaskConfig<Input extends TaskInput = TaskInput> = TaskConfig<Input> & {\n /** subGraph is extracted in the constructor before validation — not in the JSON schema */\n subGraph?: TaskGraph;\n compoundMerge?: CompoundMergeStrategy;\n};\n\n/**\n * A task that contains a subgraph of tasks\n */\nexport class GraphAsTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends GraphAsTaskConfig<Input> = GraphAsTaskConfig<Input>,\n> extends Task<Input, Output, Config> {\n // ========================================================================\n // Static properties - should be overridden by subclasses\n // ========================================================================\n\n public static override type: TaskTypeName = \"GraphAsTask\";\n public static override title: string = \"Group\";\n public static override description: string = \"A group of tasks that are executed together\";\n public static override category: string = \"Flow Control\";\n public static compoundMerge: CompoundMergeStrategy = PROPERTY_ARRAY;\n\n /** This task has dynamic schemas that change based on the subgraph structure */\n public static override hasDynamicSchemas: boolean = true;\n\n /** Entitlements are always dynamic — they depend on child tasks in the subgraph */\n public static override hasDynamicEntitlements: boolean = true;\n\n // ========================================================================\n // Constructor\n // ========================================================================\n\n /**\n * `subGraph` is extracted from `config` and applied to the instance before\n * validating the remainder of the config.\n */\n constructor(config: Partial<Config> = {}, runConfig: Partial<IRunConfig> = {}) {\n const { subGraph, ...rest } = config;\n super(rest as Partial<Config>, runConfig);\n if (subGraph) {\n this.subGraph = subGraph;\n }\n this.regenerateGraph();\n }\n\n // ========================================================================\n // TaskRunner delegation - Executes and manages the task\n // ========================================================================\n\n declare _runner: GraphAsTaskRunner<Input, Output, Config>;\n\n override get runner(): GraphAsTaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new GraphAsTaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n // ========================================================================\n // Static to Instance conversion methods\n // ========================================================================\n\n public static override configSchema(): DataPortSchema {\n return graphAsTaskConfigSchema;\n }\n\n public get compoundMerge(): CompoundMergeStrategy {\n return this.config?.compoundMerge || (this.constructor as typeof GraphAsTask).compoundMerge;\n }\n\n public override get cacheable(): boolean {\n return (\n this.runConfig?.cacheable ??\n this.config?.cacheable ??\n ((this.constructor as typeof GraphAsTask).cacheable && !this.hasChildren())\n );\n }\n\n // ========================================================================\n // Input/Output handling\n // ========================================================================\n\n /**\n * Override inputSchema to compute it dynamically from the subgraph at runtime.\n * For root tasks (no incoming edges) all input properties are collected.\n * For non-root tasks, only REQUIRED properties that are not satisfied by\n * any internal dataflow are added — this ensures that required inputs are\n * included in the graph's input schema without pulling in every optional\n * downstream property.\n */\n public override inputSchema(): DataPortSchema {\n // If there's no subgraph or it has no children, fall back to the static schema\n if (!this.hasChildren()) {\n return (this.constructor as typeof Task).inputSchema();\n }\n\n return computeGraphInputSchema(this.subGraph);\n }\n\n protected _inputSchemaNode: SchemaNode | undefined;\n protected override getInputSchemaNode(): SchemaNode {\n // every graph as task is different, so we need to compile the schema for each one\n if (!this._inputSchemaNode) {\n try {\n const dataPortSchema = this.inputSchema();\n const schemaNode = Task.generateInputSchemaNode(dataPortSchema);\n this._inputSchemaNode = schemaNode;\n } catch (error) {\n // If compilation fails, fall back to accepting any object structure.\n // This is a safety net for schemas that json-schema-library can't compile.\n getLogger().warn(\n `GraphAsTask \"${this.type}\" (${this.id}): Failed to compile input schema, ` +\n `falling back to permissive validation. Inputs will NOT be validated.`,\n { error, taskType: this.type, taskId: this.id }\n );\n this._inputSchemaNode = compileSchema({});\n }\n }\n return this._inputSchemaNode!;\n }\n\n /**\n * Compute output schema dynamically from the subgraph. Depends on the\n * compoundMerge strategy and the nodes at the last level.\n */\n public override outputSchema(): DataPortSchema {\n // If there's no subgraph or it has no children, fall back to the static schema\n if (!this.hasChildren()) {\n return (this.constructor as typeof Task).outputSchema();\n }\n\n return computeGraphOutputSchema(this.subGraph);\n }\n\n /**\n * Aggregates entitlements from all tasks in the subgraph.\n */\n public override entitlements(): TaskEntitlements {\n if (!this.hasChildren()) {\n return (this.constructor as typeof Task).entitlements();\n }\n return computeGraphEntitlements(this.subGraph);\n }\n\n public override resetInputData(): void {\n super.resetInputData();\n if (this.hasChildren()) {\n this.subGraph!.getTasks().forEach((node) => {\n node.resetInputData();\n });\n this.subGraph!.getDataflows().forEach((dataflow) => {\n dataflow.reset();\n });\n }\n }\n\n // ========================================================================\n // Streaming pass-through\n // ========================================================================\n\n /**\n * Stream pass-through for compound tasks: runs the subgraph and forwards\n * streaming events from ending nodes to the outer graph. Also re-yields\n * any input streams from upstream for cases where this GraphAsTask is\n * itself downstream of another streaming task.\n */\n async *executeStream(input: Input, context: IExecuteContext): AsyncIterable<StreamEvent<Output>> {\n // Forward upstream input streams first (pass-through from outer graph)\n if (context.inputStreams) {\n for (const [, stream] of context.inputStreams) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value.type === \"finish\") continue;\n yield value as StreamEvent<Output>;\n }\n } finally {\n reader.releaseLock();\n }\n }\n }\n\n // Run the subgraph and forward streaming events from ending nodes\n if (this.hasChildren()) {\n const endingNodeIds = new Set<unknown>();\n const tasks = this.subGraph.getTasks();\n for (const task of tasks) {\n if (this.subGraph.getTargetDataflows(task.id).length === 0) {\n endingNodeIds.add(task.id);\n }\n }\n\n const eventQueue: StreamEvent<Output>[] = [];\n let subgraphDone = false;\n\n // Eager promise/resolver — always available for producers to signal.\n // Prevents a race where producers call a stale or undefined resolver,\n // causing the generator to hang on a promise that never resolves.\n // `isWaiting` is true only while the generator is suspended at `await notifyPromise`.\n // `hasPending` records a notification that arrived while the generator was active,\n // so the generator skips the next wait without allocating a new promise.\n let { promise: notifyPromise, resolve: notifyResolve } = Promise.withResolvers<void>();\n let isWaiting = false;\n let hasPending = false;\n const notify = () => {\n if (isWaiting) {\n // Wake the generator and prepare a fresh deferred for the next wait.\n notifyResolve();\n ({ promise: notifyPromise, resolve: notifyResolve } = Promise.withResolvers<void>());\n isWaiting = false;\n } else {\n // Generator is still draining; skip the allocation.\n hasPending = true;\n }\n };\n\n const unsub = this.subGraph.subscribeToTaskStreaming({\n onStreamChunk: (taskId, event) => {\n if (endingNodeIds.has(taskId) && event.type !== \"finish\") {\n eventQueue.push(event as StreamEvent<Output>);\n notify();\n }\n },\n });\n\n const runPromise = this.subGraph\n .run<Output>(input, { parentSignal: context.signal, accumulateLeafOutputs: false })\n .then(\n (results) => {\n subgraphDone = true;\n notify();\n return results;\n },\n (err) => {\n subgraphDone = true;\n notify();\n throw err;\n }\n );\n\n // Yield events as they arrive from ending nodes\n while (!subgraphDone) {\n if (eventQueue.length === 0) {\n if (hasPending) {\n // A notification arrived while we were active; consume it without blocking.\n hasPending = false;\n } else {\n isWaiting = true;\n await notifyPromise;\n }\n }\n while (eventQueue.length > 0) {\n yield eventQueue.shift()!;\n }\n }\n // Drain any remaining events\n while (eventQueue.length > 0) {\n yield eventQueue.shift()!;\n }\n\n unsub();\n\n const results = await runPromise;\n const mergedOutput = this.subGraph.mergeExecuteOutputsToRunOutput(\n results,\n this.compoundMerge\n ) as Output;\n yield { type: \"finish\", data: mergedOutput } as StreamFinish<Output>;\n } else {\n yield { type: \"finish\", data: input as unknown as Output } as StreamFinish<Output>;\n }\n }\n\n // ========================================================================\n // Compound task methods\n // ========================================================================\n\n /**\n * Defensive re-assertion of the DAG invariant for the subgraph. `TaskGraph`\n * already rejects cycle-creating dataflows at `addDataflow` time, but this\n * runs a full topo sort so that any direct `_dag` manipulation or cycle\n * introduced via recursive subgraph composition surfaces here with a clear\n * error rather than deep inside the runner.\n */\n public validateAcyclic(): void {\n if (!this.hasChildren()) return;\n if (!this.subGraph.isAcyclic()) {\n throw new CycleError(\n `${this.type} (${this.id}): subgraph contains a cycle — loop tasks must wrap an acyclic subgraph.`\n );\n }\n for (const child of this.subGraph.getTasks()) {\n if (child instanceof GraphAsTask) {\n child.validateAcyclic();\n }\n }\n }\n\n /**\n * Regenerates the subtask graph and emits a \"regenerate\" event.\n * Subclasses override to implement actual regeneration logic; they only\n * need to call this method to emit the event.\n */\n public override regenerateGraph(): void {\n this._inputSchemaNode = undefined;\n this.events.emit(\"regenerate\");\n this.emitEntitlementChange();\n }\n\n // ========================================================================\n // SubGraph entitlement forwarding\n // ========================================================================\n\n /** Unsubscribe handle for the current subGraph entitlement subscription */\n private _entitlementUnsub: (() => void) | undefined;\n\n /**\n * Guards against re-entry while the synchronous initial emit of\n * `subscribeToTaskEntitlements` is unwinding. Without this, the initial\n * emit's callback re-reads `this.subGraph`, which would re-trigger\n * `_syncSubGraphEntitlementSubscription` before `_entitlementUnsub` has\n * been assigned and loop forever.\n */\n private _subscribingEntitlements: boolean = false;\n\n /**\n * Subscribe to the subGraph's aggregated entitlement changes and forward\n * them as an entitlementChange event on this task so that the parent\n * TaskGraph / Workflow sees the update.\n */\n private _subscribeToSubGraphEntitlements(graph: TaskGraph): void {\n this._entitlementUnsub?.();\n this._entitlementUnsub = undefined;\n this._subscribingEntitlements = true;\n try {\n this._entitlementUnsub = graph.subscribeToTaskEntitlements(() => {\n this.emitEntitlementChange();\n });\n } finally {\n this._subscribingEntitlements = false;\n }\n }\n\n private _syncSubGraphEntitlementSubscription(\n graph: TaskGraph | undefined = this._subGraph\n ): void {\n if (this._subscribingEntitlements) return;\n\n if ((this._events?.listenerCount(\"entitlementChange\") ?? 0) === 0) {\n this._entitlementUnsub?.();\n this._entitlementUnsub = undefined;\n return;\n }\n\n if (!graph || this._entitlementUnsub) {\n return;\n }\n\n this._subscribeToSubGraphEntitlements(graph);\n }\n\n public override subscribe<Event extends TaskEvents>(\n name: Event,\n fn: TaskEventListener<Event>\n ): () => void {\n const unsub = super.subscribe(name, fn);\n if (name !== \"entitlementChange\") {\n return unsub;\n }\n\n this._syncSubGraphEntitlementSubscription();\n\n return () => {\n unsub();\n this._syncSubGraphEntitlementSubscription();\n };\n }\n\n public override on<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n super.on(name, fn);\n if (name === \"entitlementChange\") {\n this._syncSubGraphEntitlementSubscription();\n }\n }\n\n public override off<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n super.off(name, fn);\n if (name === \"entitlementChange\") {\n this._syncSubGraphEntitlementSubscription();\n }\n }\n\n public override once<Event extends TaskEvents>(name: Event, fn: TaskEventListener<Event>): void {\n super.once(name, fn);\n if (name === \"entitlementChange\") {\n this._syncSubGraphEntitlementSubscription();\n }\n }\n\n public override set subGraph(subGraph: TaskGraph) {\n this._entitlementUnsub?.();\n this._entitlementUnsub = undefined;\n super.subGraph = subGraph;\n this._syncSubGraphEntitlementSubscription(subGraph);\n }\n\n override get subGraph(): TaskGraph {\n const graph = super.subGraph;\n // The base getter may have lazily created a new graph — subscribe only when needed.\n this._syncSubGraphEntitlementSubscription(graph);\n return graph;\n }\n\n // ========================================================================\n // Serialization methods\n // ========================================================================\n\n public override toJSON(options?: TaskGraphJsonOptions): TaskGraphItemJson {\n let json = super.toJSON(options);\n const hasChildren = this.hasChildren();\n if (hasChildren) {\n json = {\n ...json,\n merge: this.compoundMerge,\n subgraph: this.subGraph!.toJSON(options),\n };\n }\n return json;\n }\n\n public override toDependencyJSON(options?: TaskGraphJsonOptions): JsonTaskItem {\n const json = this.toJSON(options);\n if (this.hasChildren()) {\n if (\"subgraph\" in json) {\n delete json.subgraph;\n }\n return { ...json, subtasks: this.subGraph!.toDependencyJSON(options) };\n }\n return json;\n }\n}\n\n// ----------------------------------------------------------------------------\n// Wrappers used by ensureTask() to adapt a TaskGraph/Workflow into a task.\n// Defined here (not in Conversions) so they extend GraphAsTask directly with no\n// init-order casts; registered with Conversions' deferred factory seam.\n// ----------------------------------------------------------------------------\n\nclass ListeningGraphAsTask extends GraphAsTask<any, any> {\n constructor(config: any) {\n super(config);\n this.subGraph.on(\"start\", () => {\n this.emit(\"start\");\n });\n this.subGraph.on(\"complete\", () => {\n this.emit(\"complete\");\n });\n this.subGraph.on(\"error\", (e) => {\n this.emit(\"error\", e);\n });\n }\n}\n\nclass OwnGraphTask extends ListeningGraphAsTask {\n public static override readonly type = \"Own[Graph]\";\n}\n\nclass OwnWorkflowTask extends ListeningGraphAsTask {\n public static override readonly type = \"Own[Workflow]\";\n}\n\nclass GraphTask extends GraphAsTask {\n public static override readonly type = \"Graph\";\n}\n\nclass ConvWorkflowTask extends GraphAsTask {\n public static override readonly type = \"Workflow\";\n}\n\nregisterGraphWrapperFactory(({ subGraph, isOwned, isWorkflow, config }) => {\n if (isWorkflow) {\n return isOwned\n ? new OwnWorkflowTask({ ...config, subGraph })\n : new ConvWorkflowTask({ ...config, subGraph });\n }\n return isOwned\n ? new OwnGraphTask({ ...config, subGraph })\n : new GraphTask({ ...config, subGraph });\n});\n\ndeclare module \"../task-graph/Workflow\" {\n interface Workflow {\n /**\n * Starts a group that wraps inner tasks in a GraphAsTask subgraph.\n * Use .endGroup() to close the group and return to the parent workflow.\n */\n group: CreateLoopWorkflow<TaskInput, TaskOutput, GraphAsTaskConfig<TaskInput>>;\n\n /**\n * Ends the group and returns to the parent workflow.\n */\n endGroup(): Workflow;\n }\n}\n\n// Prototype assignments live in Workflow.ts (bottom of file) to avoid\n// circular-dependency issues at module evaluation time.\n",
|
|
41
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { GraphResultArray } from \"../task-graph/TaskGraphRunner\";\nimport type { GraphAsTaskConfig } from \"./GraphAsTask\";\nimport { GraphAsTask } from \"./GraphAsTask\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport { TaskRunner } from \"./TaskRunner\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\n\nexport class GraphAsTaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends GraphAsTaskConfig<Input> = GraphAsTaskConfig<Input>,\n> extends TaskRunner<Input, Output, Config> {\n declare task: GraphAsTask<Input, Output, Config>;\n\n /**\n * Protected method to execute a task subgraph by delegating back to the task itself.\n */\n protected async executeTaskChildren(input: Input): Promise<GraphResultArray<Output>> {\n // Route inner graph_progress through handleProgress so the outer graph's\n // updateProgress callback fires (updating task.progress and re-emitting\n // graph_progress up the chain). A bare emit on the task was silently\n // dropped by the outer TaskGraphRunner, leaving parent progress stuck at\n // the value from whichever task ran before this one. Mirrors the pattern\n // used by FallbackTaskRunner, IteratorTaskRunner, and WhileTask.\n const unsubscribe = this.task.subGraph!.subscribe(\n \"graph_progress\",\n (progress: number | undefined, message?: string, ...args: any[]) => {\n void this.handleProgress(progress, message, ...args);\n }\n );\n const results = await this.task.subGraph!.run<Output>(input, {\n parentSignal: this.currentCtx?.abortController.signal,\n outputCache: this.outputCache,\n registry: this.registry,\n resourceScope: this.resourceScope,\n });\n unsubscribe();\n return results;\n }\n /**\n * Protected method for preview execution delegation\n *\n * For GraphAsTask, we pass the parent's runInputData to the subgraph's runPreview.\n * This ensures that root tasks in the subgraph (like InputTask) receive the\n * parent's input values after resetInputData() is called.\n */\n protected async executeTaskChildrenPreview(): Promise<GraphResultArray<Output>> {\n return this.task.subGraph!.runPreview<Output>(this.task.runInputData, {\n registry: this.registry,\n resourceScope: this.resourceScope,\n });\n }\n\n protected override async handleDisable(ctx: TaskRunContext | undefined): Promise<void> {\n if (this.task.hasChildren()) {\n await this.task.subGraph!.disable();\n }\n await super.handleDisable(ctx);\n }\n\n // ========================================================================\n // TaskRunner method overrides and helpers\n // ========================================================================\n\n /**\n * Execute the task\n */\n protected override async executeTask(\n input: Input,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (this.task.hasChildren()) {\n const runExecuteOutputData = await this.executeTaskChildren(input);\n this.task.runOutputData = this.task.subGraph.mergeExecuteOutputsToRunOutput(\n runExecuteOutputData,\n this.task.compoundMerge\n );\n } else {\n const result = await super.executeTask(input, ctx);\n this.task.runOutputData = result ?? ({} as Output);\n }\n return this.task.runOutputData as Output;\n }\n\n /**\n * Execute the task in preview mode\n */\n public override async executeTaskPreview(\n input: Input,\n ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (this.task.hasChildren()) {\n const previewResults = await this.executeTaskChildrenPreview();\n this.task.runOutputData = this.task.subGraph.mergeExecuteOutputsToRunOutput(\n previewResults,\n this.task.compoundMerge\n );\n return this.task.runOutputData as Output;\n } else {\n const previewResult = await super.executeTaskPreview(input, ctx);\n if (previewResult !== undefined) {\n this.task.runOutputData = previewResult;\n }\n return this.task.runOutputData as Output;\n }\n }\n}\n",
|
|
42
42
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { JsonSchema } from \"@workglow/util/schema\";\nimport type { ITask } from \"../task/ITask\";\nimport { getPortStreamMode } from \"../task/StreamTypes\";\nimport { Task } from \"../task/Task\";\nimport { Dataflow, DATAFLOW_ALL_PORTS } from \"./Dataflow\";\nimport type { TaskGraph } from \"./TaskGraph\";\n\n/**\n * Auto-connects two tasks based on their schemas.\n * Uses multiple matching strategies:\n * 1. Match by type AND port name (highest priority)\n * 2. Match by specific type only (format, $id) for unmatched ports\n * 3. Look back through earlier tasks for unmatched required inputs\n *\n * @param graph - The task graph to add dataflows to\n * @param sourceTask - The source task to connect from\n * @param targetTask - The target task to connect to\n * @param options - Optional configuration for the auto-connect operation\n * @returns Result containing matches made, any errors, and unmatched required inputs\n */\nexport function autoConnect(\n graph: TaskGraph,\n sourceTask: ITask,\n targetTask: ITask,\n options?: {\n /** Keys of inputs that are already provided and don't need connection */\n readonly providedInputKeys?: Set<string>;\n /** Keys of inputs that are already connected via dataflow (e.g., from rename) and must not be re-matched */\n readonly connectedInputKeys?: Set<string>;\n /** Earlier tasks to search for unmatched required inputs (in reverse chronological order) */\n readonly earlierTasks?: readonly ITask[];\n /**\n * When true, skip `graph.addDataflow(...)` side effects and return matches\n * only. Used by callers (e.g. the builder's proximity auto-connect) that\n * need to know what *would* be connected without mutating the graph.\n */\n readonly dryRun?: boolean;\n }\n): {\n readonly matches: Map<string, string>;\n readonly error?: string;\n readonly unmatchedRequired: readonly string[];\n} {\n const matches = new Map<string, string>();\n const sourceSchema = sourceTask.outputSchema();\n const targetSchema = targetTask.inputSchema();\n const providedInputKeys = options?.providedInputKeys ?? new Set<string>();\n const connectedInputKeys = options?.connectedInputKeys ?? new Set<string>();\n const earlierTasks = options?.earlierTasks ?? [];\n const dryRun = options?.dryRun ?? false;\n const addDataflow = (df: Dataflow): void => {\n if (!dryRun) graph.addDataflow(df);\n };\n\n /**\n * Extracts specific type identifiers (format, $id) from a schema,\n * looking inside oneOf/anyOf wrappers if needed.\n */\n const getSpecificTypeIdentifiers = (\n schema: JsonSchema\n ): { formats: Set<string>; ids: Set<string> } => {\n const formats = new Set<string>();\n const ids = new Set<string>();\n\n if (typeof schema === \"boolean\") {\n return { formats, ids };\n }\n\n // Helper to extract from a single schema object\n const extractFromSchema = (s: any): void => {\n if (!s || typeof s !== \"object\" || Array.isArray(s)) return;\n if (s.format) formats.add(s.format);\n if (s.$id) ids.add(s.$id);\n };\n\n // Check top-level format/$id\n extractFromSchema(schema);\n\n // Check inside oneOf/anyOf\n const checkUnion = (schemas: JsonSchema[] | undefined): void => {\n if (!schemas) return;\n for (const s of schemas) {\n if (typeof s === \"boolean\") continue;\n extractFromSchema(s);\n // Also check nested items for array types\n if (s.items && typeof s.items === \"object\" && !Array.isArray(s.items)) {\n extractFromSchema(s.items);\n }\n }\n };\n\n checkUnion(schema.oneOf as JsonSchema[] | undefined);\n checkUnion(schema.anyOf as JsonSchema[] | undefined);\n\n // Check items for array types (single schema, not tuple)\n if (schema.items && typeof schema.items === \"object\" && !Array.isArray(schema.items)) {\n extractFromSchema(schema.items);\n }\n\n return { formats, ids };\n };\n\n /**\n * Checks if output schema type is compatible with input schema type.\n * Handles $id matching, format matching, and oneOf/anyOf unions.\n */\n const isTypeCompatible = (\n fromPortOutputSchema: JsonSchema,\n toPortInputSchema: JsonSchema,\n requireSpecificType: boolean = false\n ): boolean => {\n if (typeof fromPortOutputSchema === \"boolean\" || typeof toPortInputSchema === \"boolean\") {\n return fromPortOutputSchema === true && toPortInputSchema === true;\n }\n\n // Extract specific type identifiers from both schemas\n const outputIds = getSpecificTypeIdentifiers(fromPortOutputSchema);\n const inputIds = getSpecificTypeIdentifiers(toPortInputSchema);\n\n // Check if any format matches\n for (const format of outputIds.formats) {\n if (inputIds.formats.has(format)) {\n return true;\n }\n }\n\n // Check if any $id matches\n for (const id of outputIds.ids) {\n if (inputIds.ids.has(id)) {\n return true;\n }\n }\n\n // For type-only fallback, we require specific types (not primitives)\n // to avoid over-matching strings, numbers, etc.\n if (requireSpecificType) {\n return false;\n }\n\n // $id both blank at top level - check type directly (only for name-matched ports)\n const idTypeBlank =\n fromPortOutputSchema.$id === undefined && toPortInputSchema.$id === undefined;\n if (!idTypeBlank) return false;\n\n // Direct type match (for primitives, only when names also match)\n if (fromPortOutputSchema.type === toPortInputSchema.type) return true;\n\n // Check if output type matches any option in oneOf/anyOf\n const matchesOneOf =\n toPortInputSchema.oneOf?.some((schema: any) => {\n if (typeof schema === \"boolean\") return schema;\n return schema.type === fromPortOutputSchema.type;\n }) ?? false;\n\n const matchesAnyOf =\n toPortInputSchema.anyOf?.some((schema: any) => {\n if (typeof schema === \"boolean\") return schema;\n return schema.type === fromPortOutputSchema.type;\n }) ?? false;\n\n return matchesOneOf || matchesAnyOf;\n };\n\n const makeMatch = (\n fromSchema: JsonSchema,\n toSchema: JsonSchema,\n fromTaskId: unknown,\n toTaskId: unknown,\n comparator: (\n [fromOutputPortId, fromPortOutputSchema]: [string, JsonSchema],\n [toInputPortId, toPortInputSchema]: [string, JsonSchema]\n ) => boolean\n ): void => {\n if (typeof fromSchema === \"object\") {\n if (\n toSchema === true ||\n (typeof toSchema === \"object\" && toSchema.additionalProperties === true)\n ) {\n const outputKeys = Object.keys(fromSchema.properties || {});\n if (outputKeys.length > 0) {\n for (const fromOutputPortId of outputKeys) {\n if (matches.has(fromOutputPortId)) continue;\n matches.set(fromOutputPortId, fromOutputPortId);\n addDataflow(new Dataflow(fromTaskId, fromOutputPortId, toTaskId, fromOutputPortId));\n }\n } else if (fromSchema.additionalProperties === true) {\n // For passthrough tasks with no named output ports, infer output\n // port names from the task's incoming dataflows so the downstream\n // connection is established (e.g. DebugLogTask → OutputTask).\n const sourceGraphTask = graph.getTask(fromTaskId);\n if (\n sourceGraphTask &&\n (sourceGraphTask.constructor as typeof Task).passthroughInputsToOutputs === true\n ) {\n const incomingDfs = graph.getSourceDataflows(fromTaskId);\n for (const df of incomingDfs) {\n const portId = df.targetTaskPortId;\n if (portId === DATAFLOW_ALL_PORTS) continue;\n if (matches.has(portId)) continue;\n if (connectedInputKeys.has(portId)) continue;\n matches.set(portId, portId);\n addDataflow(new Dataflow(fromTaskId, portId, toTaskId, portId));\n }\n }\n }\n return;\n }\n }\n // When source is InputTask/OutputTask (pass-through with additionalProperties),\n // create same-name dataflows for all target input ports\n if (\n typeof fromSchema === \"object\" &&\n fromSchema.additionalProperties === true &&\n typeof toSchema === \"object\" &&\n (sourceTask.type === \"InputTask\" || sourceTask.type === \"OutputTask\")\n ) {\n for (const toInputPortId of Object.keys(toSchema.properties || {})) {\n if (matches.has(toInputPortId)) continue;\n if (connectedInputKeys.has(toInputPortId)) continue;\n matches.set(toInputPortId, toInputPortId);\n addDataflow(new Dataflow(fromTaskId, toInputPortId, toTaskId, toInputPortId));\n }\n return;\n }\n // If either schema is true or false, skip auto-matching\n // as we cannot determine the appropriate connections\n if (typeof fromSchema === \"boolean\" || typeof toSchema === \"boolean\") {\n return;\n }\n\n // Iterate target-first to collect candidates per target port,\n // then apply x-stream tiebreaker when multiple source ports match.\n for (const [toInputPortId, toPortInputSchema] of Object.entries(toSchema.properties || {})) {\n if (matches.has(toInputPortId)) continue;\n // Skip ports already connected via dataflow (e.g., from rename)\n if (connectedInputKeys.has(toInputPortId)) continue;\n\n const candidates: string[] = [];\n for (const [fromOutputPortId, fromPortOutputSchema] of Object.entries(\n fromSchema.properties || {}\n )) {\n if (\n comparator([fromOutputPortId, fromPortOutputSchema], [toInputPortId, toPortInputSchema])\n ) {\n candidates.push(fromOutputPortId);\n }\n }\n\n if (candidates.length === 0) continue;\n\n // Tiebreaker: when multiple source ports match, prefer the one\n // whose x-stream setting matches the target port's x-stream.\n let winner = candidates[0];\n if (candidates.length > 1) {\n const targetStreamMode = getPortStreamMode(toSchema, toInputPortId);\n const streamMatch = candidates.find(\n (portId) => getPortStreamMode(fromSchema, portId) === targetStreamMode\n );\n if (streamMatch) winner = streamMatch;\n }\n\n matches.set(toInputPortId, winner);\n addDataflow(new Dataflow(fromTaskId, winner, toTaskId, toInputPortId));\n }\n };\n\n // Strategy 1: Match by type AND port name (highest priority)\n makeMatch(\n sourceSchema,\n targetSchema,\n sourceTask.id,\n targetTask.id,\n ([fromOutputPortId, fromPortOutputSchema], [toInputPortId, toPortInputSchema]) => {\n const outputPortIdMatch = fromOutputPortId === toInputPortId;\n const outputPortIdOutputInput = fromOutputPortId === \"output\" && toInputPortId === \"input\";\n const portIdsCompatible = outputPortIdMatch || outputPortIdOutputInput;\n\n return portIdsCompatible && isTypeCompatible(fromPortOutputSchema, toPortInputSchema, false);\n }\n );\n\n // Strategy 2: Match by specific type only (fallback for unmatched ports)\n // Only matches specific types like TypedArray (with format), not primitives\n // This allows connecting ports with different names but compatible specific types\n makeMatch(\n sourceSchema,\n targetSchema,\n sourceTask.id,\n targetTask.id,\n ([_fromOutputPortId, fromPortOutputSchema], [_toInputPortId, toPortInputSchema]) => {\n return isTypeCompatible(fromPortOutputSchema, toPortInputSchema, true);\n }\n );\n\n // Strategy 3: Look back through earlier tasks for unmatched required inputs\n // Extract required inputs from target schema\n const requiredInputs = new Set<string>(\n typeof targetSchema === \"object\" ? (targetSchema.required as string[]) || [] : []\n );\n\n // Filter out required inputs that are already provided in the input parameter\n // or already connected via dataflow (e.g., from rename)\n const requiredInputsNeedingConnection = [...requiredInputs].filter(\n (r) => !providedInputKeys.has(r) && !connectedInputKeys.has(r)\n );\n\n // Compute unmatched required inputs (that aren't already provided)\n let unmatchedRequired = requiredInputsNeedingConnection.filter((r) => !matches.has(r));\n\n // If there are unmatched required inputs, iterate through earlier tasks\n if (unmatchedRequired.length > 0 && earlierTasks.length > 0) {\n for (let i = 0; i < earlierTasks.length && unmatchedRequired.length > 0; i++) {\n const earlierTask = earlierTasks[i];\n const earlierOutputSchema = earlierTask.outputSchema();\n\n // When earlier task is InputTask (pass-through), satisfy unmatched\n // required inputs. If the InputTask has an explicitly defined schema\n // (x-ui-manual), only connect ports that exist in its schema.\n // Otherwise, treat it as a universal provider.\n if (earlierTask.type === \"InputTask\") {\n const inputConfig = earlierTask.config;\n const inputSchema = inputConfig?.inputSchema ?? inputConfig?.outputSchema;\n const isManualSchema =\n inputSchema &&\n typeof inputSchema === \"object\" &&\n (inputSchema as Record<string, unknown>)[\"x-ui-manual\"] === true;\n const inputProperties =\n isManualSchema &&\n inputSchema &&\n typeof inputSchema === \"object\" &&\n \"properties\" in inputSchema &&\n inputSchema.properties &&\n typeof inputSchema.properties === \"object\"\n ? new Set(Object.keys(inputSchema.properties as Record<string, unknown>))\n : undefined;\n\n for (const requiredInputId of [...unmatchedRequired]) {\n if (matches.has(requiredInputId)) continue;\n // If schema is manual, only connect ports that exist in the explicit schema\n if (inputProperties && !inputProperties.has(requiredInputId)) continue;\n matches.set(requiredInputId, requiredInputId);\n addDataflow(\n new Dataflow(earlierTask.id, requiredInputId, targetTask.id, requiredInputId)\n );\n }\n unmatchedRequired = unmatchedRequired.filter((r) => !matches.has(r));\n continue;\n }\n\n // Helper function to match from an earlier task (only for unmatched required inputs)\n const makeMatchFromEarlier = (\n comparator: (\n [fromOutputPortId, fromPortOutputSchema]: [string, JsonSchema],\n [toInputPortId, toPortInputSchema]: [string, JsonSchema]\n ) => boolean\n ): void => {\n if (typeof earlierOutputSchema === \"boolean\" || typeof targetSchema === \"boolean\") {\n return;\n }\n\n for (const [fromOutputPortId, fromPortOutputSchema] of Object.entries(\n earlierOutputSchema.properties || {}\n )) {\n for (const requiredInputId of unmatchedRequired) {\n const toPortInputSchema = (targetSchema.properties as any)?.[requiredInputId];\n if (\n !matches.has(requiredInputId) &&\n toPortInputSchema &&\n comparator(\n [fromOutputPortId, fromPortOutputSchema],\n [requiredInputId, toPortInputSchema]\n )\n ) {\n matches.set(requiredInputId, fromOutputPortId);\n addDataflow(\n new Dataflow(earlierTask.id, fromOutputPortId, targetTask.id, requiredInputId)\n );\n }\n }\n }\n };\n\n // Try both matching strategies for earlier tasks\n // Strategy 1: Match by type AND port name\n makeMatchFromEarlier(\n ([fromOutputPortId, fromPortOutputSchema], [toInputPortId, toPortInputSchema]) => {\n const outputPortIdMatch = fromOutputPortId === toInputPortId;\n const outputPortIdOutputInput =\n fromOutputPortId === \"output\" && toInputPortId === \"input\";\n const portIdsCompatible = outputPortIdMatch || outputPortIdOutputInput;\n\n return (\n portIdsCompatible && isTypeCompatible(fromPortOutputSchema, toPortInputSchema, false)\n );\n }\n );\n\n // Strategy 2: Match by specific type only\n makeMatchFromEarlier(\n ([_fromOutputPortId, fromPortOutputSchema], [_toInputPortId, toPortInputSchema]) => {\n return isTypeCompatible(fromPortOutputSchema, toPortInputSchema, true);\n }\n );\n\n // Update unmatched required inputs\n unmatchedRequired = unmatchedRequired.filter((r) => !matches.has(r));\n }\n }\n\n // Determine if there's an error\n const stillUnmatchedRequired = requiredInputsNeedingConnection.filter((r) => !matches.has(r));\n\n if (stillUnmatchedRequired.length > 0) {\n return {\n matches,\n error:\n `Could not find matches for required inputs [${stillUnmatchedRequired.join(\", \")}] of ${targetTask.type}. ` +\n `Attempted to match from ${sourceTask.type} and earlier tasks.`,\n unmatchedRequired: stillUnmatchedRequired,\n };\n }\n\n if (matches.size === 0 && requiredInputsNeedingConnection.length === 0) {\n // No matches were made AND no required inputs need connection\n // This happens in several cases:\n // 1. Task has required inputs, but they were all provided as parameters\n // 2. Task has no required inputs (all optional)\n // 3. Task is already connected via other means (rename, manual connect)\n\n // If the target already has incoming connections (from rename, etc.),\n // consider it already connected and allow the task\n const existingTargetConnections = graph.getSourceDataflows(targetTask.id);\n if (existingTargetConnections.length > 0) {\n return { matches, unmatchedRequired: [] };\n }\n\n // If task has required inputs that were all provided as parameters, allow the task\n const hasRequiredInputs = requiredInputs.size > 0;\n const allRequiredInputsProvided =\n hasRequiredInputs && [...requiredInputs].every((r) => providedInputKeys.has(r));\n\n // If no required inputs (all optional), check if there are defaults\n const hasInputsWithDefaults =\n typeof targetSchema === \"object\" &&\n targetSchema.properties &&\n Object.values(targetSchema.properties).some(\n (prop: any) => prop && typeof prop === \"object\" && \"default\" in prop\n );\n\n // Allow if:\n // - All required inputs were provided as parameters, OR\n // - No required inputs and task has defaults\n // Otherwise fail (no required inputs, no defaults, no matches)\n if (!allRequiredInputsProvided && !hasInputsWithDefaults) {\n return {\n matches,\n error:\n `Could not find a match between the outputs of ${sourceTask.type} and the inputs of ${targetTask.type}. ` +\n `You may need to connect the outputs to the inputs via connect() manually.`,\n unmatchedRequired: [],\n };\n }\n }\n\n return {\n matches,\n unmatchedRequired: [],\n };\n}\n",
|
|
43
43
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger } from \"@workglow/util\";\nimport type { GraphAsTask } from \"../task/GraphAsTask\";\nimport type { ITask } from \"../task/ITask\";\nimport { autoConnect } from \"./autoConnect\";\nimport type { TaskGraph } from \"./TaskGraph\";\nimport type { Workflow } from \"./Workflow\";\n\n/**\n * @internal\n */\nexport interface PendingLoopConnect {\n readonly parent: ITask;\n readonly iteratorTask: ITask;\n}\n\n/**\n * @internal\n * Runs deferred auto-connect for a loop iterator task on the parent\n * workflow's graph. Extracted as a free function so it can be invoked\n * from both {@link LoopBuilderContext.consumePendingConnect} and from\n * the parent {@link Workflow}'s public delegate method (the parent is\n * not itself in loop-builder mode and has no context of its own).\n *\n * Returns the error message if auto-connect failed, otherwise undefined.\n * On failure the iterator task is removed from the parent graph; the\n * caller is responsible for surfacing the error onto the parent\n * workflow's `.error` (matches the non-loop auto-connect path).\n */\nexport function runLoopAutoConnect(\n parentGraph: TaskGraph,\n pending: PendingLoopConnect\n): string | undefined {\n const { parent, iteratorTask } = pending;\n if (parentGraph.getTargetDataflows(parent.id).length !== 0) return undefined;\n\n const nodes = parentGraph.getTasks();\n const parentIndex = nodes.findIndex((n) => n.id === parent.id);\n const earlierTasks: ITask[] = [];\n for (let i = parentIndex - 1; i >= 0; i--) {\n earlierTasks.push(nodes[i]);\n }\n\n const result = autoConnect(parentGraph, parent, iteratorTask, { earlierTasks });\n if (result.error) {\n const message = result.error + \" Task not added.\";\n getLogger().error(message);\n parentGraph.removeTask(iteratorTask.id);\n return message;\n }\n return undefined;\n}\n\n/**\n * @internal\n * Holds the parent <-> child relationship for a Workflow operating in\n * loop-builder mode (created by parent.addLoopTask). Owns deferred\n * auto-connect state. Has no events, no DSL.\n */\nexport class LoopBuilderContext {\n public readonly parent: Workflow;\n public readonly iteratorTask: GraphAsTask;\n public pendingLoopConnect?: PendingLoopConnect;\n\n constructor(parent: Workflow, iteratorTask: GraphAsTask) {\n this.parent = parent;\n this.iteratorTask = iteratorTask;\n }\n\n /**\n * Promotes a populated child template graph into the iterator task's\n * subGraph. No-op on empty graphs.\n */\n public finalizeTemplate(childGraph: TaskGraph): void {\n if (childGraph.getTasks().length === 0) return;\n this.iteratorTask.subGraph = childGraph;\n this.iteratorTask.validateAcyclic();\n }\n\n /**\n * Runs auto-connect for the pending loop connect (if any), then clears it.\n * Returns the error message if auto-connect failed, otherwise undefined,\n * so the caller can propagate the failure to the parent workflow's `.error`.\n */\n public consumePendingConnect(): string | undefined {\n const pending = this.pendingLoopConnect;\n if (!pending) return undefined;\n const error = runLoopAutoConnect(this.parent.graph, pending);\n this.pendingLoopConnect = undefined;\n return error;\n }\n\n /**\n * Finalizes the template and returns the parent workflow. Any deferred\n * auto-connect error is surfaced onto the parent's `.error` to match the\n * non-loop auto-connect path.\n */\n public finalizeAndReturn(childGraph: TaskGraph): Workflow {\n this.finalizeTemplate(childGraph);\n const error = this.consumePendingConnect();\n if (error) this.parent.builder.setError(error);\n return this.parent;\n }\n}\n",
|
|
44
44
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { getLogger, ServiceRegistry, uuid4 } from \"@workglow/util\";\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport type { ConditionFn } from \"../task/ConditionalTask\";\nimport { GraphAsTask } from \"../task/GraphAsTask\";\nimport type { IRunConfig, ITask, ITaskConstructor } from \"../task/ITask\";\nimport { WorkflowError } from \"../task/TaskError\";\nimport type { DataPorts, TaskConfig, TaskInput } from \"../task/TaskTypes\";\nimport { autoConnect } from \"./autoConnect\";\nimport { ConditionalBuilder } from \"./ConditionalBuilder\";\nimport type { Taskish } from \"./Conversions\";\nimport { ensureTask } from \"./Conversions\";\nimport { Dataflow, DATAFLOW_ALL_PORTS, DATAFLOW_ERROR_PORT } from \"./Dataflow\";\nimport { updateBoundaryTaskSchemas } from \"./GraphSchemaUtils\";\nimport { LoopBuilderContext } from \"./LoopBuilderContext\";\nimport type { RenameOptions, Workflow } from \"./Workflow\";\nimport { getLastTask } from \"./WorkflowPipe\";\n\n/**\n * Owns the DSL state machine for a {@link Workflow}: the list of pending\n * dataflows queued by `.rename(...)`, the most recent error string, the\n * optional service registry, and the optional loop-builder context.\n *\n * The {@link Workflow} facade keeps its public method signatures and\n * delegates the implementation here. This split keeps the run/abort/event\n * surface separate from the chainable graph-construction surface.\n */\n\n/**\n * Narrowed handle returned by `Workflow.builder`. Exposes only the two\n * members other in-package code legitimately needs to reach across instances\n * (loop-builder wiring + error propagation), keeping `_dataFlows`,\n * `_registry`, and other builder internals out of reach via the facade.\n * @internal\n */\nexport interface IWorkflowBuilderHandle {\n readonly loopContext: LoopBuilderContext | undefined;\n setError(message: string): void;\n}\n\nexport class WorkflowBuilder implements IWorkflowBuilderHandle {\n private readonly _facade: Workflow<any, any>;\n private _dataFlows: Dataflow[] = [];\n private _error: string = \"\";\n private readonly _registry?: ServiceRegistry;\n private readonly _loopContext?: LoopBuilderContext;\n\n constructor(\n facade: Workflow<any, any>,\n registry?: ServiceRegistry,\n loopContext?: LoopBuilderContext\n ) {\n this._facade = facade;\n this._registry = registry;\n this._loopContext = loopContext;\n }\n\n public get error(): string {\n return this._error;\n }\n\n public get registry(): ServiceRegistry | undefined {\n return this._registry;\n }\n\n public get loopContext(): LoopBuilderContext | undefined {\n return this._loopContext;\n }\n\n /**\n * Surfaces an error onto this builder's error slot. Used by deferred\n * loop-builder auto-connect (which runs from a child Workflow but reports\n * the failure onto the parent's `.error`, matching the non-loop path).\n */\n public setError(message: string): void {\n this._error = message;\n }\n\n /** Clears pending state. Called by the facade's graph setter and reset(). */\n public resetState(): void {\n this._dataFlows = [];\n this._error = \"\";\n }\n\n /**\n * Instantiates a task and adds it to the facade's graph; emits \"changed\".\n * Used both by {@link addTaskWithAutoConnect} and direct callers.\n */\n public addTaskInstance<\n I extends DataPorts,\n O extends DataPorts,\n C extends TaskConfig<I> = TaskConfig<I>,\n >(\n taskClass: ITaskConstructor<I, O, C>,\n config: C,\n runConfig?: Partial<IRunConfig>\n ): ITask<I, O, C> {\n let mergedRunConfig: Partial<IRunConfig> | undefined = runConfig;\n if (this._registry !== undefined) {\n mergedRunConfig = { ...(runConfig ?? {}), registry: this._registry };\n }\n const task = new taskClass(config, mergedRunConfig);\n const id = this._facade.graph.addTask(task);\n this._facade.events.emit(\"changed\", id);\n return task;\n }\n\n /**\n * Adds a task with auto-connect to the previous task. Drains pending\n * dataflows queued by `.rename(...)` first, then runs auto-connect\n * against the immediately-previous task plus earlier tasks for any\n * unmatched required inputs.\n */\n public addTaskWithAutoConnect<\n I extends DataPorts,\n O extends DataPorts,\n C extends TaskConfig<I> = TaskConfig<I>,\n >(\n taskClass: ITaskConstructor<I, O, C>,\n input: Partial<I> = {},\n config: Partial<C> = {},\n runConfig?: Partial<IRunConfig>\n ): Workflow<any, any> {\n this._error = \"\";\n\n const parent = getLastTask(this._facade);\n\n const task = this.addTaskInstance<I, O, C>(\n taskClass,\n {\n id: uuid4(),\n ...config,\n defaults: input,\n } as C,\n runConfig\n );\n\n // Process any pending data flows\n if (this._dataFlows.length > 0) {\n this._dataFlows.forEach((dataflow) => {\n const taskSchema = task.inputSchema();\n if (\n (typeof taskSchema !== \"boolean\" &&\n taskSchema.properties?.[dataflow.targetTaskPortId] === undefined &&\n taskSchema.additionalProperties !== true) ||\n (taskSchema === true && dataflow.targetTaskPortId !== DATAFLOW_ALL_PORTS)\n ) {\n this._error = `Input ${dataflow.targetTaskPortId} not found on task ${task.id}`;\n getLogger().error(this._error);\n return;\n }\n\n dataflow.targetTaskId = task.id;\n this._facade.graph.addDataflow(dataflow);\n });\n\n this._dataFlows = [];\n }\n\n // Auto-connect to parent if needed\n if (parent) {\n // Build the list of earlier tasks (in reverse chronological order)\n const nodes = this._facade.graph.getTasks();\n const parentIndex = nodes.findIndex((n) => n.id === parent.id);\n const earlierTasks: ITask[] = [];\n for (let i = parentIndex - 1; i >= 0; i--) {\n earlierTasks.push(nodes[i]);\n }\n\n const providedInputKeys = new Set(Object.keys(input || {}));\n\n // Ports already connected via pending dataflows (e.g., from .rename())\n // must not be re-matched by auto-connect Strategies 1/2/3.\n const connectedInputKeys = new Set(\n this._facade.graph.getSourceDataflows(task.id).map((df) => df.targetTaskPortId)\n );\n\n const result = autoConnect(this._facade.graph, parent, task, {\n providedInputKeys,\n connectedInputKeys,\n earlierTasks,\n });\n\n if (result.error) {\n // In loop builder mode, don't remove the task - allow manual connection\n // In normal mode, remove the task since auto-connect is required\n if (this._loopContext !== undefined) {\n this._error = result.error;\n getLogger().warn(this._error);\n } else {\n this._error = result.error + \" Task not added.\";\n getLogger().error(this._error);\n this._facade.graph.removeTask(task.id);\n }\n }\n }\n\n // Update InputTask/OutputTask schemas based on connected dataflows\n if (!this._error) {\n updateBoundaryTaskSchemas(this._facade.graph);\n }\n\n return this._facade;\n }\n\n /**\n * Adds an iterator/loop task to the workflow using the same auto-connect\n * logic as {@link addTaskWithAutoConnect}, then returns a new loop-builder\n * Workflow whose template graph the user populates.\n */\n public addLoopTask<\n I extends DataPorts,\n O extends DataPorts,\n C extends TaskConfig<I> = TaskConfig<I>,\n >(\n taskClass: ITaskConstructor<I, O, C>,\n config: Partial<C> = {},\n runConfig?: Partial<IRunConfig>\n ): Workflow<I, O> {\n this._error = \"\";\n\n const parent = getLastTask(this._facade);\n\n // Default maxIterations to \"unbounded\" for loop tasks whose config schema\n // marks it as required (MapTask, WhileTask, ReduceTask, ForEachTask). The\n // raw task constructors still require an explicit value; this default is a\n // convenience only for the fluent Workflow builder API.\n const schema = (\n taskClass as unknown as { configSchema?: () => DataPortSchema }\n ).configSchema?.();\n const required =\n typeof schema === \"object\" && schema !== null\n ? (schema as { required?: readonly string[] }).required\n : undefined;\n const needsMaxIterations = Array.isArray(required) && required.includes(\"maxIterations\");\n const resolvedConfig =\n needsMaxIterations && (config as { maxIterations?: unknown }).maxIterations === undefined\n ? ({ ...config, maxIterations: \"unbounded\" } as Partial<C>)\n : config;\n\n const task = this.addTaskInstance<I, O, C>(\n taskClass,\n { id: uuid4(), ...resolvedConfig } as C,\n runConfig\n );\n\n // Process any pending data flows (same as addTaskWithAutoConnect)\n if (this._dataFlows.length > 0) {\n this._dataFlows.forEach((dataflow) => {\n const taskSchema = task.inputSchema();\n if (\n (typeof taskSchema !== \"boolean\" &&\n taskSchema.properties?.[dataflow.targetTaskPortId] === undefined &&\n taskSchema.additionalProperties !== true) ||\n (taskSchema === true && dataflow.targetTaskPortId !== DATAFLOW_ALL_PORTS)\n ) {\n this._error = `Input ${dataflow.targetTaskPortId} not found on task ${task.id}`;\n getLogger().error(this._error);\n return;\n }\n\n dataflow.targetTaskId = task.id;\n this._facade.graph.addDataflow(dataflow);\n });\n\n this._dataFlows = [];\n }\n\n // Defer auto-connect until endMap/endReduce/endWhile, when the iterator task\n // has its template graph populated and its dynamic inputSchema is available.\n // Store the pending context on the loop builder workflow.\n const FacadeCtor = this._facade.constructor as new (\n cache?: ReturnType<Workflow[\"outputCache\"]>,\n parent?: Workflow,\n iteratorTask?: GraphAsTask,\n registry?: ServiceRegistry\n ) => Workflow<any, any>;\n\n const loopBuilder = new FacadeCtor(\n this._facade.outputCache(),\n this._facade,\n task as unknown as GraphAsTask,\n this._registry\n ) as unknown as Workflow<I, O>;\n\n if (parent) {\n const childCtx = loopBuilder.builder.loopContext;\n if (childCtx) {\n childCtx.pendingLoopConnect = { parent, iteratorTask: task };\n }\n }\n return loopBuilder;\n }\n\n /**\n * Connects outputs to inputs between tasks. Validates source/target\n * schemas before adding the dataflow; throws {@link WorkflowError} on\n * mismatch.\n */\n public connect(\n sourceTaskId: unknown,\n sourceTaskPortId: string,\n targetTaskId: unknown,\n targetTaskPortId: string\n ): void {\n const sourceTask = this._facade.graph.getTask(sourceTaskId);\n const targetTask = this._facade.graph.getTask(targetTaskId);\n\n if (!sourceTask || !targetTask) {\n throw new WorkflowError(\"Source or target task not found\");\n }\n\n const sourceSchema = sourceTask.outputSchema();\n const targetSchema = targetTask.inputSchema();\n\n // Handle boolean schemas\n if (typeof sourceSchema === \"boolean\") {\n if (sourceSchema === false) {\n throw new WorkflowError(`Source task has schema 'false' and outputs nothing`);\n }\n // If sourceSchema is true, we skip validation as it accepts everything\n } else if (!sourceSchema.properties?.[sourceTaskPortId]) {\n throw new WorkflowError(`Output ${sourceTaskPortId} not found on source task`);\n }\n\n if (typeof targetSchema === \"boolean\") {\n if (targetSchema === false) {\n throw new WorkflowError(`Target task has schema 'false' and accepts no inputs`);\n }\n if (targetSchema === true) {\n // do nothing, we allow additional properties\n }\n } else if (targetSchema.additionalProperties === true) {\n // do nothing, we allow additional properties\n } else if (!targetSchema.properties?.[targetTaskPortId]) {\n throw new WorkflowError(`Input ${targetTaskPortId} not found on target task`);\n }\n\n const dataflow = new Dataflow(sourceTaskId, sourceTaskPortId, targetTaskId, targetTaskPortId);\n this._facade.graph.addDataflow(dataflow);\n }\n\n /**\n * Renames an output of a task, queuing a pending dataflow. The dataflow's\n * target is filled in when the next task is added via\n * {@link addTaskWithAutoConnect}.\n */\n public rename(source: string, target: string, indexOrOptions: number | RenameOptions = -1): void {\n this._error = \"\";\n\n const index =\n typeof indexOrOptions === \"number\" ? indexOrOptions : (indexOrOptions.index ?? -1);\n const transforms = typeof indexOrOptions === \"number\" ? undefined : indexOrOptions.transforms;\n\n const nodes = this._facade.graph.getTasks();\n if (-index > nodes.length) {\n const errorMsg = `Back index greater than number of tasks`;\n this._error = errorMsg;\n getLogger().error(this._error);\n throw new WorkflowError(errorMsg);\n }\n\n const lastNode = nodes[nodes.length + index];\n const outputSchema = lastNode.outputSchema();\n\n // Handle boolean schemas\n if (typeof outputSchema === \"boolean\") {\n if (outputSchema === false && source !== DATAFLOW_ALL_PORTS) {\n const errorMsg = `Task ${lastNode.id} has schema 'false' and outputs nothing`;\n this._error = errorMsg;\n getLogger().error(this._error);\n throw new WorkflowError(errorMsg);\n }\n // If outputSchema is true, we skip validation as it outputs everything\n } else if (!(outputSchema.properties as any)?.[source] && source !== DATAFLOW_ALL_PORTS) {\n const errorMsg = `Output ${source} not found on task ${lastNode.id}`;\n this._error = errorMsg;\n getLogger().error(this._error);\n throw new WorkflowError(errorMsg);\n }\n\n const df = new Dataflow(lastNode.id, source, undefined, target);\n if (transforms && transforms.length > 0) df.setTransforms(transforms);\n this._dataFlows.push(df);\n }\n\n /**\n * Adds an error handler task that receives errors from the previous task.\n * The handler task is wired from the previous task's `[error]` output port\n * to its all-ports input.\n */\n public onError(handler: Taskish): void {\n this._error = \"\";\n\n const parent = getLastTask(this._facade);\n if (!parent) {\n this._error = \"onError() requires a preceding task in the workflow\";\n getLogger().error(this._error);\n throw new WorkflowError(this._error);\n }\n\n const handlerTask = ensureTask(handler);\n this._facade.graph.addTask(handlerTask);\n\n // Connect the previous task's error output port to the handler's all-ports input\n const dataflow = new Dataflow(\n parent.id,\n DATAFLOW_ERROR_PORT,\n handlerTask.id,\n DATAFLOW_ALL_PORTS\n );\n this._facade.graph.addDataflow(dataflow);\n this._facade.events.emit(\"changed\", handlerTask.id);\n }\n\n /** Removes the last task from the graph. */\n public pop(): void {\n this._error = \"\";\n const nodes = this._facade.graph.getTasks();\n\n if (nodes.length === 0) {\n this._error = \"No tasks to remove\";\n getLogger().error(this._error);\n return;\n }\n\n const lastNode = nodes[nodes.length - 1];\n this._facade.graph.removeTask(lastNode.id);\n }\n\n /** Opens a conditional branch builder rooted at the facade. */\n public createConditional(condition: ConditionFn<TaskInput>): ConditionalBuilder {\n return new ConditionalBuilder(this._facade, condition);\n }\n}\n",
|
|
@@ -59,8 +59,6 @@
|
|
|
59
59
|
"/**\n * @license Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { TransformRegistry } from \"../TransformRegistry\";\nimport { coalesceTransform } from \"./coalesce\";\nimport { isoDateToUnixTransform, unixToIsoDateTransform } from \"./date-conversions\";\nimport { indexTransform } from \"./index-access\";\nimport { pickTransform } from \"./pick\";\nimport {\n numberToStringTransform,\n parseJsonTransform,\n stringifyTransform,\n toBooleanTransform,\n} from \"./scalar-conversions\";\nimport {\n lowercaseTransform,\n substringTransform,\n truncateTransform,\n uppercaseTransform,\n} from \"./string-casts\";\n\nexport {\n coalesceTransform,\n indexTransform,\n isoDateToUnixTransform,\n lowercaseTransform,\n numberToStringTransform,\n parseJsonTransform,\n pickTransform,\n stringifyTransform,\n substringTransform,\n toBooleanTransform,\n truncateTransform,\n unixToIsoDateTransform,\n uppercaseTransform,\n};\n\n/**\n * Registers all MVP built-in transforms. Separate from registerBaseTasks so\n * consumers can opt in independently (tests may want transforms without\n * task registration and vice versa).\n */\nexport function registerBuiltInTransforms(): void {\n const all = [\n pickTransform,\n indexTransform,\n coalesceTransform,\n uppercaseTransform,\n lowercaseTransform,\n truncateTransform,\n substringTransform,\n unixToIsoDateTransform,\n isoDateToUnixTransform,\n numberToStringTransform,\n toBooleanTransform,\n stringifyTransform,\n parseJsonTransform,\n ];\n for (const t of all) TransformRegistry.registerTransform(t);\n}\n",
|
|
60
60
|
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n *\n * IEntitlementProfile — runtime-environment view of an entitlement system.\n * Extends IEntitlementEnforcer with a single-key request API, change-event\n * subscription, surface introspection, and disposal. Profiles delegate\n * signal observation to a pluggable IEntitlementSignalSource.\n */\n\nimport { createServiceToken } from \"@workglow/util\";\nimport type { EntitlementDenial, IEntitlementEnforcer } from \"./EntitlementEnforcer\";\nimport { createPolicyEnforcer } from \"./EntitlementEnforcer\";\nimport type { EntitlementPolicy } from \"./EntitlementPolicy\";\nimport type { IEntitlementResolver } from \"./EntitlementResolver\";\nimport type { EntitlementGrant, TaskEntitlement } from \"./TaskEntitlements\";\n\n// ========================================================================\n// Signal Source (port)\n// ========================================================================\n\n/**\n * A signal emitted by an external source telling profiles that a permission\n * may have changed.\n *\n * - `revoke`: a previously granted entitlement may now be denied.\n * - `grant`: a previously denied entitlement may now be granted.\n * - `reload`: the underlying policy may have changed in arbitrary ways;\n * profiles should re-evaluate every entitlement they have been queried\n * about.\n */\nexport type EntitlementSignal =\n | { readonly kind: \"revoke\"; readonly entitlement: TaskEntitlement }\n | { readonly kind: \"grant\"; readonly entitlement: TaskEntitlement }\n | { readonly kind: \"reload\" };\n\n/**\n * Pluggable port that produces signals about external permission changes.\n * Built-in profiles default to `STATIC_SIGNAL_SOURCE`. Downstream packages\n * (e.g. workflow-builder Electron) provide implementations that wrap\n * platform events.\n */\nexport interface IEntitlementSignalSource {\n /**\n * Register a listener for signals. The returned function unsubscribes.\n * Implementations must make the unsubscribe idempotent.\n */\n subscribe(listener: (signal: EntitlementSignal) => void): () => void;\n}\n\n/** Frozen no-op signal source. Never emits; subscribe returns a no-op unsub. */\nexport const STATIC_SIGNAL_SOURCE: IEntitlementSignalSource = Object.freeze({\n subscribe(_listener: (signal: EntitlementSignal) => void): () => void {\n return () => {\n // no-op\n };\n },\n});\n\n// ========================================================================\n// Request / Verdict\n// ========================================================================\n\n/**\n * Result of `requestEntitlement(required)`. Discriminated union on `outcome`.\n *\n * Optional entitlements always map to `outcome: \"granted\"` regardless of the\n * underlying policy verdict — matching the rule that optional entitlements\n * are filtered out of `IEntitlementEnforcer.checkAll`.\n *\n * `\"ask\"` policy verdicts are resolved internally via the registered\n * `IEntitlementResolver` before this function returns; callers only ever\n * see `\"granted\"` or `\"denied\"`.\n */\nexport type EntitlementRequestResult =\n | { readonly outcome: \"granted\"; readonly entitlement: TaskEntitlement }\n | { readonly outcome: \"denied\"; readonly denial: EntitlementDenial };\n\n// ========================================================================\n// Change Events\n// ========================================================================\n\n/**\n * Emitted by an `IEntitlementProfile` when a previously-observed entitlement\n * verdict transitions. Profiles only emit events for entitlements whose\n * verdict actually flipped between two queries.\n */\nexport type EntitlementChangeEvent = {\n readonly kind: \"revoked\" | \"granted\";\n readonly entitlement: TaskEntitlement;\n};\n\n// ========================================================================\n// Profile Interface\n// ========================================================================\n\n/**\n * Runtime-environment view of an entitlement system.\n *\n * Extends `IEntitlementEnforcer` with:\n * - `name`: free-form identifier for diagnostics.\n * - `surface()`: maximum set of entitlements this profile may grant.\n * - `requestEntitlement()`: single-key request returning a discriminated verdict.\n * - `subscribe()`: observe change events from the bound signal source.\n * - `dispose()`: idempotent teardown including signal-source unsubscribe.\n */\nexport interface IEntitlementProfile extends IEntitlementEnforcer {\n /** Free-form identifier (e.g. \"browser\", \"desktop\", \"server\"). */\n readonly name: string;\n /**\n * The maximum set of grants this profile may issue.\n *\n * Implementations MAY return a live view of the underlying policy's\n * grant array — callers must not mutate the returned array. Treat the\n * return value as `Readonly<readonly EntitlementGrant[]>` even though\n * `Object.freeze` is not guaranteed.\n */\n surface(): readonly EntitlementGrant[];\n /** Single-key request. See `EntitlementRequestResult`. */\n requestEntitlement(required: TaskEntitlement): Promise<EntitlementRequestResult>;\n /** Subscribe to change events. The returned unsubscribe must be idempotent. */\n subscribe(listener: (event: EntitlementChangeEvent) => void): () => void;\n /** Idempotent teardown. */\n dispose(): Promise<void>;\n}\n\n// ========================================================================\n// Profile Constructor\n// ========================================================================\n\nexport interface CreateProfileOptions {\n readonly resolver?: IEntitlementResolver;\n /** Defaults to `STATIC_SIGNAL_SOURCE`. */\n readonly signalSource?: IEntitlementSignalSource;\n}\n\n/**\n * Build an `IEntitlementProfile` from a policy.\n *\n * Wraps `createPolicyEnforcer` and adds:\n * - `surface()` returning the policy's grants\n * - `requestEntitlement()` reusing `checkAll` for a single entitlement\n * - signal-source subscription with verdict-flip change events\n * - idempotent `dispose()`\n *\n * The \"previously queried\" set used to scope `reload` events is private to\n * the profile and cleared on `dispose`.\n */\nexport function createPolicyProfile(\n name: string,\n policy: EntitlementPolicy,\n options: CreateProfileOptions = {}\n): IEntitlementProfile {\n const enforcer = createPolicyEnforcer(policy, options.resolver);\n const signalSource = options.signalSource ?? STATIC_SIGNAL_SOURCE;\n const listeners = new Set<(event: EntitlementChangeEvent) => void>();\n /**\n * Map from entitlement-id|resources-key → last observed outcome.\n * Used to compute verdict flips for change-event emission and to scope\n * `reload`-triggered re-evaluation.\n */\n const lastOutcome = new Map<string, \"granted\" | \"denied\">();\n /** Reference to the original entitlement object so reload can re-query. */\n const lastEntitlement = new Map<string, TaskEntitlement>();\n let disposed = false;\n\n function key(e: TaskEntitlement): string {\n // JSON.stringify with a sentinel for `undefined` so that we don't conflate\n // `resources: undefined` (broad) with `resources: []` (narrowly empty),\n // and so that resource strings containing commas don't collide.\n const resources = e.resources === undefined ? null : [...e.resources].sort();\n return `${e.id}|${JSON.stringify(resources)}`;\n }\n\n async function evaluate(e: TaskEntitlement): Promise<\"granted\" | \"denied\"> {\n if (e.optional) return \"granted\";\n const denials = await enforcer.checkAll({ entitlements: [e] });\n return denials.length === 0 ? \"granted\" : \"denied\";\n }\n\n async function emitFlipFor(e: TaskEntitlement): Promise<void> {\n const k = key(e);\n const previous = lastOutcome.get(k);\n if (previous === undefined) return; // never queried; nothing to flip\n const current = await evaluate(e);\n if (disposed) return; // dispose() was called while we were awaiting evaluate\n if (current === previous) return;\n lastOutcome.set(k, current);\n const event: EntitlementChangeEvent = {\n kind: current === \"granted\" ? \"granted\" : \"revoked\",\n entitlement: e,\n };\n for (const l of listeners) {\n try {\n l(event);\n } catch (err) {\n // L2 fix: isolate listener failures so one bad listener doesn't\n // prevent later listeners from receiving the event.\n // eslint-disable-next-line no-console\n console.error(`[EntitlementProfile:${name}] listener threw:`, err);\n }\n }\n }\n\n function safeEmitFlipFor(e: TaskEntitlement): void {\n // Signal callbacks run synchronously from the source, so we can't await.\n // Surface evaluation errors via console.error rather than letting them\n // become unhandled promise rejections that may crash the host.\n emitFlipFor(e).catch((err) => {\n // eslint-disable-next-line no-console\n console.error(`[EntitlementProfile:${name}] error evaluating signal:`, err);\n });\n }\n\n const sourceUnsub = signalSource.subscribe((signal) => {\n if (disposed) return;\n if (signal.kind === \"reload\") {\n // Re-evaluate every previously-queried entitlement.\n for (const [, e] of lastEntitlement) {\n safeEmitFlipFor(e);\n }\n } else {\n // revoke or grant: re-evaluate the targeted entitlement.\n safeEmitFlipFor(signal.entitlement);\n }\n });\n\n const profile: IEntitlementProfile = {\n name,\n checkAll: enforcer.checkAll.bind(enforcer),\n checkTask: enforcer.checkTask.bind(enforcer),\n surface: () => policy.grant,\n async requestEntitlement(required) {\n if (required.optional) {\n return { outcome: \"granted\", entitlement: required };\n }\n const denials = await enforcer.checkAll({ entitlements: [required] });\n const k = key(required);\n lastEntitlement.set(k, required);\n if (denials.length === 0) {\n lastOutcome.set(k, \"granted\");\n return { outcome: \"granted\", entitlement: required };\n }\n lastOutcome.set(k, \"denied\");\n return { outcome: \"denied\", denial: denials[0]! };\n },\n subscribe(listener) {\n listeners.add(listener);\n let unsubbed = false;\n return () => {\n if (unsubbed) return;\n unsubbed = true;\n listeners.delete(listener);\n };\n },\n async dispose() {\n if (disposed) return;\n disposed = true;\n sourceUnsub();\n listeners.clear();\n lastOutcome.clear();\n lastEntitlement.clear();\n },\n };\n return profile;\n}\n\n// ========================================================================\n// Service Token\n// ========================================================================\n\n/**\n * Service token for registering an `IEntitlementProfile`.\n *\n * Distinct from `ENTITLEMENT_ENFORCER`: a profile exposes a richer surface\n * (subscribe + dispose + surface). `ServiceRegistry` resolves by token\n * identity, so a registration under `ENTITLEMENT_PROFILE` is NOT\n * automatically visible to consumers resolving `ENTITLEMENT_ENFORCER`.\n *\n * Because `IEntitlementProfile extends IEntitlementEnforcer`, the same\n * profile instance can be registered under both tokens if both consumer\n * styles need to resolve it.\n */\nexport const ENTITLEMENT_PROFILE = createServiceToken<IEntitlementProfile>(\n \"workglow.entitlementProfile\"\n);\n",
|
|
61
61
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n *\n * Pre-built entitlement grant profiles for common runtime environments.\n * The library has no concept of Electron, brands, or deployment targets —\n * only capability profiles expressed as entitlement policies.\n */\n\nimport type { EntitlementPolicy } from \"./EntitlementPolicy\";\nimport {\n createPolicyProfile,\n type CreateProfileOptions,\n type IEntitlementProfile,\n} from \"./EntitlementProfile\";\nimport type { EntitlementGrant } from \"./TaskEntitlements\";\nimport { Entitlements } from \"./TaskEntitlements\";\n\n// ========================================================================\n// Grant Profiles\n// ========================================================================\n\n/**\n * Browser environment grants.\n * No filesystem access, no code execution, no stdio MCP.\n *\n * Network grants are intentionally narrow: `network:http` + `network:websocket`.\n * The broader `network` grant is NOT issued because its hierarchical cover\n * would silently permit `network:private`, undermining SSRF protection.\n * Callers that legitimately need private/loopback access (e.g. a dev server\n * on localhost) must augment the enforcer with a scoped `network:private`\n * grant — see `workflow-builder/packages/app/src/lib/run-workflow.ts`.\n */\nexport const BROWSER_GRANTS: readonly EntitlementGrant[] = [\n { id: Entitlements.NETWORK_HTTP },\n { id: Entitlements.NETWORK_WEBSOCKET },\n { id: Entitlements.AI },\n { id: Entitlements.MCP_TOOL_CALL },\n { id: Entitlements.MCP_RESOURCE_READ },\n { id: Entitlements.MCP_PROMPT_GET },\n { id: Entitlements.STORAGE },\n { id: Entitlements.CREDENTIAL },\n];\n\n/**\n * Desktop environment grants (e.g., Electron with Node.js main process).\n * Adds filesystem, code execution, stdio MCP, and browser control on top of browser grants.\n */\nexport const DESKTOP_GRANTS: readonly EntitlementGrant[] = [\n ...BROWSER_GRANTS,\n { id: Entitlements.FILESYSTEM },\n { id: Entitlements.CODE_EXECUTION },\n { id: Entitlements.MCP_STDIO },\n { id: Entitlements.BROWSER_CONTROL },\n { id: Entitlements.BROWSER_CONTROL_LOCAL },\n { id: Entitlements.BROWSER_CONTROL_NAVIGATE },\n { id: Entitlements.BROWSER_CONTROL_EVALUATE },\n { id: Entitlements.BROWSER_CONTROL_CREDENTIAL },\n];\n\n/**\n * Server environment grants (e.g., cloud deployment).\n * Same as desktop plus BROWSER_CONTROL_CLOUD since server can proxy to cloud providers.\n */\nexport const SERVER_GRANTS: readonly EntitlementGrant[] = [\n ...DESKTOP_GRANTS,\n { id: Entitlements.BROWSER_CONTROL_CLOUD },\n];\n\n// ========================================================================\n// Policy Factory\n// ========================================================================\n\nexport type EntitlementProfile = \"browser\" | \"desktop\" | \"server\";\n\nconst PROFILE_GRANTS: Record<EntitlementProfile, readonly EntitlementGrant[]> = {\n browser: BROWSER_GRANTS,\n desktop: DESKTOP_GRANTS,\n server: SERVER_GRANTS,\n};\n\n/**\n * Creates an entitlement policy for the given runtime profile.\n * The profile's grants become the policy's grant rules.\n * Deny and ask arrays are empty by default — callers can extend the returned policy.\n */\nexport function createProfilePolicy(profile: EntitlementProfile): EntitlementPolicy {\n return { deny: [], grant: PROFILE_GRANTS[profile], ask: [] };\n}\n\n/**\n * Creates an entitlement profile for the given runtime profile.\n * The profile's grants become the policy's grant rules.\n * Deny and ask arrays are empty by default — callers can extend the returned profile.\n *\n * @param profile - The runtime profile to use\n * @param options - Optional resolver (for \"ask\" verdicts) and signal source\n */\nexport function createProfileEnforcer(\n profile: EntitlementProfile,\n options?: CreateProfileOptions\n): IEntitlementProfile {\n return createPolicyProfile(profile, createProfilePolicy(profile), options);\n}\n\n/**\n * Returns the grant list for a given profile.\n * Useful for inspection or combining with additional grants.\n */\nexport function getProfileGrants(profile: EntitlementProfile): readonly EntitlementGrant[] {\n return PROFILE_GRANTS[profile];\n}\n",
|
|
62
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { FallbackTask, FallbackTaskConfig } from \"./FallbackTask\";\nimport { GraphAsTaskRunner } from \"./GraphAsTaskRunner\";\nimport type { ITask } from \"./ITask\";\nimport { TaskAbortedError, TaskFailedError, TaskTimeoutError } from \"./TaskError\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\nimport { TaskStatus } from \"./TaskTypes\";\n\n/**\n * Runner for FallbackTask that executes alternatives sequentially until one succeeds.\n *\n * In **task mode**, each task in the subgraph is tried independently.\n * In **data mode**, the entire subgraph is re-run with different input overrides.\n */\nexport class FallbackTaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends FallbackTaskConfig<Input> = FallbackTaskConfig<Input>,\n> extends GraphAsTaskRunner<Input, Output, Config> {\n declare task: FallbackTask<Input, Output, Config>;\n\n /**\n * Override executeTask to implement sequential fallback logic.\n */\n protected override async executeTask(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (this.task.fallbackMode === \"data\") {\n return this.executeDataFallback(input);\n }\n return this.executeTaskFallback(input);\n }\n\n /**\n * For FallbackTask, preview runs use the task's preview hook only,\n * bypassing GraphAsTaskRunner's child-merging logic.\n */\n public override async executeTaskPreview(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.task.executePreview?.(input, { own: this.own });\n }\n\n // ========================================================================\n // Task Mode: Try each task in the subgraph as an independent alternative\n // ========================================================================\n\n /**\n * Tries each task in the subgraph sequentially. Returns the first\n * successful result. If all fail, throws with collected errors.\n */\n private async executeTaskFallback(input: Input): Promise<Output | undefined> {\n const tasks = this.task.subGraph.getTasks();\n if (tasks.length === 0) {\n throw new TaskFailedError(\"FallbackTask has no alternatives to try\");\n }\n\n const errors: { task: ITask; error: Error }[] = [];\n const totalAttempts = tasks.length;\n\n for (let i = 0; i < tasks.length; i++) {\n if (this.currentCtx?.abortController.signal.aborted) {\n throw new TaskAbortedError(\"Fallback aborted\");\n }\n\n const alternativeTask = tasks[i];\n const attemptNumber = i + 1;\n\n await this.handleProgress(\n Math.round(((i + 0.5) / totalAttempts) * 100),\n `Trying alternative ${attemptNumber}/${totalAttempts}: ${alternativeTask.type}`\n );\n\n try {\n // Reset the task to PENDING so it can be run\n this.resetTask(alternativeTask);\n\n // Run the individual task with the parent's input\n const result = await alternativeTask.run(input);\n\n await this.handleProgress(\n 100,\n `Alternative ${attemptNumber}/${totalAttempts} succeeded: ${alternativeTask.type}`\n );\n\n return result as Output;\n } catch (error) {\n // Aborts (non-timeout) are not retryable — propagate immediately\n if (error instanceof TaskAbortedError && !(error instanceof TaskTimeoutError)) {\n throw error;\n }\n errors.push({ task: alternativeTask, error: error as Error });\n // Continue to next alternative\n }\n }\n\n // All alternatives failed\n throw this.buildAggregateError(errors, \"task\");\n }\n\n // ========================================================================\n // Data Mode: Run the template workflow with different input overrides\n // ========================================================================\n\n /**\n * Runs the subgraph workflow multiple times, each time with a different\n * set of input overrides merged from `config.alternatives`.\n */\n private async executeDataFallback(input: Input): Promise<Output | undefined> {\n const alternatives = this.task.alternatives;\n if (alternatives.length === 0) {\n throw new TaskFailedError(\"FallbackTask has no data alternatives to try\");\n }\n\n const errors: { alternative: Record<string, unknown>; error: Error }[] = [];\n const totalAttempts = alternatives.length;\n\n /**\n * Blend the subgraph's aggregate `graph_progress` with the outer attempt index so\n * nested streaming tasks visibly advance the bar between attempt boundaries. This\n * mirrors the pattern used by {@link IteratorTaskRunner.executeSubgraphIteration}\n * and {@link WhileTask.execute}. Because each attempt resets the subgraph and\n * `graph_progress` starts at 0, the blended value is monotonic across attempts\n * as `currentAttemptIndex` advances.\n */\n let currentAttemptIndex = 0;\n const onSubgraphProgress = (innerProgress: number | undefined, message?: string): void => {\n if (innerProgress === undefined) return;\n const blended = Math.round(\n ((currentAttemptIndex + innerProgress / 100) / totalAttempts) * 100\n );\n void this.handleProgress(\n blended,\n message ?? `Data alternative ${currentAttemptIndex + 1}/${totalAttempts}`\n );\n };\n const unsubscribeSubgraphProgress = this.task.subGraph.subscribe(\n \"graph_progress\",\n onSubgraphProgress\n );\n\n try {\n for (let i = 0; i < alternatives.length; i++) {\n if (this.currentCtx?.abortController.signal.aborted) {\n throw new TaskAbortedError(\"Fallback aborted\");\n }\n\n currentAttemptIndex = i;\n const alternative = alternatives[i];\n const attemptNumber = i + 1;\n\n await this.handleProgress(\n Math.round(((i + 0.5) / totalAttempts) * 100),\n `Trying data alternative ${attemptNumber}/${totalAttempts}`\n );\n\n try {\n // Reset all tasks in the subgraph to PENDING\n this.resetSubgraph();\n\n // Merge the alternative's data with the original input\n const mergedInput = { ...input, ...alternative } as Input;\n\n // Run the subgraph with merged input\n const results = await this.task.subGraph.run<Output>(mergedInput, {\n parentSignal: this.currentCtx?.abortController.signal,\n outputCache: this.outputCache,\n registry: this.registry,\n });\n\n const mergedOutput = this.task.subGraph.mergeExecuteOutputsToRunOutput(\n results,\n this.task.compoundMerge\n ) as Output;\n\n await this.handleProgress(\n 100,\n `Data alternative ${attemptNumber}/${totalAttempts} succeeded`\n );\n\n return mergedOutput as Output;\n } catch (error) {\n // Aborts (non-timeout) are not retryable — propagate immediately\n if (error instanceof TaskAbortedError && !(error instanceof TaskTimeoutError)) {\n throw error;\n }\n errors.push({ alternative, error: error as Error });\n // Continue to next alternative\n }\n }\n } finally {\n unsubscribeSubgraphProgress();\n }\n\n // All alternatives failed\n throw this.buildAggregateError(errors, \"data\");\n }\n\n // ========================================================================\n // Helpers\n // ========================================================================\n\n /**\n * Resets a single task to PENDING status so it can be re-run.\n */\n private resetTask(task: ITask): void {\n task.status = TaskStatus.PENDING;\n task.progress = 0;\n task.error = undefined;\n task.completedAt = undefined;\n task.startedAt = undefined;\n task.resetInputData();\n }\n\n /**\n * Resets all tasks and dataflows in the subgraph for a fresh run.\n */\n private resetSubgraph(): void {\n for (const task of this.task.subGraph.getTasks()) {\n this.resetTask(task);\n }\n for (const dataflow of this.task.subGraph.getDataflows()) {\n dataflow.reset();\n }\n }\n\n /**\n * Builds a descriptive error from all collected failures.\n */\n private buildAggregateError(\n errors: { error: Error; [key: string]: unknown }[],\n mode: \"task\" | \"data\"\n ): TaskFailedError {\n const label = mode === \"task\" ? \"alternative\" : \"data alternative\";\n const details = errors\n .map((e, i) => {\n const prefix = e.error instanceof TaskTimeoutError ? \"[timeout] \" : \"\";\n return ` ${label} ${i + 1}: ${prefix}${e.error.message}`;\n })\n .join(\"\\n\");\n return new TaskFailedError(`All ${errors.length} ${label}s failed:\\n${details}`);\n }\n}\n",
|
|
63
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport { Workflow } from \"../task-graph/Workflow\";\nimport { CreateEndLoopWorkflow, CreateLoopWorkflow } from \"../task-graph/WorkflowFactories\";\nimport { FallbackTaskRunner } from \"./FallbackTaskRunner\";\nimport type { GraphAsTaskConfig } from \"./GraphAsTask\";\nimport { GraphAsTask, graphAsTaskConfigSchema } from \"./GraphAsTask\";\nimport type { TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\n\n/**\n * Execution mode for the fallback task.\n * - `\"task\"`: each task in the subgraph is an independent alternative tried sequentially.\n * - `\"data\"`: the subgraph is a template workflow re-run with each entry in `alternatives`.\n */\nexport type FallbackMode = \"task\" | \"data\";\n\nexport const fallbackTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...graphAsTaskConfigSchema[\"properties\"],\n fallbackMode: { type: \"string\", enum: [\"task\", \"data\"] },\n alternatives: { type: \"array\", items: { type: \"object\", additionalProperties: true } },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type FallbackTaskConfig<Input extends TaskInput = TaskInput> = GraphAsTaskConfig<Input> & {\n /**\n * The fallback execution mode.\n * - `\"task\"`: Try each task in the subgraph as an alternative.\n * - `\"data\"`: Try the template workflow with each set of input overrides.\n * @default \"task\"\n */\n readonly fallbackMode?: FallbackMode;\n\n /**\n * Array of input overrides for data mode.\n * Each entry is merged with the task input before running the template.\n * Only used when `fallbackMode` is `\"data\"`.\n *\n * @example\n * ```typescript\n * alternatives: [\n * { model: \"openai:gpt-4\" },\n * { model: \"anthropic:claude-sonnet-4-20250514\" },\n * { model: \"onnx:Xenova/LaMini-Flan-T5-783M:q8\" },\n * ]\n * ```\n */\n readonly alternatives?: Record<string, unknown>[];\n};\n\n/**\n * Tries multiple alternatives and returns the first successful result.\n *\n * In task mode each child is an independent alternative tried sequentially;\n * in data mode the subgraph is a template re-run with each entry in\n * `alternatives` merged into the input. If all alternatives fail a\n * `TaskFailedError` aggregating each attempt's error is thrown.\n */\nexport class FallbackTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends FallbackTaskConfig<Input> = FallbackTaskConfig<Input>,\n> extends GraphAsTask<Input, Output, Config> {\n // ========================================================================\n // Static properties\n // ========================================================================\n\n public static override type: TaskTypeName = \"FallbackTask\";\n public static override category: string = \"Flow Control\";\n public static override title: string = \"Fallback\";\n public static override description: string = \"Try alternatives until one succeeds\";\n\n public static override hasDynamicSchemas: boolean = true;\n\n public static override configSchema(): DataPortSchema {\n return fallbackTaskConfigSchema;\n }\n\n // ========================================================================\n // TaskRunner Override\n // ========================================================================\n\n declare _runner: FallbackTaskRunner<Input, Output, Config>;\n\n override get runner(): FallbackTaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new FallbackTaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n // ========================================================================\n // Config accessors\n // ========================================================================\n\n public get fallbackMode(): FallbackMode {\n return this.config?.fallbackMode ?? \"task\";\n }\n\n public get alternatives(): Record<string, unknown>[] {\n return this.config?.alternatives ?? [];\n }\n\n // ========================================================================\n // Schema Methods\n // ========================================================================\n\n /**\n * In task mode, input schema is the union of all alternative tasks' inputs.\n * In data mode, input schema comes from the template workflow's starting nodes.\n */\n public override inputSchema(): DataPortSchema {\n if (!this.hasChildren()) {\n return (this.constructor as typeof FallbackTask).inputSchema();\n }\n\n if (this.fallbackMode === \"data\") {\n // Data mode: use the base GraphAsTask logic (union of starting node inputs)\n return super.inputSchema();\n }\n\n // Task mode: union of all tasks' input schemas (they are independent alternatives)\n const properties: Record<string, unknown> = {};\n const tasks = this.subGraph.getTasks();\n\n for (const task of tasks) {\n const taskInputSchema = task.inputSchema();\n if (typeof taskInputSchema === \"boolean\") continue;\n const taskProperties = taskInputSchema.properties || {};\n\n for (const [inputName, inputProp] of Object.entries(taskProperties)) {\n if (!properties[inputName]) {\n properties[inputName] = inputProp;\n }\n }\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: true,\n } as DataPortSchema;\n }\n\n /**\n * Output schema is derived from the first task in the subgraph.\n * All alternatives should produce compatible output.\n */\n public override outputSchema(): DataPortSchema {\n if (!this.hasChildren()) {\n return (this.constructor as typeof FallbackTask).outputSchema();\n }\n\n const tasks = this.subGraph.getTasks();\n if (tasks.length === 0) {\n return { type: \"object\", properties: {}, additionalProperties: false } as DataPortSchema;\n }\n\n if (this.fallbackMode === \"task\") {\n // Task mode: use the first task's output schema (all alternatives should be compatible)\n const firstTask = tasks[0];\n return firstTask.outputSchema();\n }\n\n // Data mode: use the ending nodes' output schema via base class logic\n return super.outputSchema();\n }\n\n // ========================================================================\n // Serialization\n // ========================================================================\n\n public override toJSON() {\n const json = super.toJSON();\n return {\n ...json,\n config: {\n ...(\"config\" in json ? json.config : {}),\n fallbackMode: this.fallbackMode,\n ...(this.alternatives.length > 0 ? { alternatives: this.alternatives } : {}),\n },\n };\n }\n}\n\n// ============================================================================\n// Workflow Prototype Extensions\n// ============================================================================\n\ndeclare module \"../task-graph/Workflow\" {\n interface Workflow {\n /**\n * Starts a task-mode fallback block. Each task added inside the block\n * is an independent alternative tried sequentially until one succeeds.\n * Use `.endFallback()` to close the block and return to the parent workflow.\n */\n fallback: CreateLoopWorkflow<TaskInput, TaskOutput, FallbackTaskConfig<TaskInput>>;\n\n /**\n * Ends the task-mode fallback block and returns to the parent workflow.\n */\n endFallback(): Workflow;\n\n /**\n * Starts a data-mode fallback block. The tasks added inside the block\n * form a template workflow that is re-run with each set of input overrides\n * from `alternatives`. Use `.endFallbackWith()` to close the block.\n *\n * @param alternatives - Array of input override objects to try sequentially\n */\n fallbackWith(alternatives: Record<string, unknown>[]): Workflow;\n\n /**\n * Ends the data-mode fallback block and returns to the parent workflow.\n */\n endFallbackWith(): Workflow;\n }\n}\n\nqueueMicrotask(() => {\n Workflow.prototype.fallback = function (this: Workflow): Workflow {\n return this.addLoopTask(FallbackTask, { fallbackMode: \"task\" });\n };\n Workflow.prototype.endFallback = CreateEndLoopWorkflow(\"endFallback\");\n\n Workflow.prototype.fallbackWith = function (\n this: Workflow,\n alternatives: Record<string, unknown>[]\n ): Workflow {\n return this.addLoopTask(FallbackTask, {\n fallbackMode: \"data\",\n alternatives,\n });\n };\n Workflow.prototype.endFallbackWith = CreateEndLoopWorkflow(\"endFallbackWith\");\n});\n",
|
|
64
62
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { getInputCompactors } from \"@workglow/util\";\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport { getFormatPrefix, getObjectSchema, getSchemaFormat } from \"./InputResolver\";\n\n/**\n * Configuration for the input compactor\n */\nexport interface InputCompactorConfig {\n readonly registry: ServiceRegistry;\n}\n\n/**\n * Checks if a schema allows a string variant, recursively checking\n * through oneOf/anyOf nesting (e.g., TypeSingleOrArray(TypeModel(...))).\n */\nfunction schemaAllowsString(schema: unknown, visited: WeakSet<object> = new WeakSet()): boolean {\n if (typeof schema !== \"object\" || schema === null) return false;\n if (visited.has(schema)) return false;\n visited.add(schema);\n\n const s = schema as Record<string, unknown>;\n\n if (s.type === \"string\") return true;\n\n const variants = (s.oneOf ?? s.anyOf) as unknown[] | undefined;\n if (Array.isArray(variants)) {\n for (const variant of variants) {\n if (schemaAllowsString(variant, visited)) return true;\n }\n }\n\n const allOf = s.allOf as unknown[] | undefined;\n if (Array.isArray(allOf)) {\n for (const sub of allOf) {\n if (schemaAllowsString(sub, visited)) return true;\n }\n }\n\n return false;\n}\n\n/**\n * Compacts resolved inputs by converting instances back to their string IDs.\n * This is the reverse of `resolveSchemaInputs()` — objects with registered\n * compactors are replaced with their string identifier when the schema\n * allows a string variant (oneOf/anyOf with type: \"string\").\n *\n * @param input The task input object with resolved values\n * @param schema The task's input/config schema\n * @param config Configuration including the service registry\n * @returns The input with compacted values (objects replaced with string IDs)\n *\n * @example\n * ```typescript\n * // Compact a resolved model config back to its ID\n * const compacted = await compactSchemaInputs(\n * { model: { model_id: \"gpt-4\", provider: \"openai\", ... } },\n * taskSchema,\n * { registry: globalServiceRegistry }\n * );\n * // compacted.model === \"gpt-4\"\n * ```\n */\nexport async function compactSchemaInputs<T extends Record<string, unknown>>(\n input: T,\n schema: DataPortSchema,\n config: InputCompactorConfig,\n visited: Set<object> = new Set()\n): Promise<T> {\n if (typeof schema === \"boolean\") return input;\n\n const properties = schema.properties;\n if (!properties || typeof properties !== \"object\") return input;\n\n const compactors = getInputCompactors();\n const compacted: Record<string, unknown> = { ...input };\n\n for (const [key, propSchema] of Object.entries(properties)) {\n let value = compacted[key];\n\n const format = getSchemaFormat(propSchema);\n if (format) {\n let compactor = compactors.get(format);\n if (!compactor) {\n const prefix = getFormatPrefix(format);\n compactor = compactors.get(prefix);\n }\n\n if (compactor) {\n // Handle object values: attempt to compact to string ID\n // Only compact if the schema allows a string variant (oneOf/anyOf with type: \"string\")\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n schemaAllowsString(propSchema)\n ) {\n const id = await compactor(value, format, config.registry);\n if (id !== undefined) {\n compacted[key] = id;\n continue; // Replaced with string — skip recursion\n }\n }\n // Handle arrays: compact object elements to strings where possible\n else if (Array.isArray(value)) {\n compacted[key] = await Promise.all(\n value.map(async (item) => {\n if (\n item !== null &&\n item !== undefined &&\n typeof item === \"object\" &&\n !Array.isArray(item)\n ) {\n const id = await compactor(item, format, config.registry);\n return id !== undefined ? id : item;\n }\n return item;\n })\n );\n continue;\n }\n // String values are already compact — pass through\n }\n }\n\n // Recurse into object values that have nested properties in schema\n if (\n value !== null &&\n value !== undefined &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n const objectSchema = getObjectSchema(propSchema);\n if (objectSchema && !visited.has(objectSchema)) {\n visited.add(objectSchema);\n try {\n compacted[key] = await compactSchemaInputs(\n value as Record<string, unknown>,\n objectSchema as DataPortSchema,\n config,\n visited\n );\n } finally {\n visited.delete(objectSchema);\n }\n }\n }\n }\n\n return compacted as T;\n}\n",
|
|
65
63
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { uuid4 } from \"@workglow/util\";\nimport { Dataflow } from \"../task-graph/Dataflow\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport { GraphAsTaskRunner } from \"./GraphAsTaskRunner\";\nimport type { ITaskConstructor } from \"./ITask\";\nimport {\n resolveIterationBound,\n type IterationAnalysisResult,\n type IteratorTask,\n type IteratorTaskConfig,\n} from \"./IteratorTask\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\n\n/**\n * Runner for IteratorTask that executes a single subgraph repeatedly with\n * per-iteration inputs. The task defines iteration analysis/collection hooks,\n * while this runner owns scheduling and execution orchestration.\n */\nexport class IteratorTaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends IteratorTaskConfig<Input> = IteratorTaskConfig<Input>,\n> extends GraphAsTaskRunner<Input, Output, Config> {\n declare task: IteratorTask<Input, Output, Config>;\n\n /** When true, {@link executeSubgraphIteration} folds inner progress into parent MapTask %. */\n private aggregatingParentMapProgress = false;\n private mapPartialProgress: number[] = [];\n private mapPartialIterationCount = 0;\n\n /**\n * For iterator tasks, runPreview() invokes only the task's executePreview hook —\n * it does not iterate the subgraph.\n */\n\n protected override async executeTask(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n let analysis = this.task.analyzeIterationInput(input);\n\n // Enforce maxIterations cap. Config is required (construction-time guard),\n // so the bound is always set; `\"unbounded\"` resolves to Infinity, which\n // leaves the natural array-length count untouched.\n const maxIterations = resolveIterationBound(this.task.config.maxIterations);\n if (analysis.iterationCount > maxIterations) {\n analysis = { ...analysis, iterationCount: maxIterations };\n }\n\n if (analysis.iterationCount === 0) {\n return this.task.getEmptyResult() as Output;\n }\n\n const result = this.task.isReduceTask()\n ? await this.executeReduceIterations(analysis)\n : await this.executeCollectIterations(analysis);\n\n return result as Output;\n }\n\n /**\n * Iterator tasks should only run the task's preview hook here.\n */\n public override async executeTaskPreview(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.task.executePreview?.(input, { own: this.own });\n }\n\n protected async executeCollectIterations(analysis: IterationAnalysisResult): Promise<Output> {\n const iterationCount = analysis.iterationCount;\n const preserveOrder = this.task.preserveIterationOrder();\n\n const batchSize =\n this.task.batchSize !== undefined && this.task.batchSize > 0\n ? this.task.batchSize\n : iterationCount;\n\n const requestedConcurrency = this.task.concurrencyLimit ?? iterationCount;\n const concurrency = Math.max(1, Math.min(requestedConcurrency, iterationCount));\n\n const orderedResults: Array<TaskOutput | undefined> = preserveOrder\n ? new Array(iterationCount)\n : [];\n const completionOrderResults: TaskOutput[] = [];\n\n this.aggregatingParentMapProgress = true;\n this.mapPartialIterationCount = iterationCount;\n this.mapPartialProgress = new Array(iterationCount).fill(0);\n\n try {\n for (let batchStart = 0; batchStart < iterationCount; batchStart += batchSize) {\n if (this.currentCtx?.abortController.signal.aborted) {\n break;\n }\n\n const batchEnd = Math.min(batchStart + batchSize, iterationCount);\n const batchIndices = Array.from(\n { length: batchEnd - batchStart },\n (_, i) => batchStart + i\n );\n\n const batchResults = await this.executeBatch(\n batchIndices,\n analysis,\n iterationCount,\n concurrency,\n undefined\n );\n\n for (const { index, result } of batchResults) {\n if (result === undefined) continue;\n\n if (preserveOrder) {\n orderedResults[index] = result;\n } else {\n completionOrderResults.push(result);\n }\n }\n }\n\n const collected = preserveOrder\n ? orderedResults.filter((result): result is TaskOutput => result !== undefined)\n : completionOrderResults;\n\n return this.task.collectResults(collected);\n } finally {\n this.aggregatingParentMapProgress = false;\n }\n }\n\n /**\n * Updates parent MapTask / workflow progress from per-iteration partial completion (0–100 each).\n */\n private emitMapParentProgressFromPartials(\n childMessage?: string,\n activeIterationIndex?: number\n ): void {\n const n = this.mapPartialIterationCount;\n if (n <= 0) return;\n const sum = this.mapPartialProgress.reduce((a, b) => a + b, 0);\n const overall = Math.round(sum / n);\n const done = this.mapPartialProgress.filter((v) => v >= 100).length;\n const displayIteration =\n activeIterationIndex === undefined ? done : Math.min(activeIterationIndex + 1, n);\n const base = `Map ${displayIteration}/${n}`;\n const msg =\n activeIterationIndex === undefined\n ? `${base} iterations`\n : childMessage\n ? `${base} — ${childMessage}`\n : base;\n void this.handleProgress(overall, msg);\n }\n\n protected async executeReduceIterations(analysis: IterationAnalysisResult): Promise<Output> {\n const iterationCount = analysis.iterationCount;\n let accumulator = this.task.getInitialAccumulator();\n\n for (let index = 0; index < iterationCount; index++) {\n if (this.currentCtx?.abortController.signal.aborted) {\n break;\n }\n\n const iterationInput = this.task.buildIterationRunInput(analysis, index, iterationCount, {\n accumulator,\n });\n\n const iterationResult = await this.executeSubgraphIteration(\n iterationInput,\n index,\n iterationCount\n );\n accumulator = this.task.mergeIterationIntoAccumulator(accumulator, iterationResult, index);\n\n const progress = Math.round(((index + 1) / iterationCount) * 100);\n await this.handleProgress(progress, `Completed ${index + 1}/${iterationCount} iterations`);\n }\n\n return accumulator;\n }\n\n protected async executeBatch(\n indices: number[],\n analysis: IterationAnalysisResult,\n iterationCount: number,\n concurrency: number,\n onItemComplete?: () => Promise<void>\n ): Promise<Array<{ index: number; result: TaskOutput | undefined }>> {\n const results: Array<{ index: number; result: TaskOutput | undefined }> = [];\n let cursor = 0;\n\n const workerCount = Math.max(1, Math.min(concurrency, indices.length));\n\n const workers = Array.from({ length: workerCount }, async () => {\n while (true) {\n if (this.currentCtx?.abortController.signal.aborted) {\n return;\n }\n\n const position = cursor;\n cursor += 1;\n\n if (position >= indices.length) {\n return;\n }\n\n const index = indices[position];\n const iterationInput = this.task.buildIterationRunInput(analysis, index, iterationCount);\n const result = await this.executeSubgraphIteration(iterationInput, index, iterationCount);\n results.push({ index, result });\n await onItemComplete?.();\n }\n });\n\n await Promise.all(workers);\n return results;\n }\n\n /**\n * Clones a TaskGraph by reconstructing each task from its constructor,\n * defaults, and config. This preserves non-serializable config such as\n * function references (e.g. WhileTask condition functions).\n */\n private cloneGraph(graph: TaskGraph): TaskGraph {\n const clone = new TaskGraph();\n const idMap = new Map<unknown, string>();\n for (const task of graph.getTasks()) {\n const ctor = task.constructor as ITaskConstructor<any, any, any>;\n const newId = uuid4();\n idMap.set(task.config.id, newId);\n const clonedConfig = { ...task.config, id: newId };\n const newTask = new ctor({ ...clonedConfig, defaults: task.defaults }, task.runConfig);\n if (task.hasChildren()) {\n newTask.subGraph = this.cloneGraph(task.subGraph);\n }\n clone.addTask(newTask);\n }\n for (const df of graph.getDataflows()) {\n clone.addDataflow(\n new Dataflow(\n idMap.get(df.sourceTaskId) ?? df.sourceTaskId,\n df.sourceTaskPortId,\n idMap.get(df.targetTaskId) ?? df.targetTaskId,\n df.targetTaskPortId\n )\n );\n }\n return clone;\n }\n\n protected async executeSubgraphIteration(\n input: Record<string, unknown>,\n index: number,\n iterationCount: number\n ): Promise<TaskOutput | undefined> {\n if (this.currentCtx?.abortController.signal.aborted) {\n return undefined;\n }\n\n const graphClone = this.cloneGraph(this.task.subGraph);\n\n this.task.emit(\"iteration_start\", index, iterationCount);\n\n /**\n * Subscribe to the iteration subgraph's aggregate `graph_progress` rather than individual\n * task `progress` events. {@link TaskGraphRunner.handleProgress} already averages across\n * only the tasks whose class declares its own `execute` (see `taskPrototypeHasOwnExecute`),\n * so passthrough nodes like `InputTask` — which hit `progress=100` immediately and would\n * otherwise saturate a max-across-tasks partial — are correctly excluded. This mirrors\n * the pattern in {@link GraphAsTaskRunner.executeTaskChildren}, and the `finally` block\n * below bumps the partial to 100 to guarantee completion for degenerate (all-passthrough)\n * subgraphs where `contributors.length === 0`.\n */\n const onGraphProgress = (p: number | undefined, message?: string): void => {\n this.task.emit(\"iteration_progress\", index, iterationCount, p, message);\n if (\n p !== undefined &&\n this.aggregatingParentMapProgress &&\n this.mapPartialIterationCount > 0\n ) {\n this.mapPartialProgress[index] = Math.max(this.mapPartialProgress[index] ?? 0, p);\n this.emitMapParentProgressFromPartials(message, index);\n }\n };\n const unsubscribeGraphProgress = graphClone.subscribe(\"graph_progress\", onGraphProgress);\n\n try {\n const results = await graphClone.run<TaskOutput>(input as TaskInput, {\n parentSignal: this.currentCtx?.abortController.signal,\n outputCache: this.outputCache,\n registry: this.registry,\n resourceScope: this.resourceScope,\n });\n\n if (results.length === 0) {\n return undefined;\n }\n\n return graphClone.mergeExecuteOutputsToRunOutput(\n results,\n this.task.compoundMerge\n ) as TaskOutput;\n } finally {\n unsubscribeGraphProgress();\n if (this.aggregatingParentMapProgress && this.mapPartialIterationCount > 0) {\n this.mapPartialProgress[index] = 100;\n this.emitMapParentProgressFromPartials();\n }\n this.task.emit(\"iteration_complete\", index, iterationCount);\n }\n }\n}\n",
|
|
66
64
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchema, PropertySchema } from \"@workglow/util/schema\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport type { GraphAsTaskConfig } from \"./GraphAsTask\";\nimport { GraphAsTask, graphAsTaskConfigSchema } from \"./GraphAsTask\";\nimport type { IExecuteContext, IRunConfig } from \"./ITask\";\nimport { IteratorTaskRunner } from \"./IteratorTaskRunner\";\nimport type { StreamEvent, StreamFinish } from \"./StreamTypes\";\nimport { TaskConfigurationError } from \"./TaskError\";\nimport type { TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\n\n/**\n * Standard iteration context schema for IteratorTask subclasses (Map, Reduce).\n * Properties are marked with \"x-ui-iteration\": true so the builder\n * knows to hide them from parent-level display.\n */\nexport const ITERATOR_CONTEXT_SCHEMA: DataPortSchema = {\n type: \"object\",\n properties: {\n _iterationIndex: {\n type: \"integer\",\n minimum: 0,\n title: \"Iteration Index\",\n description: \"Current iteration index (0-based)\",\n \"x-ui-iteration\": true,\n },\n _iterationCount: {\n type: \"integer\",\n minimum: 0,\n title: \"Iteration Count\",\n description: \"Total number of iterations\",\n \"x-ui-iteration\": true,\n },\n },\n};\n\n/**\n * Execution mode for iterator tasks.\n * - `parallel`: Execute all iterations concurrently (logical mode)\n * - `parallel-limited`: Execute with a concurrency limit\n */\nexport type ExecutionMode = \"parallel\" | \"parallel-limited\";\n\n/**\n * Input mode for a property in the iteration input schema.\n * - \"array\": Property must be an array (will be iterated)\n * - \"scalar\": Property must be a scalar (constant for all iterations)\n * - \"flexible\": Property accepts both array and scalar (T | T[])\n */\nexport type IterationInputMode = \"array\" | \"scalar\" | \"flexible\";\n\n/**\n * Upper bound for iteration. Either a positive integer or the string\n * sentinel `\"unbounded\"` — which the runner treats as `Number.POSITIVE_INFINITY`.\n * The string form forces every caller to explicitly acknowledge the opt-out\n * instead of silently dropping the safety ceiling.\n */\nexport type IterationBound = number | \"unbounded\";\n\n/**\n * Resolves an IterationBound to a numeric cap the runner can compare against.\n */\nexport function resolveIterationBound(bound: IterationBound): number {\n return bound === \"unbounded\" ? Number.POSITIVE_INFINITY : bound;\n}\n\nexport interface IterationPropertyConfig {\n /** The base schema for the property (without array wrapping) */\n readonly baseSchema: PropertySchema;\n /** The input mode for this property */\n readonly mode: IterationInputMode;\n}\n\nexport const iteratorTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...graphAsTaskConfigSchema[\"properties\"],\n concurrencyLimit: { type: \"integer\", minimum: 1 },\n batchSize: { type: \"integer\", minimum: 1 },\n maxIterations: {\n oneOf: [\n { type: \"integer\", minimum: 1 },\n { type: \"string\", const: \"unbounded\" },\n ],\n },\n iterationInputConfig: { type: \"object\", additionalProperties: true },\n },\n required: [\"maxIterations\"],\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type IteratorTaskConfig<Input extends TaskInput = TaskInput> = GraphAsTaskConfig<Input> & {\n /**\n * Maximum number of concurrent iteration workers\n * @default undefined (unlimited)\n */\n readonly concurrencyLimit?: number;\n\n /**\n * Number of items per batch. When set, iteration indices are grouped into batches.\n * @default undefined\n */\n readonly batchSize?: number;\n\n /**\n * Upper bound on the number of iterations. Required — pass `\"unbounded\"` to\n * explicitly opt out of the safety ceiling, or a positive integer to cap.\n * Prevents runaway iteration on unexpectedly large input arrays.\n */\n readonly maxIterations: IterationBound;\n\n /**\n * User-defined iteration input schema configuration.\n */\n readonly iterationInputConfig?: Record<string, IterationPropertyConfig>;\n};\n\ninterface IteratorPortInfo {\n readonly portName: string;\n readonly itemSchema: DataPortSchema;\n}\n\nexport interface IterationAnalysisResult {\n /** The number of iterations to perform */\n readonly iterationCount: number;\n /** Names of properties that are arrays (to be iterated) */\n readonly arrayPorts: string[];\n /** Names of properties that are scalars (passed as constants) */\n readonly scalarPorts: string[];\n /** Gets the input for a specific iteration index */\n getIterationInput(index: number): Record<string, unknown>;\n}\n\nfunction isArrayVariant(schema: unknown): boolean {\n if (!schema || typeof schema !== \"object\") return false;\n const record = schema as Record<string, unknown>;\n return record.type === \"array\" || record.items !== undefined;\n}\n\nfunction getExplicitIterationFlag(schema: DataPortSchema | undefined): boolean | undefined {\n if (!schema || typeof schema !== \"object\") return undefined;\n const record = schema as Record<string, unknown>;\n const flag = record[\"x-ui-iteration\"];\n if (flag === true) return true;\n if (flag === false) return false;\n return undefined;\n}\n\nfunction inferIterationFromSchema(schema: DataPortSchema | undefined): boolean | undefined {\n if (!schema || typeof schema !== \"object\") return undefined;\n\n const record = schema as Record<string, unknown>;\n\n if (record.type === \"array\" || record.items !== undefined) {\n return true;\n }\n\n const variants = (record.oneOf ?? record.anyOf) as unknown[] | undefined;\n if (!Array.isArray(variants) || variants.length === 0) {\n // Schema does not clearly indicate array/non-array - defer to runtime\n if (record.type !== undefined) {\n return false;\n }\n return undefined;\n }\n\n let hasArrayVariant = false;\n let hasNonArrayVariant = false;\n\n for (const variant of variants) {\n if (isArrayVariant(variant)) {\n hasArrayVariant = true;\n } else {\n hasNonArrayVariant = true;\n }\n }\n\n if (hasArrayVariant && hasNonArrayVariant) return undefined;\n if (hasArrayVariant) return true;\n return false;\n}\n\n/** Creates a union type schema (T | T[]) for flexible iteration input. */\nexport function createFlexibleSchema(baseSchema: PropertySchema): PropertySchema {\n return {\n anyOf: [baseSchema, { type: \"array\", items: baseSchema }],\n } as PropertySchema;\n}\n\nexport function createArraySchema(baseSchema: PropertySchema): PropertySchema {\n return {\n type: \"array\",\n items: baseSchema,\n } as PropertySchema;\n}\n\n/**\n * Extracts the base (scalar) schema from a potentially wrapped schema.\n * Only unwraps flexible schemas (T | T[]) and plain arrays.\n * Preserves discriminated unions (oneOf/anyOf) that aren't flexible wrappers.\n */\nexport function extractBaseSchema(schema: PropertySchema): PropertySchema {\n const schemaType = (schema as Record<string, unknown>).type;\n if (schemaType === \"array\" && (schema as Record<string, unknown>).items) {\n return (schema as Record<string, unknown>).items as PropertySchema;\n }\n\n const variants =\n (schema as Record<string, unknown>).oneOf ?? (schema as Record<string, unknown>).anyOf;\n if (Array.isArray(variants)) {\n // Only unwrap if this is a flexible schema (T | T[]) pattern.\n // Discriminated unions (e.g., oneOf: [string, object]) should be preserved as-is.\n let hasScalar = false;\n let hasArray = false;\n let scalarVariant: PropertySchema | undefined;\n let arrayVariant: PropertySchema | undefined;\n\n for (const variant of variants) {\n if (typeof variant === \"object\") {\n const v = variant as Record<string, unknown>;\n if (v.type === \"array\" || \"items\" in v) {\n hasArray = true;\n arrayVariant = variant as PropertySchema;\n } else {\n hasScalar = true;\n scalarVariant = variant as PropertySchema;\n }\n }\n }\n\n if (hasScalar && hasArray && variants.length === 2) {\n // This is a flexible (T | T[]) wrapper — extract the scalar base\n return scalarVariant!;\n }\n\n if (!hasScalar && hasArray && arrayVariant) {\n // All variants are arrays — extract items from the first array variant\n return (arrayVariant as Record<string, unknown>).items as PropertySchema;\n }\n\n // Not a flexible wrapper — preserve the union as-is\n return schema;\n }\n\n return schema;\n}\n\nexport function schemaAcceptsArray(schema: DataPortSchema): boolean {\n if (typeof schema === \"boolean\") return false;\n\n const schemaType = (schema as Record<string, unknown>).type;\n if (schemaType === \"array\") return true;\n\n const variants = (schema.oneOf ?? schema.anyOf) as DataPortSchema[] | undefined;\n if (Array.isArray(variants)) {\n return variants.some((variant) => isArrayVariant(variant));\n }\n\n return false;\n}\n\nexport abstract class IteratorTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends IteratorTaskConfig<Input> = IteratorTaskConfig<Input>,\n> extends GraphAsTask<Input, Output, Config> {\n public static override type: TaskTypeName = \"IteratorTask\";\n public static override category: string = \"Flow Control\";\n public static override title: string = \"Iterator\";\n public static override description: string = \"Base class for loop-type tasks\";\n\n /** This task has dynamic schemas based on the inner workflow */\n public static override hasDynamicSchemas: boolean = true;\n\n public static override configSchema(): DataPortSchema {\n return iteratorTaskConfigSchema;\n }\n\n constructor(config: Partial<Config> = {}, runConfig: Partial<IRunConfig> = {}) {\n if ((config as Partial<IteratorTaskConfig<Input>>).maxIterations === undefined) {\n throw new TaskConfigurationError(\n `${(new.target as typeof IteratorTask).type ?? \"IteratorTask\"}: maxIterations is required. ` +\n `Pass a positive integer to cap iteration, or \"unbounded\" to opt out explicitly.`\n );\n }\n super(config, runConfig);\n }\n\n /**\n * Returns the schema for iteration-context inputs that will be\n * injected into the subgraph at runtime.\n */\n public static getIterationContextSchema(): DataPortSchema {\n return ITERATOR_CONTEXT_SCHEMA;\n }\n\n /** Cached iterator port info from schema analysis. */\n protected _iteratorPortInfo: IteratorPortInfo | undefined;\n\n /** Cached computed iteration input schema. */\n protected _iterationInputSchema: DataPortSchema | undefined;\n\n // ========================================================================\n // TaskRunner Override\n // ========================================================================\n\n declare _runner: IteratorTaskRunner<Input, Output, Config>;\n\n override get runner(): IteratorTaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new IteratorTaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n /**\n * IteratorTask does not support streaming pass-through because its output\n * is an aggregation of multiple iterations (arrays for MapTask, accumulated\n * value for ReduceTask). The inherited GraphAsTask.executeStream is\n * overridden to just emit a finish event (no streaming).\n */\n override async *executeStream(\n input: Input,\n _context: IExecuteContext\n ): AsyncIterable<StreamEvent<Output>> {\n yield { type: \"finish\", data: input as unknown as Output } as StreamFinish<Output>;\n }\n\n // ========================================================================\n // Graph hooks\n // ========================================================================\n\n override set subGraph(subGraph: TaskGraph) {\n super.subGraph = subGraph;\n this.invalidateIterationInputSchema();\n this.events.emit(\"regenerate\");\n }\n\n override get subGraph(): TaskGraph {\n return super.subGraph;\n }\n\n public override regenerateGraph(): void {\n this.invalidateIterationInputSchema();\n super.regenerateGraph();\n }\n\n // ========================================================================\n // Runner hooks\n // ========================================================================\n\n /**\n * Whether results should be ordered by iteration index.\n * MapTask overrides this to use its `preserveOrder` config.\n */\n public preserveIterationOrder(): boolean {\n return true;\n }\n\n public isReduceTask(): boolean {\n return false;\n }\n\n /** Initial accumulator for reduce mode. */\n public getInitialAccumulator(): Output {\n return {} as Output;\n }\n\n public buildIterationRunInput(\n analysis: IterationAnalysisResult,\n index: number,\n iterationCount: number,\n extraInput: Record<string, unknown> = {}\n ): Record<string, unknown> {\n return {\n ...analysis.getIterationInput(index),\n ...extraInput,\n _iterationIndex: index,\n _iterationCount: iterationCount,\n };\n }\n\n /** Updates the accumulator with one iteration result in reduce mode. */\n public mergeIterationIntoAccumulator(\n accumulator: Output,\n iterationResult: TaskOutput | undefined,\n _index: number\n ): Output {\n return (iterationResult ?? accumulator) as Output;\n }\n\n /** Returns the result when there are no items to iterate. */\n public getEmptyResult(): Output {\n return {} as Output;\n }\n\n /** Collects and merges results from all iterations. */\n public collectResults(results: TaskOutput[]): Output {\n if (results.length === 0) {\n return {} as Output;\n }\n\n const merged: Record<string, unknown[]> = {};\n\n for (const result of results) {\n if (!result || typeof result !== \"object\") continue;\n\n for (const [key, value] of Object.entries(result as Record<string, unknown>)) {\n if (!merged[key]) {\n merged[key] = [];\n }\n merged[key].push(value);\n }\n }\n\n return merged as Output;\n }\n\n // ========================================================================\n // Execution Mode Configuration\n // ========================================================================\n\n public get concurrencyLimit(): number | undefined {\n return this.config.concurrencyLimit;\n }\n\n public get batchSize(): number | undefined {\n return this.config.batchSize;\n }\n\n // ========================================================================\n // Iteration Input Schema Management\n // ========================================================================\n\n public get iterationInputConfig(): Record<string, IterationPropertyConfig> | undefined {\n return this.config.iterationInputConfig;\n }\n\n protected buildDefaultIterationInputSchema(): DataPortSchema {\n const innerSchema = this.getInnerInputSchema();\n if (!innerSchema || typeof innerSchema === \"boolean\") {\n return { type: \"object\", properties: {}, additionalProperties: true };\n }\n\n const properties: Record<string, PropertySchema> = {};\n const innerProps = innerSchema.properties || {};\n\n for (const [key, propSchema] of Object.entries(innerProps)) {\n if (typeof propSchema === \"boolean\") continue;\n\n if ((propSchema as Record<string, unknown>)[\"x-ui-iteration\"]) {\n continue;\n }\n\n const baseSchema = propSchema as PropertySchema;\n properties[key] = createFlexibleSchema(baseSchema);\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: innerSchema.additionalProperties ?? true,\n } as DataPortSchema;\n }\n\n protected buildConfiguredIterationInputSchema(): DataPortSchema {\n const innerSchema = this.getInnerInputSchema();\n if (!innerSchema || typeof innerSchema === \"boolean\") {\n return { type: \"object\", properties: {}, additionalProperties: true };\n }\n\n const config = this.iterationInputConfig || {};\n const properties: Record<string, PropertySchema> = {};\n const innerProps = innerSchema.properties || {};\n\n for (const [key, propSchema] of Object.entries(innerProps)) {\n if (typeof propSchema === \"boolean\") continue;\n\n if ((propSchema as Record<string, unknown>)[\"x-ui-iteration\"]) {\n continue;\n }\n\n const baseSchema = propSchema as PropertySchema;\n const propConfig = config[key];\n\n if (!propConfig) {\n properties[key] = createFlexibleSchema(baseSchema);\n continue;\n }\n\n switch (propConfig.mode) {\n case \"array\":\n properties[key] = createArraySchema(propConfig.baseSchema);\n break;\n case \"scalar\":\n properties[key] = propConfig.baseSchema;\n break;\n case \"flexible\":\n default:\n properties[key] = createFlexibleSchema(propConfig.baseSchema);\n break;\n }\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: innerSchema.additionalProperties ?? true,\n } as DataPortSchema;\n }\n\n /**\n * Derives the schema accepted by each iteration of the inner workflow.\n * For root tasks (no incoming edges) all input properties are collected.\n * For non-root tasks, only REQUIRED properties that are not satisfied by\n * any internal dataflow are added — this ensures that required inputs are\n * included in the iterator's input schema without pulling in every optional\n * downstream property.\n */\n protected getInnerInputSchema(): DataPortSchema | undefined {\n if (!this.hasChildren()) return undefined;\n\n const tasks = this.subGraph.getTasks();\n if (tasks.length === 0) return undefined;\n\n const startingNodes = tasks.filter(\n (task) => this.subGraph.getSourceDataflows(task.id).length === 0\n );\n const sources = startingNodes.length > 0 ? startingNodes : tasks;\n\n const properties: Record<string, DataPortSchema> = {};\n const required: string[] = [];\n let additionalProperties = false;\n\n // Collect all properties from root tasks (original behavior)\n for (const task of sources) {\n const inputSchema = task.inputSchema();\n if (typeof inputSchema === \"boolean\") {\n if (inputSchema === true) {\n additionalProperties = true;\n }\n continue;\n }\n\n additionalProperties = additionalProperties || inputSchema.additionalProperties === true;\n\n for (const [key, prop] of Object.entries(inputSchema.properties || {})) {\n if (typeof prop === \"boolean\") continue;\n if (!properties[key]) {\n properties[key] = prop as DataPortSchema;\n }\n }\n\n for (const key of inputSchema.required || []) {\n if (!required.includes(key)) {\n required.push(key);\n }\n }\n }\n\n // For non-root tasks, collect only REQUIRED properties not satisfied by dataflows.\n // This handles cases like: map().fetch().structuralParser() where structuralParser\n // requires \"title\" but fetch doesn't output it — title must come from the map input.\n const sourceIds = new Set(sources.map((t) => t.id));\n for (const task of tasks) {\n if (sourceIds.has(task.id)) continue;\n\n const inputSchema = task.inputSchema();\n if (typeof inputSchema === \"boolean\") continue;\n\n const requiredKeys = new Set<string>((inputSchema.required as string[] | undefined) || []);\n if (requiredKeys.size === 0) continue;\n\n const connectedPorts = new Set(\n this.subGraph.getSourceDataflows(task.id).map((df) => df.targetTaskPortId)\n );\n\n for (const key of requiredKeys) {\n // Skip if already connected via dataflow or already collected from a root task\n if (connectedPorts.has(key)) continue;\n if (properties[key]) continue;\n\n // Skip if the task already has a default value for this property\n // (e.g., .textEmbedding({ model }) stores model in task.defaults)\n if (task.defaults && task.defaults[key] !== undefined) continue;\n\n const prop = (inputSchema.properties || {})[key];\n if (!prop || typeof prop === \"boolean\") continue;\n\n properties[key] = prop as DataPortSchema;\n if (!required.includes(key)) {\n required.push(key);\n }\n }\n }\n\n return {\n type: \"object\",\n properties,\n ...(required.length > 0 ? { required } : {}),\n additionalProperties,\n } as DataPortSchema;\n }\n\n public getIterationInputSchema(): DataPortSchema {\n if (this._iterationInputSchema) {\n return this._iterationInputSchema;\n }\n\n this._iterationInputSchema = this.iterationInputConfig\n ? this.buildConfiguredIterationInputSchema()\n : this.buildDefaultIterationInputSchema();\n\n return this._iterationInputSchema;\n }\n\n public setIterationInputSchema(schema: DataPortSchema): void {\n this._iterationInputSchema = schema;\n this._inputSchemaNode = undefined;\n this.events.emit(\"regenerate\");\n }\n\n public setPropertyInputMode(\n propertyName: string,\n mode: IterationInputMode,\n baseSchema?: PropertySchema\n ): void {\n const currentSchema = this.getIterationInputSchema();\n if (typeof currentSchema === \"boolean\") return;\n\n const currentProps = (currentSchema.properties || {}) as Record<string, PropertySchema>;\n const existingProp = currentProps[propertyName];\n const base: PropertySchema =\n baseSchema ?? (existingProp ? extractBaseSchema(existingProp) : { type: \"string\" });\n\n let newPropSchema: PropertySchema;\n switch (mode) {\n case \"array\":\n newPropSchema = createArraySchema(base);\n break;\n case \"scalar\":\n newPropSchema = base;\n break;\n case \"flexible\":\n default:\n newPropSchema = createFlexibleSchema(base);\n break;\n }\n\n this._iterationInputSchema = {\n ...currentSchema,\n properties: {\n ...currentProps,\n [propertyName]: newPropSchema,\n },\n } as DataPortSchema;\n\n this._inputSchemaNode = undefined;\n this.events.emit(\"regenerate\");\n }\n\n public invalidateIterationInputSchema(): void {\n this._iterationInputSchema = undefined;\n this._iteratorPortInfo = undefined;\n this._inputSchemaNode = undefined;\n }\n\n // ========================================================================\n // Iteration analysis\n // ========================================================================\n\n /**\n * Analyzes input to determine which ports are iterated vs scalar.\n * Precedence:\n * 1) explicit x-ui-iteration annotation\n * 2) schema inference where deterministic\n * 3) runtime value fallback (Array.isArray)\n */\n public analyzeIterationInput(input: Input): IterationAnalysisResult {\n const inputData = input as Record<string, unknown>;\n const schema = this.hasChildren() ? this.getIterationInputSchema() : this.inputSchema();\n const schemaProps: Record<string, DataPortSchema> =\n typeof schema === \"object\" && schema.properties\n ? (schema.properties as Record<string, DataPortSchema>)\n : {};\n\n const keys = new Set([...Object.keys(schemaProps), ...Object.keys(inputData)]);\n\n const arrayPorts: string[] = [];\n const scalarPorts: string[] = [];\n const iteratedValues: Record<string, unknown[]> = {};\n const arrayLengths: number[] = [];\n\n for (const key of keys) {\n if (key.startsWith(\"_iteration\")) continue;\n\n const value = inputData[key];\n const portSchema = schemaProps[key];\n\n let shouldIterate: boolean;\n\n const explicitFlag = getExplicitIterationFlag(portSchema);\n if (explicitFlag !== undefined) {\n shouldIterate = explicitFlag;\n } else {\n const schemaInference = inferIterationFromSchema(portSchema);\n shouldIterate = schemaInference ?? Array.isArray(value);\n }\n\n if (!shouldIterate) {\n scalarPorts.push(key);\n continue;\n }\n\n if (!Array.isArray(value)) {\n throw new TaskConfigurationError(\n `${this.type}: Input '${key}' is configured for iteration but value is not an array.`\n );\n }\n\n iteratedValues[key] = value;\n arrayPorts.push(key);\n arrayLengths.push(value.length);\n }\n\n if (arrayPorts.length === 0) {\n throw new TaskConfigurationError(\n `${this.type}: At least one array input is required for iteration. ` +\n `Mark a port with x-ui-iteration=true, provide array-typed schema, or pass array values at runtime.`\n );\n }\n\n const uniqueLengths = new Set(arrayLengths);\n if (uniqueLengths.size > 1) {\n const lengthInfo = arrayPorts\n .map((port, index) => `${port}=${arrayLengths[index]}`)\n .join(\", \");\n throw new TaskConfigurationError(\n `${this.type}: All iterated array inputs must have the same length (zip semantics). ` +\n `Found different lengths: ${lengthInfo}`\n );\n }\n\n const iterationCount = arrayLengths[0] ?? 0;\n\n const getIterationInput = (index: number): Record<string, unknown> => {\n const iterInput: Record<string, unknown> = {};\n\n for (const key of arrayPorts) {\n iterInput[key] = iteratedValues[key][index];\n }\n\n for (const key of scalarPorts) {\n if (key in inputData) {\n iterInput[key] = inputData[key];\n }\n }\n\n return iterInput;\n };\n\n return {\n iterationCount,\n arrayPorts,\n scalarPorts,\n getIterationInput,\n };\n }\n\n // ========================================================================\n // Schema Methods\n // ========================================================================\n\n public getIterationContextSchema(): DataPortSchema {\n return (this.constructor as typeof IteratorTask).getIterationContextSchema();\n }\n\n public override inputSchema(): DataPortSchema {\n if (this.hasChildren()) {\n return this.getIterationInputSchema();\n }\n return (this.constructor as typeof IteratorTask).inputSchema();\n }\n\n public override outputSchema(): DataPortSchema {\n if (!this.hasChildren()) {\n return (this.constructor as typeof IteratorTask).outputSchema();\n }\n\n return this.getWrappedOutputSchema();\n }\n\n protected getWrappedOutputSchema(): DataPortSchema {\n if (!this.hasChildren()) {\n return { type: \"object\", properties: {}, additionalProperties: false };\n }\n\n const endingNodes = this.subGraph\n .getTasks()\n .filter((task) => this.subGraph.getTargetDataflows(task.id).length === 0);\n\n if (endingNodes.length === 0) {\n return { type: \"object\", properties: {}, additionalProperties: false };\n }\n\n const properties: Record<string, unknown> = {};\n\n for (const task of endingNodes) {\n const taskOutputSchema = task.outputSchema();\n if (typeof taskOutputSchema === \"boolean\") continue;\n\n for (const [key, schema] of Object.entries(taskOutputSchema.properties || {})) {\n properties[key] = {\n type: \"array\",\n items: schema,\n };\n }\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: false,\n } as DataPortSchema;\n }\n}\n",
|
|
@@ -73,13 +71,17 @@
|
|
|
73
71
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n createServiceToken,\n getLogger,\n globalServiceRegistry,\n registerInputCompactor,\n registerInputResolver,\n ServiceRegistry,\n} from \"@workglow/util\";\nimport { validateSchema } from \"@workglow/util/schema\";\nimport type { ITaskConstructor } from \"./ITask\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTaskConstructor = ITaskConstructor<any, any, any>;\n\n/**\n * Map storing all registered task constructors.\n * Keys are task type identifiers and values are their corresponding constructor functions.\n */\nconst taskConstructors = new Map<string, AnyTaskConstructor>();\n\n/**\n * Registers a task constructor with the registry.\n * This allows the task type to be instantiated dynamically based on its type identifier.\n * Re-registering the exact same class is idempotent and does nothing.\n *\n * @param baseClass - The constructor function for the task to register\n * @throws Error if a different constructor is already registered for the same task type.\n * Call {@link unregisterTask} first to replace an existing registration.\n */\nfunction registerTask(baseClass: AnyTaskConstructor): void {\n const existing = taskConstructors.get(baseClass.type);\n if (existing) {\n if (existing === baseClass) return; // same class, idempotent\n throw new Error(\n `Task type \"${baseClass.type}\" is already registered. Unregister it first to replace.`\n );\n }\n taskConstructors.set(baseClass.type, baseClass);\n\n // Validate schemas at registration time (soft — warn only, don't throw)\n const schemas = [\n { name: \"inputSchema\", schema: baseClass.inputSchema() },\n { name: \"outputSchema\", schema: baseClass.outputSchema() },\n ] as const;\n\n for (const { name, schema } of schemas) {\n const result = validateSchema(schema);\n if (!result.valid) {\n const messages = result.errors.map((e) => `${e.path}: ${e.message}`).join(\"; \");\n getLogger().warn(`Task \"${baseClass.type}\" has invalid ${name}: ${messages}`, {\n taskType: baseClass.type,\n schemaName: name,\n errors: result.errors,\n });\n }\n }\n}\n\n/**\n * Removes a task constructor from the registry.\n * Must be called before re-registering a task type with a different constructor.\n *\n * @param type - The task type identifier to remove\n * @returns true if the task type was found and removed, false otherwise\n */\nfunction unregisterTask(type: string): boolean {\n return taskConstructors.delete(type);\n}\n\n/**\n * TaskRegistry provides a centralized registry for task types.\n * It enables dynamic task instantiation and management across the application.\n */\nexport const TaskRegistry = {\n all: taskConstructors,\n registerTask,\n unregisterTask,\n};\n\n// ========================================================================\n// DI-based access\n// ========================================================================\n\n/**\n * Service token for the task constructor registry.\n * Maps task type names to their constructor functions.\n */\nexport const TASK_CONSTRUCTORS =\n createServiceToken<Map<string, AnyTaskConstructor>>(\"task.constructors\");\n\nexport function getGlobalTaskConstructors(): Map<string, AnyTaskConstructor> {\n return globalServiceRegistry.get(TASK_CONSTRUCTORS);\n}\n\n/**\n * Sets the global task constructors map, replacing the default TaskRegistry-backed factory.\n */\nexport function setGlobalTaskConstructors(map: Map<string, AnyTaskConstructor>): void {\n globalServiceRegistry.registerInstance(TASK_CONSTRUCTORS, map);\n}\n\n/**\n * Gets the task constructors map from the given registry,\n * falling back to the global TaskRegistry.\n */\nexport function getTaskConstructors(registry?: ServiceRegistry): Map<string, AnyTaskConstructor> {\n if (!registry) return TaskRegistry.all;\n return registry.has(TASK_CONSTRUCTORS) ? registry.get(TASK_CONSTRUCTORS) : TaskRegistry.all;\n}\n\n// ========================================================================\n// Tasks resolver\n// ========================================================================\n\n/**\n * Resolves a task type name to a tool definition object via the task constructor registry.\n *\n * Used by the input resolver system for `format: \"tasks\"` properties.\n * Converts lightweight string IDs (stored by the property editor) into full\n * tool definition objects at runtime.\n *\n * @param id - Task type name registered in TaskRegistry\n * @param format - The format string (unused)\n * @param registry - Service registry for context-specific lookups\n * @returns Tool definition object, or undefined if the task type is not found\n */\nfunction resolveTaskFromRegistry(\n id: string,\n _format: string,\n registry: ServiceRegistry\n):\n | {\n name: string;\n description: string;\n inputSchema: unknown;\n outputSchema: unknown;\n configSchema?: unknown;\n }\n | undefined {\n const constructors = getTaskConstructors(registry);\n const ctor = constructors.get(id);\n if (!ctor) return undefined;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ctorAny = ctor as any;\n const configSchema =\n typeof ctorAny.configSchema === \"function\" ? ctorAny.configSchema() : undefined;\n return {\n name: ctor.type,\n description: (ctor as { description?: string }).description ?? \"\",\n inputSchema: ctor.inputSchema(),\n outputSchema: ctor.outputSchema(),\n ...(configSchema ? { configSchema } : {}),\n };\n}\n\nfunction compactTask(\n value: unknown,\n _format: string,\n registry: ServiceRegistry\n): string | undefined {\n if (typeof value === \"object\" && value !== null && \"name\" in value) {\n const name = (value as Record<string, unknown>).name;\n if (typeof name !== \"string\") return undefined;\n const constructors = getTaskConstructors(registry);\n const ctor = constructors.get(name);\n return ctor ? name : undefined;\n }\n return undefined;\n}\n\n/**\n * Registers the task constructor map default factory and the \"tasks\" input resolver/compactor\n * on the given registry. Called by `bootstrapWorkglow` and `createOrchestrationContext`.\n */\nexport function registerTaskDefaults(registry: ServiceRegistry = globalServiceRegistry): void {\n registry.registerIfAbsent(\n TASK_CONSTRUCTORS,\n (): Map<string, AnyTaskConstructor> => TaskRegistry.all,\n true\n );\n registerInputResolver(\"tasks\", resolveTaskFromRegistry, registry);\n registerInputCompactor(\"tasks\", compactTask, registry);\n}\n\n// Self-register on the global registry. Idempotent.\nregisterTaskDefaults();\n",
|
|
74
72
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { Dataflow } from \"../task-graph/Dataflow\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport { CompoundMergeStrategy } from \"../task-graph/TaskGraphRunner\";\nimport type { ITransformStep } from \"../task-graph/TransformTypes\";\nimport { TaskConfigurationError, TaskJSONError } from \"../task/TaskError\";\nimport { getTaskConstructors } from \"../task/TaskRegistry\";\nimport { ConditionalTaskConfig } from \"./ConditionalTask\";\nimport { GraphAsTask, GraphAsTaskConfig } from \"./GraphAsTask\";\nimport { IteratorTaskConfig } from \"./IteratorTask\";\nimport { MapTaskConfig } from \"./MapTask\";\nimport { ReduceTaskConfig } from \"./ReduceTask\";\nimport { TaskConfig, TaskInput } from \"./TaskTypes\";\nimport { WhileTaskConfig } from \"./WhileTask\";\n\n// ========================================================================\n// JSON Serialization Types\n// ========================================================================\n\nexport type JsonTaskConfig = Omit<\n TaskConfig &\n GraphAsTaskConfig &\n WhileTaskConfig &\n IteratorTaskConfig &\n ReduceTaskConfig &\n MapTaskConfig &\n ConditionalTaskConfig,\n \"id\" | \"defaults\" | \"maxIterations\"\n> & {\n /**\n * Optional in the JSON union because non-loop tasks don't carry it —\n * each loop task class still enforces required-at-construction via its\n * own config type.\n */\n readonly maxIterations?: WhileTaskConfig[\"maxIterations\"];\n};\n\nexport type JsonTaskItem = {\n /** Unique identifier for the task */\n id: unknown;\n\n /** Type of task to create */\n type: string;\n\n /** Optional configuration for the task */\n config?: JsonTaskConfig;\n\n /** Default input values for the task */\n defaults?: TaskInput;\n\n /** Defines data flow between tasks */\n dependencies?: {\n /** Input parameter name mapped to source task output */\n [x: string]:\n | {\n /** ID of the source task */\n id: unknown;\n\n /** Output parameter name from source task */\n output: string;\n }\n | Array<{\n id: unknown;\n output: string;\n }>;\n };\n\n /** Nested tasks for compound operations */\n subtasks?: JsonTaskItem[];\n};\n\nexport type TaskGraphItemJson = {\n id: unknown;\n type: string;\n defaults?: TaskInput;\n config?: JsonTaskConfig;\n subgraph?: TaskGraphJson;\n merge?: CompoundMergeStrategy;\n};\n\nexport type TaskGraphJson = {\n tasks: TaskGraphItemJson[];\n dataflows: DataflowJson[];\n};\n\nexport type DataflowJson = {\n sourceTaskId: unknown;\n sourceTaskPortId: string;\n targetTaskId: unknown;\n targetTaskPortId: string;\n transforms?: ReadonlyArray<ITransformStep>;\n};\n\nexport interface TaskGraphJsonOptions {\n /** When true, synthetic InputTask/OutputTask boundary nodes are added at each graph level */\n readonly withBoundaryNodes?: boolean;\n}\n\nexport interface TaskDeserializationOptions {\n /**\n * Optional allowlist of task type names. When provided, only task types\n * in this set will be instantiated. Any other type throws TaskJSONError.\n * Use this to restrict which tasks can be created from untrusted JSON.\n */\n readonly allowedTypes?: ReadonlySet<string> | readonly string[];\n}\n\nconst createSingleTaskFromJSON = (\n item: JsonTaskItem | TaskGraphItemJson,\n registry?: ServiceRegistry,\n options?: TaskDeserializationOptions\n) => {\n if (!item.id) throw new TaskJSONError(\"Task id required\");\n if (!item.type) throw new TaskJSONError(\"Task type required\");\n if (item.defaults && Array.isArray(item.defaults))\n throw new TaskJSONError(\"Task defaults must be an object\");\n\n // Check allowlist if provided\n if (options?.allowedTypes) {\n const allowed =\n options.allowedTypes instanceof Set ? options.allowedTypes : new Set(options.allowedTypes);\n if (!allowed.has(item.type)) {\n throw new TaskJSONError(`Task type \"${item.type}\" is not in the allowed types list`);\n }\n }\n\n const constructors = getTaskConstructors(registry);\n const taskClass = constructors.get(item.type);\n if (!taskClass)\n throw new TaskJSONError(`Task type ${item.type} not found, perhaps not registered?`);\n\n // Validate that the resolved value is actually a constructable task class\n if (typeof taskClass !== \"function\" || typeof taskClass.type !== \"string\") {\n throw new TaskJSONError(`Task type ${item.type} resolved to an invalid constructor`);\n }\n\n const taskConfig: TaskConfig = {\n ...item.config,\n id: item.id,\n defaults: item.defaults ?? {},\n };\n const task = new taskClass(taskConfig, registry ? { registry } : {});\n return task;\n};\n\n/**\n * Creates a task instance from a JSON task item configuration.\n * Validates required fields and resolves the task constructor by type name.\n *\n * @param item - The JSON task item containing the task `type`, `id`, optional `config`,\n * `defaults`, `dependencies`, and `subtasks`.\n * @param registry - Optional service registry for dependency-injection-based constructor\n * lookup. When provided, task constructors are resolved from the registry's\n * `TASK_CONSTRUCTORS` binding (if present); otherwise falls back to the global\n * `TaskRegistry`. Omit to use the global registry.\n * @returns A fully constructed task instance, with its `subGraph` populated when\n * `subtasks` are present.\n * @throws {TaskJSONError} If `id` or `type` are missing, if `defaults` is an array,\n * or if the task type is not found in the resolved constructors map.\n * @throws {TaskConfigurationError} If `subtasks` are provided for a task that is not\n * a `GraphAsTask`.\n */\nexport const createTaskFromDependencyJSON = (\n item: JsonTaskItem,\n registry?: ServiceRegistry,\n options?: TaskDeserializationOptions\n) => {\n const task = createSingleTaskFromJSON(item, registry, options);\n if (item.subtasks && item.subtasks.length > 0) {\n if (!(task instanceof GraphAsTask)) {\n throw new TaskConfigurationError(\"Subgraph is only supported for CompoundTasks\");\n }\n task.subGraph = createGraphFromDependencyJSON(item.subtasks, registry, options);\n }\n return task;\n};\n\n/**\n * Creates a `TaskGraph` from an array of JSON dependency-style task items.\n * Recursively processes `subtasks` for compound (`GraphAsTask`) tasks.\n *\n * @param jsonItems - Array of JSON task items to convert into a task graph.\n * @param registry - Optional service registry for dependency-injection-based constructor\n * lookup. When provided, task constructors are resolved from the registry's\n * `TASK_CONSTRUCTORS` binding (if present); otherwise falls back to the global\n * `TaskRegistry`. Omit to use the global registry.\n * @returns A new `TaskGraph` containing all tasks built from `jsonItems`.\n * @throws {TaskJSONError} If any task item has missing/invalid required fields or an\n * unregistered task type.\n * @throws {TaskConfigurationError} If `subtasks` are specified for a non-`GraphAsTask`.\n */\nexport const createGraphFromDependencyJSON = (\n jsonItems: JsonTaskItem[],\n registry?: ServiceRegistry,\n options?: TaskDeserializationOptions\n) => {\n const subGraph = new TaskGraph();\n for (const subitem of jsonItems) {\n subGraph.addTask(createTaskFromDependencyJSON(subitem, registry, options));\n }\n return subGraph;\n};\n\n/**\n * Creates a task instance from a task graph item JSON representation.\n *\n * @param item - The JSON representation of the task, including its `type`, `id`,\n * optional `config`, `defaults`, `subgraph`, and `merge` strategy.\n * @param registry - Optional service registry for dependency-injection-based constructor\n * lookup. When provided, task constructors are resolved from the registry's\n * `TASK_CONSTRUCTORS` binding (if present); otherwise falls back to the global\n * `TaskRegistry`. Omit to use the global registry.\n * @returns A new task instance, with its `subGraph` populated when `subgraph` is present.\n * @throws {TaskJSONError} If required fields are missing or the task type is not found\n * in the resolved constructors map.\n * @throws {TaskConfigurationError} If a `subgraph` is provided for a task that is not\n * a `GraphAsTask`.\n */\nexport const createTaskFromGraphJSON = (\n item: TaskGraphItemJson,\n registry?: ServiceRegistry,\n options?: TaskDeserializationOptions\n) => {\n const task = createSingleTaskFromJSON(item, registry, options);\n if (item.subgraph) {\n if (!(task instanceof GraphAsTask)) {\n throw new TaskConfigurationError(\"Subgraph is only supported for GraphAsTask\");\n }\n task.subGraph = createGraphFromGraphJSON(item.subgraph, registry, options);\n }\n return task;\n};\n\n/**\n * Creates a `TaskGraph` instance from its JSON representation.\n * Reconstructs all tasks and the data flows between them.\n *\n * @param graphJsonObj - The JSON representation of the task graph, containing\n * `tasks` (array of `TaskGraphItemJson`) and `dataflows` (array of `DataflowJson`).\n * @param registry - Optional service registry for dependency-injection-based constructor\n * lookup. When provided, task constructors are resolved from the registry's\n * `TASK_CONSTRUCTORS` binding (if present); otherwise falls back to the global\n * `TaskRegistry`. Omit to use the global registry.\n * @returns A new `TaskGraph` instance with all tasks and data flows restored.\n * @throws {TaskJSONError} If any task item has missing/invalid required fields or an\n * unregistered task type.\n * @throws {TaskConfigurationError} If a `subgraph` is specified for a non-`GraphAsTask`.\n */\nexport const createGraphFromGraphJSON = (\n graphJsonObj: TaskGraphJson,\n registry?: ServiceRegistry,\n options?: TaskDeserializationOptions\n) => {\n const subGraph = new TaskGraph();\n for (const subitem of graphJsonObj.tasks) {\n subGraph.addTask(createTaskFromGraphJSON(subitem, registry, options));\n }\n for (const subitem of graphJsonObj.dataflows) {\n const dataflow = new Dataflow(\n subitem.sourceTaskId,\n subitem.sourceTaskPortId,\n subitem.targetTaskId,\n subitem.targetTaskPortId\n );\n if (subitem.transforms && subitem.transforms.length > 0) {\n dataflow.setTransforms(subitem.transforms);\n }\n subGraph.addDataflow(dataflow);\n }\n return subGraph;\n};\n",
|
|
75
73
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { IQueueStorage } from \"@workglow/job-queue\";\nimport { JobQueueClient, JobQueueServer } from \"@workglow/job-queue\";\nimport { EventEmitter } from \"@workglow/util\";\n\n/**\n * Combined structure for a registered job queue containing server, client, and storage\n */\nexport interface RegisteredQueue<Input = unknown, Output = unknown> {\n readonly server: JobQueueServer<Input, Output>;\n readonly client: JobQueueClient<Input, Output>;\n readonly storage: IQueueStorage<Input, Output>;\n}\n\n/**\n * Global singleton instance of the TaskQueueRegistry.\n * This is used to manage all job queues across the application.\n */\nlet taskQueueRegistry: TaskQueueRegistry | null = null;\n\n/**\n * Registry for managing task queues in the application.\n * Provides functionality to register, manage, and control job queues.\n *\n * @template Input - The type of input data for tasks in the queues\n * @template Output - The type of output data for tasks in the queues\n */\nexport type TaskQueueRegistryEvents = {\n queue_registered: (queueName: string) => void;\n};\n\nexport class TaskQueueRegistry {\n /**\n * Emits when queues are registered ({@link TaskQueueRegistryEvents}).\n */\n public readonly emitter = new EventEmitter<TaskQueueRegistryEvents>();\n\n /**\n * Map of queue names to their corresponding registered queue instances\n */\n public readonly queues: Map<string, RegisteredQueue<unknown, unknown>> = new Map();\n\n /**\n * Registers a new job queue with the registry\n *\n * @param queue - The registered queue containing server, client, and storage\n * @throws Error if a queue with the same name already exists\n */\n registerQueue<Input, Output>(queue: RegisteredQueue<Input, Output>): void {\n const queueName = queue.server.queueName;\n if (this.queues.has(queueName)) {\n throw new Error(`Queue with name ${queueName} already exists`);\n }\n this.queues.set(queueName, queue as RegisteredQueue<unknown, unknown>);\n this.emitter.emit(\"queue_registered\", queueName);\n }\n\n /**\n * Retrieves a registered queue by its name\n *\n * @param queueName - The name of the queue to retrieve\n * @returns The registered queue or undefined if not found\n */\n getQueue<Input, Output>(queueName: string): RegisteredQueue<Input, Output> | undefined {\n return this.queues.get(queueName) as RegisteredQueue<Input, Output> | undefined;\n }\n\n /**\n * Starts all registered job queue servers\n * This allows queues to begin processing their jobs\n *\n * @returns The registry instance for chaining\n */\n async startQueues() {\n for (const queue of this.queues.values()) {\n await queue.server.start();\n }\n }\n\n /**\n * Stops all registered job queue servers\n * This pauses job processing but maintains the queued jobs\n *\n * @returns The registry instance for chaining\n */\n async stopQueues() {\n for (const queue of this.queues.values()) {\n await queue.server.stop();\n }\n }\n\n /**\n * Clears all registered job queues\n * This removes all queued jobs from the storage\n *\n * @returns The registry instance for chaining\n */\n async clearQueues() {\n for (const queue of this.queues.values()) {\n await queue.storage.deleteAll();\n }\n }\n}\n\n/**\n * Gets the global TaskQueueRegistry instance\n * Creates a new instance if one doesn't exist\n *\n * @returns The global TaskQueueRegistry instance\n */\nexport function getTaskQueueRegistry(): TaskQueueRegistry {\n if (!taskQueueRegistry) {\n taskQueueRegistry = new TaskQueueRegistry();\n }\n return taskQueueRegistry;\n}\n\n/**\n * Sets the global TaskQueueRegistry instance\n * Stops and clears any existing registry before replacing it\n *\n * @param registry - The new registry instance to use, or null to clear\n */\nexport async function setTaskQueueRegistry(registry: TaskQueueRegistry | null): Promise<void> {\n if (taskQueueRegistry) {\n await taskQueueRegistry.stopQueues();\n await taskQueueRegistry.clearQueues();\n }\n taskQueueRegistry = registry;\n}\n",
|
|
76
|
-
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\
|
|
74
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { FallbackTask, FallbackTaskConfig } from \"./FallbackTask\";\nimport { GraphAsTaskRunner } from \"./GraphAsTaskRunner\";\nimport type { ITask } from \"./ITask\";\nimport { TaskAbortedError, TaskFailedError, TaskTimeoutError } from \"./TaskError\";\nimport type { TaskRunContext } from \"./TaskRunContext\";\nimport type { TaskInput, TaskOutput } from \"./TaskTypes\";\nimport { TaskStatus } from \"./TaskTypes\";\n\n/**\n * Runner for FallbackTask that executes alternatives sequentially until one succeeds.\n *\n * In **task mode**, each task in the subgraph is tried independently.\n * In **data mode**, the entire subgraph is re-run with different input overrides.\n */\nexport class FallbackTaskRunner<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends FallbackTaskConfig<Input> = FallbackTaskConfig<Input>,\n> extends GraphAsTaskRunner<Input, Output, Config> {\n declare task: FallbackTask<Input, Output, Config>;\n\n /**\n * Override executeTask to implement sequential fallback logic.\n */\n protected override async executeTask(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n if (this.task.fallbackMode === \"data\") {\n return this.executeDataFallback(input);\n }\n return this.executeTaskFallback(input);\n }\n\n /**\n * For FallbackTask, preview runs use the task's preview hook only,\n * bypassing GraphAsTaskRunner's child-merging logic.\n */\n public override async executeTaskPreview(\n input: Input,\n _ctx: TaskRunContext\n ): Promise<Output | undefined> {\n return this.task.executePreview?.(input, { own: this.own });\n }\n\n // ========================================================================\n // Task Mode: Try each task in the subgraph as an independent alternative\n // ========================================================================\n\n /**\n * Tries each task in the subgraph sequentially. Returns the first\n * successful result. If all fail, throws with collected errors.\n */\n private async executeTaskFallback(input: Input): Promise<Output | undefined> {\n const tasks = this.task.subGraph.getTasks();\n if (tasks.length === 0) {\n throw new TaskFailedError(\"FallbackTask has no alternatives to try\");\n }\n\n const errors: { task: ITask; error: Error }[] = [];\n const totalAttempts = tasks.length;\n\n for (let i = 0; i < tasks.length; i++) {\n if (this.currentCtx?.abortController.signal.aborted) {\n throw new TaskAbortedError(\"Fallback aborted\");\n }\n\n const alternativeTask = tasks[i];\n const attemptNumber = i + 1;\n\n await this.handleProgress(\n Math.round(((i + 0.5) / totalAttempts) * 100),\n `Trying alternative ${attemptNumber}/${totalAttempts}: ${alternativeTask.type}`\n );\n\n try {\n // Reset the task to PENDING so it can be run\n this.resetTask(alternativeTask);\n\n // Run the individual task with the parent's input\n const result = await alternativeTask.run(input);\n\n await this.handleProgress(\n 100,\n `Alternative ${attemptNumber}/${totalAttempts} succeeded: ${alternativeTask.type}`\n );\n\n return result as Output;\n } catch (error) {\n // Aborts (non-timeout) are not retryable — propagate immediately\n if (error instanceof TaskAbortedError && !(error instanceof TaskTimeoutError)) {\n throw error;\n }\n errors.push({ task: alternativeTask, error: error as Error });\n // Continue to next alternative\n }\n }\n\n // All alternatives failed\n throw this.buildAggregateError(errors, \"task\");\n }\n\n // ========================================================================\n // Data Mode: Run the template workflow with different input overrides\n // ========================================================================\n\n /**\n * Runs the subgraph workflow multiple times, each time with a different\n * set of input overrides merged from `config.alternatives`.\n */\n private async executeDataFallback(input: Input): Promise<Output | undefined> {\n const alternatives = this.task.alternatives;\n if (alternatives.length === 0) {\n throw new TaskFailedError(\"FallbackTask has no data alternatives to try\");\n }\n\n const errors: { alternative: Record<string, unknown>; error: Error }[] = [];\n const totalAttempts = alternatives.length;\n\n /**\n * Blend the subgraph's aggregate `graph_progress` with the outer attempt index so\n * nested streaming tasks visibly advance the bar between attempt boundaries. This\n * mirrors the pattern used by {@link IteratorTaskRunner.executeSubgraphIteration}\n * and {@link WhileTask.execute}. Because each attempt resets the subgraph and\n * `graph_progress` starts at 0, the blended value is monotonic across attempts\n * as `currentAttemptIndex` advances.\n */\n let currentAttemptIndex = 0;\n const onSubgraphProgress = (innerProgress: number | undefined, message?: string): void => {\n if (innerProgress === undefined) return;\n const blended = Math.round(\n ((currentAttemptIndex + innerProgress / 100) / totalAttempts) * 100\n );\n void this.handleProgress(\n blended,\n message ?? `Data alternative ${currentAttemptIndex + 1}/${totalAttempts}`\n );\n };\n const unsubscribeSubgraphProgress = this.task.subGraph.subscribe(\n \"graph_progress\",\n onSubgraphProgress\n );\n\n try {\n for (let i = 0; i < alternatives.length; i++) {\n if (this.currentCtx?.abortController.signal.aborted) {\n throw new TaskAbortedError(\"Fallback aborted\");\n }\n\n currentAttemptIndex = i;\n const alternative = alternatives[i];\n const attemptNumber = i + 1;\n\n await this.handleProgress(\n Math.round(((i + 0.5) / totalAttempts) * 100),\n `Trying data alternative ${attemptNumber}/${totalAttempts}`\n );\n\n try {\n // Reset all tasks in the subgraph to PENDING\n this.resetSubgraph();\n\n // Merge the alternative's data with the original input\n const mergedInput = { ...input, ...alternative } as Input;\n\n // Run the subgraph with merged input\n const results = await this.task.subGraph.run<Output>(mergedInput, {\n parentSignal: this.currentCtx?.abortController.signal,\n outputCache: this.outputCache,\n registry: this.registry,\n });\n\n const mergedOutput = this.task.subGraph.mergeExecuteOutputsToRunOutput(\n results,\n this.task.compoundMerge\n ) as Output;\n\n await this.handleProgress(\n 100,\n `Data alternative ${attemptNumber}/${totalAttempts} succeeded`\n );\n\n return mergedOutput as Output;\n } catch (error) {\n // Aborts (non-timeout) are not retryable — propagate immediately\n if (error instanceof TaskAbortedError && !(error instanceof TaskTimeoutError)) {\n throw error;\n }\n errors.push({ alternative, error: error as Error });\n // Continue to next alternative\n }\n }\n } finally {\n unsubscribeSubgraphProgress();\n }\n\n // All alternatives failed\n throw this.buildAggregateError(errors, \"data\");\n }\n\n // ========================================================================\n // Helpers\n // ========================================================================\n\n /**\n * Resets a single task to PENDING status so it can be re-run.\n */\n private resetTask(task: ITask): void {\n task.status = TaskStatus.PENDING;\n task.progress = 0;\n task.error = undefined;\n task.completedAt = undefined;\n task.startedAt = undefined;\n task.resetInputData();\n }\n\n /**\n * Resets all tasks and dataflows in the subgraph for a fresh run.\n */\n private resetSubgraph(): void {\n for (const task of this.task.subGraph.getTasks()) {\n this.resetTask(task);\n }\n for (const dataflow of this.task.subGraph.getDataflows()) {\n dataflow.reset();\n }\n }\n\n /**\n * Builds a descriptive error from all collected failures.\n */\n private buildAggregateError(\n errors: { error: Error; [key: string]: unknown }[],\n mode: \"task\" | \"data\"\n ): TaskFailedError {\n const label = mode === \"task\" ? \"alternative\" : \"data alternative\";\n const details = errors\n .map((e, i) => {\n const prefix = e.error instanceof TaskTimeoutError ? \"[timeout] \" : \"\";\n return ` ${label} ${i + 1}: ${prefix}${e.error.message}`;\n })\n .join(\"\\n\");\n return new TaskFailedError(`All ${errors.length} ${label}s failed:\\n${details}`);\n }\n}\n",
|
|
75
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchema } from \"@workglow/util/schema\";\nimport { Workflow } from \"../task-graph/Workflow\";\nimport { CreateEndLoopWorkflow, CreateLoopWorkflow } from \"../task-graph/WorkflowFactories\";\nimport { FallbackTaskRunner } from \"./FallbackTaskRunner\";\nimport type { GraphAsTaskConfig } from \"./GraphAsTask\";\nimport { GraphAsTask, graphAsTaskConfigSchema } from \"./GraphAsTask\";\nimport type { TaskInput, TaskOutput, TaskTypeName } from \"./TaskTypes\";\n\n/**\n * Execution mode for the fallback task.\n * - `\"task\"`: each task in the subgraph is an independent alternative tried sequentially.\n * - `\"data\"`: the subgraph is a template workflow re-run with each entry in `alternatives`.\n */\nexport type FallbackMode = \"task\" | \"data\";\n\nexport const fallbackTaskConfigSchema = {\n type: \"object\",\n properties: {\n ...graphAsTaskConfigSchema[\"properties\"],\n fallbackMode: { type: \"string\", enum: [\"task\", \"data\"] },\n alternatives: { type: \"array\", items: { type: \"object\", additionalProperties: true } },\n },\n additionalProperties: false,\n} as const satisfies DataPortSchema;\n\nexport type FallbackTaskConfig<Input extends TaskInput = TaskInput> = GraphAsTaskConfig<Input> & {\n /**\n * The fallback execution mode.\n * - `\"task\"`: Try each task in the subgraph as an alternative.\n * - `\"data\"`: Try the template workflow with each set of input overrides.\n * @default \"task\"\n */\n readonly fallbackMode?: FallbackMode;\n\n /**\n * Array of input overrides for data mode.\n * Each entry is merged with the task input before running the template.\n * Only used when `fallbackMode` is `\"data\"`.\n *\n * @example\n * ```typescript\n * alternatives: [\n * { model: \"openai:gpt-4\" },\n * { model: \"anthropic:claude-sonnet-4-20250514\" },\n * { model: \"onnx:Xenova/LaMini-Flan-T5-783M:q8\" },\n * ]\n * ```\n */\n readonly alternatives?: Record<string, unknown>[];\n};\n\n/**\n * Tries multiple alternatives and returns the first successful result.\n *\n * In task mode each child is an independent alternative tried sequentially;\n * in data mode the subgraph is a template re-run with each entry in\n * `alternatives` merged into the input. If all alternatives fail a\n * `TaskFailedError` aggregating each attempt's error is thrown.\n */\nexport class FallbackTask<\n Input extends TaskInput = TaskInput,\n Output extends TaskOutput = TaskOutput,\n Config extends FallbackTaskConfig<Input> = FallbackTaskConfig<Input>,\n> extends GraphAsTask<Input, Output, Config> {\n // ========================================================================\n // Static properties\n // ========================================================================\n\n public static override type: TaskTypeName = \"FallbackTask\";\n public static override category: string = \"Flow Control\";\n public static override title: string = \"Fallback\";\n public static override description: string = \"Try alternatives until one succeeds\";\n\n public static override hasDynamicSchemas: boolean = true;\n\n public static override configSchema(): DataPortSchema {\n return fallbackTaskConfigSchema;\n }\n\n // ========================================================================\n // TaskRunner Override\n // ========================================================================\n\n declare _runner: FallbackTaskRunner<Input, Output, Config>;\n\n override get runner(): FallbackTaskRunner<Input, Output, Config> {\n if (!this._runner) {\n this._runner = new FallbackTaskRunner<Input, Output, Config>(this);\n }\n return this._runner;\n }\n\n // ========================================================================\n // Config accessors\n // ========================================================================\n\n public get fallbackMode(): FallbackMode {\n return this.config?.fallbackMode ?? \"task\";\n }\n\n public get alternatives(): Record<string, unknown>[] {\n return this.config?.alternatives ?? [];\n }\n\n // ========================================================================\n // Schema Methods\n // ========================================================================\n\n /**\n * In task mode, input schema is the union of all alternative tasks' inputs.\n * In data mode, input schema comes from the template workflow's starting nodes.\n */\n public override inputSchema(): DataPortSchema {\n if (!this.hasChildren()) {\n return (this.constructor as typeof FallbackTask).inputSchema();\n }\n\n if (this.fallbackMode === \"data\") {\n // Data mode: use the base GraphAsTask logic (union of starting node inputs)\n return super.inputSchema();\n }\n\n // Task mode: union of all tasks' input schemas (they are independent alternatives)\n const properties: Record<string, unknown> = {};\n const tasks = this.subGraph.getTasks();\n\n for (const task of tasks) {\n const taskInputSchema = task.inputSchema();\n if (typeof taskInputSchema === \"boolean\") continue;\n const taskProperties = taskInputSchema.properties || {};\n\n for (const [inputName, inputProp] of Object.entries(taskProperties)) {\n if (!properties[inputName]) {\n properties[inputName] = inputProp;\n }\n }\n }\n\n return {\n type: \"object\",\n properties,\n additionalProperties: true,\n } as DataPortSchema;\n }\n\n /**\n * Output schema is derived from the first task in the subgraph.\n * All alternatives should produce compatible output.\n */\n public override outputSchema(): DataPortSchema {\n if (!this.hasChildren()) {\n return (this.constructor as typeof FallbackTask).outputSchema();\n }\n\n const tasks = this.subGraph.getTasks();\n if (tasks.length === 0) {\n return { type: \"object\", properties: {}, additionalProperties: false } as DataPortSchema;\n }\n\n if (this.fallbackMode === \"task\") {\n // Task mode: use the first task's output schema (all alternatives should be compatible)\n const firstTask = tasks[0];\n return firstTask.outputSchema();\n }\n\n // Data mode: use the ending nodes' output schema via base class logic\n return super.outputSchema();\n }\n\n // ========================================================================\n // Serialization\n // ========================================================================\n\n public override toJSON() {\n const json = super.toJSON();\n return {\n ...json,\n config: {\n ...(\"config\" in json ? json.config : {}),\n fallbackMode: this.fallbackMode,\n ...(this.alternatives.length > 0 ? { alternatives: this.alternatives } : {}),\n },\n };\n }\n}\n\n// ============================================================================\n// Workflow Prototype Extensions\n// ============================================================================\n\ndeclare module \"../task-graph/Workflow\" {\n interface Workflow {\n /**\n * Starts a task-mode fallback block. Each task added inside the block\n * is an independent alternative tried sequentially until one succeeds.\n * Use `.endFallback()` to close the block and return to the parent workflow.\n */\n fallback: CreateLoopWorkflow<TaskInput, TaskOutput, FallbackTaskConfig<TaskInput>>;\n\n /**\n * Ends the task-mode fallback block and returns to the parent workflow.\n */\n endFallback(): Workflow;\n\n /**\n * Starts a data-mode fallback block. The tasks added inside the block\n * form a template workflow that is re-run with each set of input overrides\n * from `alternatives`. Use `.endFallbackWith()` to close the block.\n *\n * @param alternatives - Array of input override objects to try sequentially\n */\n fallbackWith(alternatives: Record<string, unknown>[]): Workflow;\n\n /**\n * Ends the data-mode fallback block and returns to the parent workflow.\n */\n endFallbackWith(): Workflow;\n }\n}\n\nqueueMicrotask(() => {\n Workflow.prototype.fallback = function (this: Workflow): Workflow {\n return this.addLoopTask(FallbackTask, { fallbackMode: \"task\" });\n };\n Workflow.prototype.endFallback = CreateEndLoopWorkflow(\"endFallback\");\n\n Workflow.prototype.fallbackWith = function (\n this: Workflow,\n alternatives: Record<string, unknown>[]\n ): Workflow {\n return this.addLoopTask(FallbackTask, {\n fallbackMode: \"data\",\n alternatives,\n });\n };\n Workflow.prototype.endFallbackWith = CreateEndLoopWorkflow(\"endFallbackWith\");\n});\n",
|
|
76
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// organize-imports-ignore\n\nexport * from \"./ConditionalTask\";\nexport * from \"./ConditionUtils\";\nexport * from \"./EntitlementEnforcer\";\nexport * from \"./EntitlementPolicy\";\nexport * from \"./EntitlementProfile\";\nexport * from \"./EntitlementProfiles\";\nexport * from \"./EntitlementResolver\";\nexport * from \"./InputCompactor\";\nexport * from \"./InputResolver\";\nexport * from \"./ITask\";\nexport * from \"./iterationSchema\";\nexport * from \"./JobQueueFactory\";\nexport * from \"./MapTask\";\nexport * from \"./ReduceTask\";\nexport * from \"./StreamTypes\";\nexport * from \"./Task\";\nexport * from \"./TaskEntitlements\";\nexport * from \"./TaskError\";\nexport * from \"./TaskEvents\";\nexport * from \"./TaskJSON\";\nexport * from \"./TaskQueueRegistry\";\nexport * from \"./TaskRegistry\";\nexport * from \"./TaskTypes\";\n\nexport * from \"./GraphAsTask\";\nexport * from \"./GraphAsTaskRunner\";\n\nexport * from \"./FallbackTask\";\nexport * from \"./FallbackTaskRunner\";\nexport * from \"./IteratorTask\";\nexport * from \"./IteratorTaskRunner\";\nexport * from \"./WhileTask\";\nexport * from \"./WhileTaskRunner\";\n\nimport { ConditionalTask } from \"./ConditionalTask\";\nimport { FallbackTask } from \"./FallbackTask\";\nimport { GraphAsTask } from \"./GraphAsTask\";\nimport { MapTask } from \"./MapTask\";\nimport { ReduceTask } from \"./ReduceTask\";\nimport { TaskRegistry } from \"./TaskRegistry\";\nimport { WhileTask } from \"./WhileTask\";\n\nexport const registerBaseTasks = () => {\n const tasks = [GraphAsTask, ConditionalTask, FallbackTask, MapTask, WhileTask, ReduceTask];\n tasks.map(TaskRegistry.registerTask);\n return tasks;\n};\n",
|
|
77
|
+
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { ITabularStorage } from \"@workglow/storage\";\nimport type {\n ITaskOutputStorage,\n TaskOutputDeleteSearchCriteria,\n TaskOutputRow,\n TaskOutputRowPrimaryKey,\n} from \"./ITaskOutputStorage\";\nimport { TaskOutputPrimaryKeyNames, TaskOutputSchema } from \"./TaskOutputStorageSchema\";\n\ntype TaskOutputTabularBacking = ITabularStorage<\n typeof TaskOutputSchema,\n typeof TaskOutputPrimaryKeyNames\n>;\n\nexport type { TaskOutputTabularBacking };\n\n/**\n * Adapts a full {@link ITabularStorage} table to {@link ITaskOutputStorage}.\n */\nexport class TabularTaskOutputStorage implements ITaskOutputStorage {\n constructor(private readonly tabular: TaskOutputTabularBacking) {}\n\n async setupDatabase(): Promise<void> {\n await this.tabular.setupDatabase?.();\n }\n\n async put(row: TaskOutputRow): Promise<void> {\n await this.tabular.put(row);\n }\n\n async get(key: TaskOutputRowPrimaryKey): Promise<TaskOutputRow | undefined> {\n const row = await this.tabular.get(key);\n return row as TaskOutputRow | undefined;\n }\n\n async delete(key: TaskOutputRowPrimaryKey): Promise<void> {\n await this.tabular.delete(key);\n }\n\n async deleteAll(): Promise<void> {\n await this.tabular.deleteAll();\n }\n\n async size(): Promise<number> {\n return await this.tabular.size();\n }\n\n async deleteSearch(criteria: TaskOutputDeleteSearchCriteria): Promise<void> {\n await this.tabular.deleteSearch(criteria);\n }\n\n records(pageSize?: number): AsyncGenerator<TaskOutputRow, void, undefined> {\n return this.tabular.records(pageSize) as AsyncGenerator<TaskOutputRow, void, undefined>;\n }\n\n isDurable(): boolean {\n return this.tabular.isDurable?.() ?? true;\n }\n}\n\n/** Convenience factory for {@link TabularTaskOutputStorage}. */\nexport function tabularTaskOutputStorage(tabular: TaskOutputTabularBacking): ITaskOutputStorage {\n return new TabularTaskOutputStorage(tabular);\n}\n",
|
|
77
78
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { createServiceToken, EventEmitter, EventParameters } from \"@workglow/util\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\n\n/**\n * Service token for TaskGraphRepository\n */\nexport const TASK_GRAPH_REPOSITORY = createServiceToken<TaskGraphRepository>(\n \"taskgraph.taskGraphRepository\"\n);\n\n/**\n * Events that can be emitted by the TaskGraphRepository\n */\nexport type TaskGraphRepositoryEvents = keyof TaskGraphRepositoryEventListeners;\n\nexport type TaskGraphRepositoryEventListeners = {\n graph_saved: (key: string) => void;\n graph_retrieved: (key: string) => void;\n graph_cleared: () => void;\n};\n\nexport type TaskGraphRepositoryEventListener<Event extends TaskGraphRepositoryEvents> =\n TaskGraphRepositoryEventListeners[Event];\n\nexport type TaskGraphRepositoryEventParameters<Event extends TaskGraphRepositoryEvents> =\n EventParameters<TaskGraphRepositoryEventListeners, Event>;\n\n/**\n * Repository class for managing task graphs persistence and retrieval.\n * Provides functionality to save, load, and manipulate task graphs with their associated tasks and data flows.\n */\nexport abstract class TaskGraphRepository {\n /**\n * The type of the repository\n */\n public type = \"TaskGraphRepository\";\n\n /**\n * The event emitter for the task graphs\n */\n private get events() {\n if (!this._events) {\n this._events = new EventEmitter<TaskGraphRepositoryEventListeners>();\n }\n return this._events;\n }\n private _events: EventEmitter<TaskGraphRepositoryEventListeners> | undefined;\n\n /**\n * Registers an event listener for the specified event\n * @param name The event name to listen for\n * @param fn The callback function to execute when the event occurs\n */\n on<Event extends TaskGraphRepositoryEvents>(\n name: Event,\n fn: TaskGraphRepositoryEventListener<Event>\n ) {\n this.events.on(name, fn);\n }\n\n /**\n * Removes an event listener for the specified event\n * @param name The event name to stop listening for\n * @param fn The callback function to remove\n */\n off<Event extends TaskGraphRepositoryEvents>(\n name: Event,\n fn: TaskGraphRepositoryEventListener<Event>\n ) {\n this.events.off(name, fn);\n }\n\n /**\n * Adds an event listener that will only be called once\n * @param name The event name to listen for\n * @param fn The callback function to execute when the event occurs\n */\n once<Event extends TaskGraphRepositoryEvents>(\n name: Event,\n fn: TaskGraphRepositoryEventListener<Event>\n ) {\n this.events.once(name, fn);\n }\n\n /**\n * Returns when the event was emitted (promise form of once)\n * @param name The event name to check\n * @returns true if the event has listeners, false otherwise\n */\n waitOn<Event extends TaskGraphRepositoryEvents>(name: Event) {\n return this.events.waitOn(name) as Promise<TaskGraphRepositoryEventParameters<Event>>;\n }\n\n /**\n * Emits an event (if there are listeners)\n * @param name The event name to emit\n * @param args The event parameters\n */\n emit<Event extends TaskGraphRepositoryEvents>(\n name: Event,\n ...args: TaskGraphRepositoryEventParameters<Event>\n ) {\n this._events?.emit(name, ...args);\n }\n\n /**\n * Saves a task graph to persistent storage\n * @param key The unique identifier for the task graph\n * @param output The task graph to save\n * @emits graph_saved when the operation completes\n */\n abstract saveTaskGraph(key: string, output: TaskGraph): Promise<void>;\n\n /**\n * Retrieves a task graph from persistent storage\n * @param key The unique identifier of the task graph to retrieve\n * @returns The retrieved task graph, or undefined if not found\n * @emits graph_retrieved when the operation completes successfully\n */\n abstract getTaskGraph(key: string): Promise<TaskGraph | undefined>;\n\n /**\n * Clears all task graphs from the repository\n * @emits graph_cleared when the operation completes\n */\n abstract clear(): Promise<void>;\n\n /**\n * Returns the number of task graphs stored in the repository\n * @returns The count of stored task graphs\n */\n abstract size(): Promise<number>;\n}\n",
|
|
78
79
|
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { BaseTabularStorage } from \"@workglow/storage\";\nimport type { ServiceRegistry } from \"@workglow/util\";\nimport { DataPortSchemaObject } from \"@workglow/util/schema\";\nimport { TaskGraph } from \"../task-graph/TaskGraph\";\nimport { createGraphFromGraphJSON } from \"../task/TaskJSON\";\nimport { TaskGraphRepository } from \"./TaskGraphRepository\";\n\nexport const TaskGraphSchema = {\n type: \"object\",\n properties: {\n key: { type: \"string\" },\n value: { type: \"string\" },\n },\n additionalProperties: false,\n} satisfies DataPortSchemaObject;\n\nexport const TaskGraphPrimaryKeyNames = [\"key\"] as const;\n\n/**\n * Options for the TaskGraphRepository\n */\nexport type TaskGraphRepositoryStorage = BaseTabularStorage<\n typeof TaskGraphSchema,\n typeof TaskGraphPrimaryKeyNames\n>;\ntype TaskGraphRepositoryOptions = {\n tabularRepository: TaskGraphRepositoryStorage;\n registry?: ServiceRegistry;\n};\n\n/**\n * Repository class for managing task graphs persistence and retrieval.\n * Provides functionality to save, load, and manipulate task graphs with their associated tasks and data flows.\n */\nexport class TaskGraphTabularRepository extends TaskGraphRepository {\n /**\n * The type of the repository\n */\n public override type = \"TaskGraphTabularRepository\";\n\n /**\n * The tabular repository for the task graphs\n */\n tabularRepository: TaskGraphRepositoryStorage;\n\n /**\n * Optional service registry for DI-based task constructor lookups\n */\n readonly registry: ServiceRegistry | undefined;\n\n /**\n * Constructor for the TaskGraphRepository\n * @param options The options for the repository\n */\n constructor({ tabularRepository, registry }: TaskGraphRepositoryOptions) {\n super();\n this.tabularRepository = tabularRepository;\n this.registry = registry;\n }\n\n /**\n * Sets up the database for the repository.\n * Must be called before using any other methods.\n */\n async setupDatabase(): Promise<void> {\n await this.tabularRepository.setupDatabase?.();\n }\n\n /**\n * Saves a task graph to persistent storage\n * @param key The unique identifier for the task graph\n * @param output The task graph to save\n * @emits graph_saved when the operation completes\n */\n async saveTaskGraph(key: string, output: TaskGraph): Promise<void> {\n const value = JSON.stringify(output.toJSON());\n await this.tabularRepository.put({ key, value });\n this.emit(\"graph_saved\", key);\n }\n\n /**\n * Retrieves a task graph from persistent storage\n * @param key The unique identifier of the task graph to retrieve\n * @returns The retrieved task graph, or undefined if not found\n * @emits graph_retrieved when the operation completes successfully\n */\n async getTaskGraph(key: string): Promise<TaskGraph | undefined> {\n const result = await this.tabularRepository.get({ key });\n const value = result?.value;\n if (!value) {\n return undefined;\n }\n const jsonObj = JSON.parse(value);\n const graph = createGraphFromGraphJSON(jsonObj, this.registry);\n\n this.emit(\"graph_retrieved\", key);\n return graph;\n }\n\n /**\n * Clears all task graphs from the repository\n * @emits graph_cleared when the operation completes\n */\n async clear(): Promise<void> {\n await this.tabularRepository.deleteAll();\n this.emit(\"graph_cleared\");\n }\n\n /**\n * Returns the number of task graphs stored in the repository\n * @returns The count of stored task graphs\n */\n async size(): Promise<number> {\n return await this.tabularRepository.size();\n }\n}\n",
|
|
79
|
-
"/**\n * @license\n * Copyright
|
|
80
|
+
"/**\n * @license\n * Copyright 2026 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type { DataPortSchemaObject } from \"@workglow/util/schema\";\n\nexport type TaskOutputPrimaryKey = {\n key: string;\n taskType: string;\n};\n\nexport const TaskOutputSchema = {\n type: \"object\",\n properties: {\n key: { type: \"string\" },\n taskType: { type: \"string\" },\n value: { type: \"string\", contentEncoding: \"blob\" },\n createdAt: { type: \"string\", format: \"date-time\" },\n },\n additionalProperties: false,\n} satisfies DataPortSchemaObject;\n\nexport const TaskOutputPrimaryKeyNames = [\"key\", \"taskType\"] as const;\n",
|
|
81
|
+
"/**\n * @license\n * Copyright 2025 Steven Roussey <sroussey@gmail.com>\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { makeFingerprint } from \"@workglow/util\";\nimport { compress, decompress } from \"@workglow/util/compress\";\nimport { TaskInput, TaskOutput } from \"../task/TaskTypes\";\nimport type { ITaskOutputStorage } from \"./ITaskOutputStorage\";\nimport type { TaskOutputTabularBacking } from \"./TabularTaskOutputStorage\";\nimport { TaskOutputRepository } from \"./TaskOutputRepository\";\n\nexport { TaskOutputPrimaryKeyNames, TaskOutputSchema } from \"./TaskOutputStorageSchema\";\nexport type { TaskOutputPrimaryKey } from \"./TaskOutputStorageSchema\";\n\nexport type TaskOutputRepositoryOptions = {\n storage: ITaskOutputStorage;\n outputCompression?: boolean;\n};\n\n/** Backing tabular table type for {@link tabularTaskOutputStorage}. */\nexport type TaskOutputRepositoryStorage = TaskOutputTabularBacking;\n\n/**\n * Repository for task output caching backed by {@link ITaskOutputStorage}.\n */\nexport class TaskOutputTabularRepository extends TaskOutputRepository {\n readonly storage: ITaskOutputStorage;\n\n constructor({ storage, outputCompression }: TaskOutputRepositoryOptions) {\n super({ outputCompression });\n this.storage = storage;\n this.outputCompression = outputCompression ?? true;\n }\n\n public isDurable(): boolean {\n return this.storage.isDurable?.() ?? true;\n }\n\n async setupDatabase(): Promise<void> {\n await this.storage.setupDatabase?.();\n }\n\n public async keyFromInputs(inputs: TaskInput): Promise<string> {\n return await makeFingerprint(inputs);\n }\n\n async saveOutput(\n taskType: string,\n inputs: TaskInput,\n output: TaskOutput,\n createdAt = new Date()\n ): Promise<void> {\n const key = await this.keyFromInputs(inputs);\n const value = JSON.stringify(output);\n if (this.outputCompression) {\n const compressedValue = await compress(value);\n await this.storage.put({\n taskType,\n key,\n value: compressedValue as unknown as string,\n createdAt: createdAt.toISOString(),\n });\n } else {\n const valueBuffer = Buffer.from(value);\n await this.storage.put({\n taskType,\n key,\n value: valueBuffer as unknown as string,\n createdAt: createdAt.toISOString(),\n });\n }\n this.emit(\"output_saved\", taskType);\n }\n\n async getOutput(taskType: string, inputs: TaskInput): Promise<TaskOutput | undefined> {\n const key = await this.keyFromInputs(inputs);\n const output = await this.storage.get({ key, taskType });\n this.emit(\"output_retrieved\", taskType);\n if (output?.value) {\n if (this.outputCompression) {\n const raw: unknown = output.value as unknown;\n const bytes: Uint8Array =\n raw instanceof Uint8Array\n ? raw\n : Array.isArray(raw)\n ? new Uint8Array(raw as number[])\n : raw && typeof raw === \"object\"\n ? new Uint8Array(\n Object.keys(raw as Record<string, number>)\n .filter((k) => /^\\d+$/.test(k))\n .sort((a, b) => Number(a) - Number(b))\n .map((k) => (raw as Record<string, number>)[k])\n )\n : new Uint8Array();\n const decompressedValue = await decompress(bytes);\n const value = JSON.parse(decompressedValue) as TaskOutput;\n return value as TaskOutput;\n } else {\n const stringValue = output.value.toString();\n const value = JSON.parse(stringValue) as TaskOutput;\n return value as TaskOutput;\n }\n } else {\n return undefined;\n }\n }\n\n async clear(): Promise<void> {\n await this.storage.deleteAll();\n this.emit(\"output_cleared\");\n }\n\n async size(): Promise<number> {\n return await this.storage.size();\n }\n\n async clearOlderThan(olderThanInMs: number): Promise<void> {\n const date = new Date(Date.now() - olderThanInMs).toISOString();\n await this.storage.deleteSearch({ createdAt: { value: date, operator: \"<\" } });\n this.emit(\"output_pruned\");\n }\n\n override async deleteByTaskTypePrefix(prefix: string): Promise<void> {\n for await (const row of this.storage.records()) {\n if (typeof row.taskType === \"string\" && row.taskType.startsWith(prefix)) {\n await this.storage.delete({ key: row.key, taskType: row.taskType });\n }\n }\n }\n\n override async clearOlderThanWithTaskTypePrefix(\n prefix: string,\n olderThanInMs: number\n ): Promise<void> {\n const cutoff = Date.now() - olderThanInMs;\n for await (const row of this.storage.records()) {\n if (typeof row.taskType === \"string\" && row.taskType.startsWith(prefix)) {\n const ts = typeof row.createdAt === \"string\" ? new Date(row.createdAt).getTime() : NaN;\n if (!isNaN(ts) && ts < cutoff) {\n await this.storage.delete({ key: row.key, taskType: row.taskType });\n }\n }\n }\n }\n\n override async sizeByTaskTypePrefix(prefix: string): Promise<number> {\n let count = 0;\n for await (const row of this.storage.records()) {\n if (typeof row.taskType === \"string\" && row.taskType.startsWith(prefix)) {\n count++;\n }\n }\n return count;\n }\n}\n",
|
|
80
82
|
"/**\n * @copyright\n * Copyright 2026 Steven Roussey\n * All Rights Reserved\n */\nexport { _resetPortCodecsForTests, getPortCodec, registerPortCodec } from \"@workglow/util\";\nexport type { PortCodec } from \"@workglow/util\";\n"
|
|
81
83
|
],
|
|
82
|
-
"mappings": ";AAOA;AACA;;;ACDA;AAAA;AAEO,MAAM,kBAAkB,UAAU;AAAA,SACd,OAAe;AAAA,EAEjC;AAAA,EAEA;AAAA,EACP,WAAW,CAAC,SAAiB;AAAA,IAC3B,MAAM,OAAO;AAAA;AAEjB;AAAA;AAEO,MAAM,+BAA+B,UAAU;AAAA,SAC3B,OAAe;AAAA,EACxC,WAAW,CAAC,SAAiB;AAAA,IAC3B,MAAM,OAAO;AAAA;AAEjB;AAAA;AAEO,MAAM,sBAAsB,UAAU;AAAA,SAClB,OAAe;AAAA,EACxC,WAAW,CAAC,SAAiB;AAAA,IAC3B,MAAM,OAAO;AAAA;AAEjB;AAAA;AAKO,MAAM,yBAAyB,UAAU;AAAA,SACrB,OAAe;AAAA,EACxC,WAAW,CAAC,UAAkB,gBAAgB;AAAA,IAC5C,MAAM,OAAO;AAAA;AAEjB;AAAA;AAKO,MAAM,yBAAyB,iBAAiB;AAAA,SAC5B,OAAe;AAAA,EACxC,WAAW,CAAC,WAAoB;AAAA,IAC9B,MAAM,YAAY,wBAAwB,gBAAgB,gBAAgB;AAAA;AAE9E;AAAA;AAQO,MAAM,8BAA8B,iBAAiB;AAAA,SACjC,OAAe;AAAA,EACxC,WAAW,CAAC,WAAoB;AAAA,IAC9B,MAAM,SAAS;AAAA,IAEf,KAAK,UAAU,YACX,mCAAmC,gBACnC;AAAA;AAER;AAAA;AAEO,MAAM,wBAAwB,UAAU;AAAA,SACpB,OAAe;AAAA,EACxC,WAAW,CAAC,UAAkB,eAAe;AAAA,IAC3C,MAAM,OAAO;AAAA;AAEjB;AAAA;AAEO,MAAM,2BAA2B,gBAAgB;AAAA,SAC7B,OAAe;AAAA,EACjC;AAAA,EAEA;AAAA,EACP,WAAW,CAA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