@powerhousedao/reactor-workflow 6.2.3-dev.61 → 6.2.3-dev.62
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/index.js +1 -1
- package/dist/{telemetry-DhYq0z32.js → telemetry-CBZzPM22.js} +2 -2
- package/dist/{telemetry-DhYq0z32.js.map → telemetry-CBZzPM22.js.map} +1 -1
- package/dist/testing.js +1 -1
- package/dist/worker-entry.js +685 -278
- package/dist/worker-entry.js.map +1 -1
- package/package.json +7 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"telemetry-DhYq0z32.js","names":["logger","gunzip","gunzipCb","isRecord","pkg.version","CORE_PIECE_NAME","logger","otelContext"],"sources":["../src/pieces/activepieces/types.ts","../src/pieces/activepieces/indeterminate.ts","../src/pieces/activepieces/registry-source.ts","../src/pieces/activepieces/fetch.ts","../src/pieces/activepieces/unsupported.ts","../src/pieces/activepieces/descriptor.ts","../src/pieces/activepieces/resolver.ts","../src/pieces/activepieces/worker/json-safe.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/worker/host-call.ts","../src/pieces/activepieces/context/limits.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/trigger.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/redact.ts","../src/pieces/activepieces/worker/reactor-rpc.ts","../src/pieces/activepieces/worker/transport.ts","../src/pieces/activepieces/worker/timings.ts","../src/pieces/activepieces/worker/host.ts","../src/pieces/activepieces/worker/pool.ts","../src/pieces/engine/types.ts","../src/pieces/engine/secrets.ts","../src/pieces/engine/expressions.ts","../src/pieces/core/branch-operators.ts","../src/pieces/engine/step-input.ts","../src/pieces/engine/connections.ts","../src/pieces/engine/attachment-cache.ts","../src/pieces/core/hints.ts","../src/pieces/core/actions.ts","../src/pieces/core/triggers.ts","../package.json","../src/pieces/core/version.ts","../src/pieces/core/index.ts","../src/pieces/builtin.ts","../src/pieces/engine/resolution.ts","../src/pieces/engine/blocks.ts","../src/pieces/engine/retry.ts","../src/pieces/engine/dynamic-props.ts","../src/pieces/engine/canonical.ts","../src/pieces/engine/coordinator.ts","../src/reactor/piece-registry.ts","../src/telemetry.ts"],"sourcesContent":["// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<\n DropdownOption<unknown>,\n \"label\" | \"value\"\n> &\n Partial<Pick<DropdownOption<unknown>, \"description\" | \"icon\">>;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<\n BasePropertySchema,\n \"displayName\" | \"description\" | \"placeholder\" | \"advanced\"\n >\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // FILE: hand the piece a stream instead of the bytes.\n streaming?: boolean;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n // Layout and control hints, each read off only the types that declare it.\n width?: string;\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // The core piece's form hints; see PiecePropDescriptor.\n showWhen?: unknown;\n emptyChoice?: unknown;\n };\n\n// Widened from PropertyGroupDisplay: tabs | section | summary | builder | footer.\nexport interface ApPropertyGroup {\n key?: string;\n display?: string;\n label?: string;\n description?: string;\n icon?: string;\n props?: string[];\n}\n\nexport interface ApErrorHandlingOption {\n defaultValue?: boolean;\n hide?: boolean;\n}\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n propertyGroups?: ApPropertyGroup[];\n // READ | SEARCH | WRITE | DESTRUCTIVE, widened for the cross-bundle reason.\n classification?: string;\n errorHandlingOptions?: {\n retryOnFailure?: ApErrorHandlingOption;\n continueOnFailure?: ApErrorHandlingOption;\n };\n // Output ports, read only off a piece the host runs in process.\n ports?: unknown;\n // \"read\" | \"write\"; anything else reads as undeclared.\n requireReactor?: unknown;\n run: (ctx: unknown) => Promise<unknown>;\n // Called instead of run by a single-step test.\n test?: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: unknown;\n requireReactor?: unknown;\n props?: Record<string, ApProperty>;\n propertyGroups?: ApPropertyGroup[];\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n // Widened from WebhookRenewConfiguration: CRON | NONE.\n renewConfiguration?: { strategy?: string; cronExpression?: string };\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n deprecated?: boolean;\n // An array when the piece offers several auth methods.\n auth?: ApProperty | ApProperty[];\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","// \"Nobody knows whether that write landed\", as a property an error carries.\n//\n// A step whose host call wrote something and then did not get an answer in\n// time is neither a success nor a failure, and reporting it as FAILED is a\n// claim nobody can stand behind — which is what the 10s host-call cap was\n// doing to a reactor dispatch under load (backlog item 6).\n//\n// The marker is an ENUMERABLE OWN PROPERTY rather than a class, because the\n// error is usually thrown in the forked child and reaches the coordinator as a\n// `SerializedPieceError`: a name, a message, and the error's own enumerable\n// properties. The class does not survive; the property does.\n//\n// The reactor RPC keeps only an error's name and message, so a reactor job\n// still unfinished at the step deadline is recognised by its name.\nimport { ReactorJobPendingError } from \"@powerhousedao/pieces-framework\";\n\n/** The property name, so both sides spell it once. */\nexport const INDETERMINATE_FLAG = \"indeterminate\";\n\n/** Marks an error as indeterminate, in place. */\nexport function markIndeterminate<T extends Error>(error: T): T {\n Object.defineProperty(error, INDETERMINATE_FLAG, {\n value: true,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n return error;\n}\n\nconst INDETERMINATE_NAMES: ReadonlySet<string> = new Set([\n ReactorJobPendingError,\n]);\n\nfunction named(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const name = (value as { name?: unknown }).name;\n return typeof name === \"string\" && INDETERMINATE_NAMES.has(name);\n}\n\nfunction flagged(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n return (value as Record<string, unknown>)[INDETERMINATE_FLAG] === true;\n}\n\n/**\n * Whether this error means \"the write may have landed\".\n *\n * Three places to look, in the order the error can reach us: the error itself\n * (thrown in the reactor process), the `properties` record of the\n * `SerializedPieceError` a `PieceWorkerError` carries (thrown in the child),\n * and the `cause` chain (a piece that wrapped it).\n */\nexport function isIndeterminateError(error: unknown): boolean {\n if (flagged(error) || named(error)) return true;\n const serialized = (\n error as { serialized?: { name?: unknown; properties?: unknown } }\n )?.serialized;\n if (flagged(serialized?.properties) || named(serialized)) return true;\n const cause = (error as { cause?: unknown })?.cause;\n return (\n cause !== undefined && cause !== error && (flagged(cause) || named(cause))\n );\n}\n","// A Powerhouse registry as a source of pieces: where this runtime reads piece\n// metadata and fetches piece code.\n\n// It serves the same three shapes cloud.activepieces.com and its CDN do — a\n// list, one piece's detail, a bundle tarball — at its own paths.\n\n// The registry is the one the host already installs packages from. A package\n// installed from it ships pieces that run in the worker with the same reach, so\n// a bundle fetched from it is no more trusted than one that arrived inside a\n// package; the trust boundary is the registry, and it is already drawn.\nimport { childLogger } from \"document-model\";\n\nconst logger = childLogger([\"workflow\", \"piece-registry\"]);\n\nexport interface PieceRegistrySource {\n /** Origin the piece endpoints hang off, without a trailing slash. */\n baseUrl: string;\n /** The catalog, in cloud.activepieces.com's list shape. */\n catalogUrl(suggestions?: boolean): string;\n /** One piece's detail, in the shape their piece endpoint answers with. */\n pieceUrl(name: string): string;\n /** The bundle; a folder per piece name keeps scoped names distinct. */\n tarballUrl(name: string, version: string): string;\n}\n\nfunction source(baseUrl: string): PieceRegistrySource {\n return {\n baseUrl,\n catalogUrl: (suggestions) =>\n suggestions\n ? `${baseUrl}/pieces?suggestionType=ACTION_AND_TRIGGER`\n : `${baseUrl}/pieces`,\n // Encoded whole, slash included: a scoped name is one path segment to the\n // registry's route, not two.\n pieceUrl: (name) => `${baseUrl}/pieces/${encodeURIComponent(name)}`,\n tarballUrl: (name, version) =>\n `${baseUrl}/-/pieces/bundled/${name}/${version}.tgz`,\n };\n}\n\n// Set by the host at composition from the registry it resolved for package\n// installs; absent on a host that installs no packages from one, and nothing\n// changes.\nlet configured: PieceRegistrySource | undefined;\n\nexport function setPieceRegistryUrl(url: string | undefined): void {\n const trimmed = url?.trim().replace(/\\/+$/, \"\") ?? \"\";\n if (trimmed === \"\") {\n configured = undefined;\n return;\n }\n if (configured?.baseUrl === trimmed) return;\n configured = source(trimmed);\n logger.info(`Pieces may be fetched from ${configured.baseUrl}`);\n}\n\n/** The registry at `baseUrl`, whichever one this host is configured with. */\nexport function pieceRegistrySourceAt(baseUrl: string): PieceRegistrySource {\n return source(baseUrl.replace(/\\/+$/, \"\"));\n}\n\nexport function pieceRegistrySource(): PieceRegistrySource | undefined {\n return configured;\n}\n","import { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gunzip as gunzipCb } from \"node:zlib\";\nimport {\n pieceRegistrySource,\n pieceRegistrySourceAt,\n type PieceRegistrySource,\n} from \"./registry-source.js\";\n\nconst gunzip = promisify(gunzipCb);\n\n// Mirrors their pieceBundle.resolve(): CDN bundle when served, else the npm\n// tarball. Tarballs are immutable per (name, version), so the cache never expires.\nconst DEFAULT_CDN_PIECES_URL = \"https://cdn.activepieces.com/pieces/bundled\";\nconst DEFAULT_NPM_REGISTRY_URL = \"https://registry.npmjs.org\";\n\nlet cdnPiecesUrl = DEFAULT_CDN_PIECES_URL;\nlet npmRegistryUrl = DEFAULT_NPM_REGISTRY_URL;\n\n// Host and test seam: the public CDN and npm registry a piece is fetched from.\nexport function setPublicPieceSources(sources: {\n cdnUrl?: string;\n npmRegistryUrl?: string;\n}): void {\n const trim = (url: string) => url.trim().replace(/\\/+$/, \"\");\n cdnPiecesUrl = sources.cdnUrl ? trim(sources.cdnUrl) : DEFAULT_CDN_PIECES_URL;\n npmRegistryUrl = sources.npmRegistryUrl\n ? trim(sources.npmRegistryUrl)\n : DEFAULT_NPM_REGISTRY_URL;\n}\n\nexport function npmRegistryBaseUrl(): string {\n return npmRegistryUrl;\n}\n\nexport function cdnTarballUrl(name: string, version: string): string {\n return `${cdnPiecesUrl}/${name.replace(\"/\", \"-\")}-${version}.tgz`;\n}\n\nexport function npmTarballUrl(name: string, version: string): string {\n const unscoped = name.startsWith(\"@\") ? name.split(\"/\")[1] : name;\n return `${npmRegistryUrl}/${name}/-/${unscoped}-${version}.tgz`;\n}\n\n// name/version come from a workflow step's pieceName and pieceVersion,\n// unconstrained strings.\nconst NPM_NAME_RE = /^(@[a-z0-9][a-z0-9-_.]*\\/)?[a-z0-9][a-z0-9-_.]*$/;\nconst NPM_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/;\n\nfunction assertValidPackageCoordinate(name: string, version: string): void {\n if (!NPM_NAME_RE.test(name)) {\n throw new Error(`Invalid piece package name: ${name}`);\n }\n if (!NPM_VERSION_RE.test(version)) {\n throw new Error(`Invalid piece package version: ${version}`);\n }\n}\n\n// Belt-and-suspenders: the path we're about to rm/rename must land under cacheDir.\nfunction assertWithinCacheDir(dir: string, cacheDir: string): void {\n const root = path.resolve(cacheDir);\n const resolved = path.resolve(dir);\n if (resolved !== root && !resolved.startsWith(root + path.sep)) {\n throw new Error(`Resolved piece cache path escapes cacheDir: ${dir}`);\n }\n}\n\nfunction readString(header: Buffer, offset: number, length: number): string {\n const slice = header.subarray(offset, offset + length);\n const nul = slice.indexOf(0);\n return slice.subarray(0, nul === -1 ? length : nul).toString(\"utf8\");\n}\n\n// Published piece bundles run a few hundred KB extracted; the cap is well clear\n// of that and bounds what a hostile or corrupt tarball can inflate to.\nconst MAX_EXTRACTED_BYTES = 64 * 1024 * 1024;\n\n// Caps the compressed transfer itself, before gunzip ever runs — the decompressed\n// cap above does nothing for a huge (not necessarily bomb-like) response body.\nconst MAX_COMPRESSED_BYTES = 64 * 1024 * 1024;\n\n// Minimal ustar extraction: regular files only, \"package/\" root stripped.\nasync function extractTarball(tgz: Buffer, dest: string): Promise<void> {\n // Async gunzip: the sync one blocks the reactor's event loop for every\n // request, not just this one, and inflation is unbounded without maxOutputLength.\n const tar = await gunzip(tgz, { maxOutputLength: MAX_EXTRACTED_BYTES }).catch(\n (error: unknown) => {\n throw new Error(`Failed to decompress piece bundle: ${String(error)}`);\n },\n );\n let offset = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n if (header.every((byte) => byte === 0)) break;\n const name = readString(header, 0, 100);\n const prefix = readString(header, 345, 155);\n const size = parseInt(readString(header, 124, 12).trim() || \"0\", 8);\n const type = String.fromCharCode(header[156]);\n offset += 512;\n const isFile = type === \"0\" || type === \"\\0\" || type === \"\";\n if (isFile && size >= 0) {\n const full = prefix ? `${prefix}/${name}` : name;\n const rel = full.replace(/^[^/]+\\//, \"\");\n const target = path.resolve(dest, rel);\n // Guard against path traversal from a hostile tarball.\n if (rel && target.startsWith(path.resolve(dest) + path.sep)) {\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, tar.subarray(offset, offset + size));\n }\n }\n offset += Math.ceil(size / 512) * 512;\n }\n}\n\nexport interface FetchPieceBundleOptions {\n name: string;\n version: string;\n cacheDir: string;\n timeoutMs?: number;\n // Where a piece an installed reactor package ships is served, when the\n // package itself came from a registry rather than this disk.\n entryUrl?: string;\n // How long the install of a bundle's declared dependencies may run, for the\n // few that declare any. Bounds a hung registry rather than budgeting work.\n installTimeoutMs?: number;\n // The only tarball sources to try, in order; every one when unset.\n sources?: readonly BundleSource[];\n // Cache subdirectory, so copies from different sources never alias.\n cacheScope?: string;\n}\n\n/** Where a bundle came from, \"cache\" being a copy one of the others left. */\nexport type BundleSource = \"package\" | \"registry\" | \"cdn\" | \"npm\";\n\nexport interface FetchedBundle {\n dir: string;\n source: BundleSource | \"cache\";\n // What the bundle's own manifest declares. Empty for 739 of the 760\n // published pieces, which is the path that costs nothing.\n dependencies: Record<string, string>;\n // Whether those declarations were installed beside it, rather than the\n // bundle being loaded straight out of its extraction.\n installed: boolean;\n}\n\n// Bounds the transfer before gunzip: rejects an over-limit Content-Length up\n// front, else tracks a running total as the body streams in.\nasync function readBoundedBody(\n response: Response,\n url: string,\n): Promise<Buffer> {\n const declared = response.headers.get(\"content-length\");\n if (declared && Number(declared) > MAX_COMPRESSED_BYTES) {\n throw new Error(\n `${url} exceeds the ${MAX_COMPRESSED_BYTES}-byte compressed size cap (Content-Length: ${declared})`,\n );\n }\n if (!response.body) return Buffer.from(await response.arrayBuffer());\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > MAX_COMPRESSED_BYTES) {\n await reader.cancel();\n throw new Error(\n `${url} exceeds the ${MAX_COMPRESSED_BYTES}-byte compressed size cap`,\n );\n }\n chunks.push(value);\n }\n return Buffer.concat(chunks);\n}\n\n// A Powerhouse registry this deployment allowed comes first, so a piece it\n// serves is not shadowed by an Activepieces piece of the same name.\nfunction tarballSources(\n name: string,\n version: string,\n only?: readonly BundleSource[],\n registry = pieceRegistrySource(),\n): { source: BundleSource; url: string }[] {\n const all = allTarballSources(name, version, registry);\n return only ? all.filter(({ source }) => only.includes(source)) : all;\n}\n\nfunction allTarballSources(\n name: string,\n version: string,\n registry: PieceRegistrySource | undefined,\n): { source: BundleSource; url: string }[] {\n return [\n ...(registry\n ? [\n {\n source: \"registry\" as const,\n url: registry.tarballUrl(name, version),\n },\n ]\n : []),\n { source: \"cdn\" as const, url: cdnTarballUrl(name, version) },\n { source: \"npm\" as const, url: npmTarballUrl(name, version) },\n ];\n}\n\nasync function downloadTarball(\n name: string,\n version: string,\n timeoutMs: number,\n only?: readonly BundleSource[],\n registry?: PieceRegistrySource,\n): Promise<{ tgz: Buffer; source: BundleSource }> {\n const sources = tarballSources(name, version, only, registry);\n let lastError: unknown;\n for (const { source, url } of sources) {\n try {\n const response = await fetch(url, {\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!response.ok) {\n lastError = new Error(`${url} responded ${response.status}`);\n continue;\n }\n return { tgz: await readBoundedBody(response, url), source };\n } catch (error) {\n lastError = error;\n }\n }\n throw new Error(\n `Failed to fetch piece bundle ${name}@${version}: ${String(lastError)}`,\n );\n}\n\nasync function extractDownloadedTarball(\n name: string,\n version: string,\n timeoutMs: number,\n staging: string,\n only?: readonly BundleSource[],\n): Promise<BundleSource> {\n const { tgz, source } = await downloadTarball(name, version, timeoutMs, only);\n await extractTarball(tgz, staging);\n return source;\n}\n\n// A piece from an installed reactor package, served by the registry that\n// package came from: its manifest, then the one file the manifest names.\n\n// `ph build` leaves each piece a self-contained module with a package.json\n// beside it, so those two files are the whole bundle.\nasync function downloadPackagePiece(\n entryUrl: string,\n staging: string,\n timeoutMs: number,\n): Promise<BundleSource> {\n const base = entryUrl.slice(0, entryUrl.lastIndexOf(\"/\") + 1);\n const fetchInto = async (url: string, name: string): Promise<Buffer> => {\n const response = await fetch(url, {\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!response.ok) {\n throw new Error(`${url} responded ${response.status}`);\n }\n const body = await readBoundedBody(response, url);\n await writeFile(path.join(staging, name), body);\n return body;\n };\n await mkdir(staging, { recursive: true });\n const manifest = await fetchInto(`${base}package.json`, \"package.json\");\n const main = (JSON.parse(manifest.toString(\"utf8\")) as { main?: unknown })\n .main;\n const entry =\n typeof main === \"string\" && main !== \"\"\n ? main\n : entryUrl.slice(base.length);\n // One segment: the manifest of a built piece names a file beside itself, and\n // a path that climbs out of the staging directory is not that.\n if (entry.includes(\"/\") || entry.includes(\"\\\\\") || entry.startsWith(\".\")) {\n throw new Error(\n `Piece manifest at ${base} names an unusable main: ${entry}`,\n );\n }\n await fetchInto(`${base}${entry}`, entry);\n return \"package\";\n}\n\nfunction bundleDirFor(options: FetchPieceBundleOptions): string {\n const leaf = `${options.name.replace(\"/\", \"-\")}-${options.version}`;\n return options.cacheScope\n ? path.join(options.cacheDir, options.cacheScope, leaf)\n : path.join(options.cacheDir, leaf);\n}\n\n// Downloads and extracts a published piece bundle, returning the directory to\n// hand to loadPieceFromDir(). A cached extraction is reused, and re-checked.\nexport async function fetchPieceBundle(\n options: FetchPieceBundleOptions,\n): Promise<FetchedBundle> {\n const { name, version, cacheDir, timeoutMs = 30_000 } = options;\n assertValidPackageCoordinate(name, version);\n const dir = bundleDirFor(options);\n assertWithinCacheDir(dir, cacheDir);\n if (existsSync(path.join(dir, \"package.json\"))) {\n return {\n dir,\n source: \"cache\",\n dependencies: await readDependencies(dir),\n installed: false,\n };\n }\n\n const staging = `${dir}.tmp-${process.pid}`;\n await rm(staging, { recursive: true, force: true });\n // A piece a package ships is served as its built module, not as a tarball,\n // so it is fetched file by file rather than extracted.\n const source = options.entryUrl\n ? await downloadPackagePiece(options.entryUrl, staging, timeoutMs)\n : await extractDownloadedTarball(\n name,\n version,\n timeoutMs,\n staging,\n options.sources,\n );\n await rm(dir, { recursive: true, force: true });\n try {\n await rename(staging, dir);\n } catch (error) {\n // Concurrent fetcher won the rename; its extraction is identical.\n await rm(staging, { recursive: true, force: true });\n if (!existsSync(path.join(dir, \"package.json\"))) throw error;\n }\n return {\n dir,\n source,\n dependencies: await readDependencies(dir),\n installed: false,\n };\n}\n\n// Concurrent callers for the same bundle share one download+extract rather\n// than racing each other through it.\nconst inFlight = new Map<string, Promise<FetchedBundle>>();\n\n// The way in: a bundle arrives extracted, cached and loadable, and callers\n// that ask for the same one at the same time wait on a single fetch.\nexport async function ensurePieceBundle(\n options: FetchPieceBundleOptions,\n): Promise<FetchedBundle> {\n const key = bundleDirFor(options);\n const pending = inFlight.get(key);\n if (pending) return pending;\n // Dropped once settled, refusals included, so a later caller re-checks the\n // bundle rather than inheriting this call's answer forever.\n const started = resolveBundle(options).finally(() => inFlight.delete(key));\n inFlight.set(key, started);\n return started;\n}\n\n// 739 of the 760 published pieces declare nothing, and they take the path they\n// always took: extract, load, no package manager anywhere near it.\n\n// The rest have their declarations installed beside them, once per name and\n// version, and the refusal is what is left when that cannot be done.\nasync function resolveBundle(\n options: FetchPieceBundleOptions,\n): Promise<FetchedBundle> {\n const fetched = await fetchPieceBundle(options);\n if (Object.keys(fetched.dependencies).length === 0) return fetched;\n return installPieceBundle(options, fetched);\n}\n\n// Installs a bundle plus its declared deps into an isolated workspace, the way\n// their piece-installer does: the bundle as a file: dependency, then install.\nasync function installPieceBundle(\n options: FetchPieceBundleOptions,\n fetched: FetchedBundle,\n): Promise<FetchedBundle> {\n const { name, version, cacheDir } = options;\n const timeoutMs = options.installTimeoutMs ?? INSTALL_TIMEOUT_MS;\n const workspace = `${bundleDirFor(options)}.install`;\n assertWithinCacheDir(workspace, cacheDir);\n const dir = path.join(workspace, \"node_modules\", name);\n // Written last, so a torn install is never mistaken for a finished one.\n if (\n existsSync(path.join(workspace, INSTALL_READY_MARKER)) &&\n existsSync(path.join(dir, \"package.json\"))\n ) {\n return {\n dir,\n source: \"cache\",\n dependencies: fetched.dependencies,\n installed: true,\n };\n }\n try {\n await stageInstallWorkspace(workspace, options);\n // A package's piece installs from the registry the package came from,\n // which proxies npm; an npm piece keeps the host's own npm config.\n await runInstall(workspace, timeoutMs, packageRegistry(options)?.baseUrl);\n await writeFile(path.join(workspace, INSTALL_READY_MARKER), \"true\");\n } catch (error) {\n // Swept, so the next attempt starts clean: a half-written node_modules\n // loads worse than none at all, and more confusingly.\n await rm(workspace, { recursive: true, force: true }).catch(\n () => undefined,\n );\n throw notInstallable(name, version, fetched.dependencies, error);\n }\n return {\n dir,\n source: fetched.source,\n dependencies: fetched.dependencies,\n installed: true,\n };\n}\n\n// \"<registry>/-/cdn/<package>@<version>/<file>\" -> \"<registry>\".\nexport function registryOf(entryUrl: string): string | undefined {\n const at = entryUrl.indexOf(\"/-/cdn/\");\n return at > 0 ? entryUrl.slice(0, at) : undefined;\n}\n\n// A package's piece comes from, and installs through, the package's registry.\nfunction packageRegistry(\n options: FetchPieceBundleOptions,\n): PieceRegistrySource | undefined {\n if (!options.entryUrl) return undefined;\n const base = registryOf(options.entryUrl);\n return base ? pieceRegistrySourceAt(base) : pieceRegistrySource();\n}\n\n// The tarball, not the directory already extracted: npm symlinks a directory\n// dependency, and node resolves a symlinked module from its realpath.\n\n// That realpath is back in the cache, where the installed deps are not, so\n// the tgz is what makes npm unpack a real directory under node_modules.\nasync function stageInstallWorkspace(\n workspace: string,\n options: FetchPieceBundleOptions,\n): Promise<void> {\n const { tgz } = await downloadTarball(\n options.name,\n options.version,\n options.timeoutMs ?? 30_000,\n options.sources,\n packageRegistry(options),\n );\n await rm(workspace, { recursive: true, force: true });\n await mkdir(workspace, { recursive: true });\n await writeFile(path.join(workspace, \"bundle.tgz\"), tgz);\n await writeFile(\n path.join(workspace, \"package.json\"),\n JSON.stringify({\n name: \"piece-workspace\",\n version: \"1.0.0\",\n private: true,\n dependencies: { [options.name]: \"file:./bundle.tgz\" },\n }),\n );\n}\n\n// Enough to recognise what the bundle wants without turning the refusal into\n// a wall of text.\nconst MAX_LISTED_DEPENDENCIES = 5;\n\n// Written into the workspace once the install has finished, so a cache hit is\n// a finished install and never a torn one.\nconst INSTALL_READY_MARKER = \"ready\";\n\n// A published piece pulls a handful of packages at most; this is a bound on a\n// hung registry, not a budget. Configurable for a slow or distant mirror.\nconst INSTALL_TIMEOUT_MS =\n Number(process.env.PH_WORKFLOWS_PIECE_INSTALL_TIMEOUT_MS) || 120_000;\n\n// npm, and only npm. It is on every image that can run this reactor, which bun\n// is not, and one package manager is one thing to keep --ignore-scripts true of.\n\n// Activepieces use bun and it is much faster, but the install is cached per\n// name and version and off every hot path, so what it would buy is one-off.\nfunction installCommand(registry?: string): {\n file: string;\n args: string[];\n shell: boolean;\n} {\n // Windows installs npm as npm.cmd, which only a shell can spawn.\n const windows = process.platform === \"win32\";\n return {\n file: windows ? \"npm.cmd\" : \"npm\",\n // --ignore-scripts is not optional and has no switch to turn it off: it is\n // what makes installing a third party's package at runtime defensible.\n args: [\n \"install\",\n \"--ignore-scripts\",\n \"--no-audit\",\n \"--no-fund\",\n \"--omit=dev\",\n \"--loglevel=error\",\n ...(registry ? [`--registry=${registry}/`] : []),\n ],\n shell: windows,\n };\n}\n\nasync function runInstall(\n cwd: string,\n timeoutMs: number,\n registry?: string,\n): Promise<void> {\n const { file, args, shell } = installCommand(registry);\n await new Promise<void>((resolve, reject) => {\n execFile(\n file,\n args,\n // No bunfig to inherit: npm reads the host's config, and only the\n // registry above overrides it.\n { cwd, timeout: timeoutMs, shell, windowsHide: true },\n (error, _stdout, stderr) => {\n if (!error) return resolve();\n const killed = (error as { killed?: boolean }).killed === true;\n // npm's \"a complete log of this run\" line points at a file nobody\n // reading a reactor log can open; the cause above it is the message.\n const reported = stderr\n .split(\"\\n\")\n .filter((line) => !line.includes(\"A complete log of this run\"))\n .join(\"\\n\")\n .trim();\n reject(\n new Error(\n killed\n ? `timed out after ${timeoutMs}ms`\n : reported || error.message,\n ),\n );\n },\n );\n });\n}\n\n// What is left when a bundle names code it does not carry and that code could\n// not be fetched: the piece is unloadable, and this says what was tried.\nexport class PieceNotInstallableError extends Error {\n constructor(\n readonly packageName: string,\n readonly version: string,\n readonly dependencies: Record<string, string>,\n readonly cause: unknown,\n ) {\n const declared = Object.keys(dependencies);\n const listed = declared\n .slice(0, MAX_LISTED_DEPENDENCIES)\n .map((dep) => `${dep}@${dependencies[dep]}`);\n const rest = declared.length - listed.length;\n const count =\n declared.length === 1\n ? \"a dependency\"\n : `${declared.length} dependencies`;\n super(\n `Piece bundle ${packageName}@${version} carries ${count} it does not ` +\n `bundle (${listed.join(\", \")}${rest > 0 ? `, and ${rest} more` : \"\"}), ` +\n `and installing them here failed: ${reasonOf(cause)}. ` +\n `The install runs once per version, with lifecycle scripts disabled, so ` +\n `a dependency that builds or downloads on install cannot be prepared ` +\n `this way. Check that this reactor can reach an npm registry, or run a ` +\n `piece whose bundle inlines what it needs.`,\n );\n this.name = \"PieceNotInstallableError\";\n }\n}\n\nfunction reasonOf(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction notInstallable(\n name: string,\n version: string,\n dependencies: Record<string, string>,\n cause: unknown,\n): PieceNotInstallableError {\n return new PieceNotInstallableError(name, version, dependencies, cause);\n}\n\nasync function readDependencies(dir: string): Promise<Record<string, string>> {\n const raw = await readFile(path.join(dir, \"package.json\"), \"utf8\");\n const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> };\n return pkg.dependencies ?? {};\n}\n","import { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\nimport { Cron } from \"croner\";\n\n// Piece features this engine cannot run. Read off a loaded piece or off its\n// published listing alike, since both carry auth and triggers as data.\nconst ISSUES_URL = \"https://github.com/powerhouse-inc/powerhouse/issues/\";\n\nexport interface UnsupportedFeature {\n feature: string;\n issue: number;\n // \"<feature> is not supported yet (<issue url>)\", what a listing shows.\n reason: string;\n}\n\nfunction unsupported(feature: string, issue: number): UnsupportedFeature {\n return {\n feature,\n issue,\n reason: `${feature} is not supported yet (${ISSUES_URL}${issue})`,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// A piece's auth, from the bundle or the listing. With several methods the\n// piece runs if any one does; the connection picks which.\nexport function unsupportedAuth(auth: unknown): UnsupportedFeature | undefined {\n if (Array.isArray(auth)) {\n const reasons = auth.map(unsupportedMethod);\n return reasons.some((reason) => reason === undefined)\n ? undefined\n : reasons[0];\n }\n return unsupportedMethod(auth);\n}\n\n// The method a connection of `type` signs in with: the piece's only auth,\n// or the entry of that type among several (upstream's getAuthPropertyForValue).\nexport function authMethodFor(auth: unknown, type: unknown): unknown {\n if (!Array.isArray(auth)) return auth;\n return auth.find((entry) => isRecord(entry) && entry.type === type);\n}\n\nfunction unsupportedMethod(auth: unknown): UnsupportedFeature | undefined {\n if (!isRecord(auth)) return undefined;\n if (auth.type === \"OAUTH2\" && auth.grantType === \"client_credentials\") {\n return unsupported(\"OAuth2 client credentials\", 3091);\n }\n if (auth.type === \"OIDC\") return unsupported(\"OIDC auth\", 3091);\n if (auth.type === \"CUSTOM_AUTH\" && auth.refresh != null) {\n return unsupported(\"CustomAuth refresh\", 3091);\n }\n return undefined;\n}\n\n// A piece trigger; the core piece's triggers are fed by the host and never pass here.\nexport function unsupportedTrigger(trigger: {\n type?: unknown;\n renewConfiguration?: unknown;\n}): UnsupportedFeature | undefined {\n if (trigger.type === \"MANUAL\") {\n return unsupported(\"TriggerStrategy.MANUAL\", 3091);\n }\n const strategy = checkTriggerStrategy(trigger.type);\n if (\"issue\" in strategy) {\n const issue = trigger.type === \"APP_WEBHOOK\" ? 3081 : 3091;\n return {\n feature: `TriggerStrategy ${String(trigger.type)}`,\n issue,\n reason: `${strategy.issue} (${ISSUES_URL}${issue})`,\n };\n }\n const problem = renewProblem(trigger.renewConfiguration);\n if (problem) {\n return {\n feature: \"renewConfiguration\",\n issue: 3090,\n reason: `renewConfiguration ${problem} (${ISSUES_URL}3090)`,\n };\n }\n return undefined;\n}\n\n// A subscription the supervisor renews on a UTC cron by calling onRenew.\nexport interface TriggerRenew {\n strategy: \"CRON\";\n cronExpression: string;\n}\n\nfunction cronFires(cron: string): boolean {\n try {\n return (\n new Cron(cron, { timezone: \"UTC\", legacyMode: false }).nextRun() !== null\n );\n } catch {\n return false;\n }\n}\n\n// createTrigger fills in { strategy: \"NONE\" } for every trigger.\nfunction renewProblem(renew: unknown): string | undefined {\n if (renew === undefined || renew === null) return undefined;\n if (!isRecord(renew)) return \"is not an object\";\n if (renew.strategy === \"NONE\") return undefined;\n if (renew.strategy !== \"CRON\") {\n return `strategy ${String(renew.strategy)} is not supported`;\n }\n const cron = renew.cronExpression;\n if (typeof cron !== \"string\" || !cronFires(cron)) {\n return `cron ${JSON.stringify(cron)} is invalid`;\n }\n return undefined;\n}\n\n// The trigger's renewal, when it declares a valid CRON one.\nexport function triggerRenew(trigger: {\n renewConfiguration?: unknown;\n}): TriggerRenew | undefined {\n const renew = trigger.renewConfiguration;\n if (!isRecord(renew) || renew.strategy !== \"CRON\") return undefined;\n if (renewProblem(renew)) return undefined;\n return { strategy: \"CRON\", cronExpression: renew.cronExpression as string };\n}\n\nexport class UnsupportedPieceFeatureError extends Error {\n readonly feature: string;\n readonly issue: number;\n\n constructor(subject: string, unsupportedFeature: UnsupportedFeature) {\n super(`${subject}: ${unsupportedFeature.reason}`);\n this.name = \"UnsupportedPieceFeatureError\";\n this.feature = unsupportedFeature.feature;\n this.issue = unsupportedFeature.issue;\n }\n}\n","import type { RequireReactor } from \"@powerhousedao/pieces-framework\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApPropertyType,\n type ApDropdownOption,\n type ApPropertyGroup,\n type ApTrigger,\n type ApTriggerStrategy,\n} from \"./types.js\";\nimport {\n triggerRenew,\n unsupportedAuth,\n unsupportedTrigger,\n type TriggerRenew,\n type UnsupportedFeature,\n} from \"./unsupported.js\";\n\nexport interface PiecePropDescriptor {\n name: string;\n displayName: string;\n description?: string;\n placeholder?: string;\n type: ApPropertyType;\n required: boolean;\n defaultValue?: unknown;\n // STATIC_DROPDOWN choices, extracted so the editor needs no runtime call.\n staticOptions?: ApDropdownOption[];\n // True when the prop carries a design-time resolver (DROPDOWN options() / DYNAMIC props()).\n hasDynamicResolver: boolean;\n // Synthesised domain-provider id: activepieces:<pkg>#<action>.<prop> (doc 08 §6.3).\n // Only top-level props get one; nested resolvers are not addressable yet.\n dynamicResolverId?: string;\n // Sibling prop names whose values feed the resolver; the editor re-runs\n // it when any of them changes.\n refreshers?: string[];\n // Nested shape: an ARRAY item's fields, or the props a DYNAMIC resolver\n // produced (see describeProperties). OBJECT props are free-form and carry none.\n properties?: PiecePropDescriptor[];\n // Activepieces' layout hint: rendered in the collapsed advanced section.\n advanced?: boolean;\n // Layout and control hints (see describeHints); absent when not declared.\n width?: \"half\" | \"full\";\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // A STATIC_DROPDOWN's own state, beside its options.\n staticDisabled?: boolean;\n staticPlaceholder?: string;\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport interface PiecePropertyGroupDescriptor {\n key: string;\n display: string;\n label?: string;\n description?: string;\n icon?: string;\n props: string[];\n}\n\nexport interface PieceErrorHandlingDescriptor {\n retryOnFailure?: { defaultValue?: boolean; hide?: boolean };\n continueOnFailure?: { defaultValue?: boolean; hide?: boolean };\n}\n\nexport interface PieceActionDescriptor {\n name: string;\n displayName: string;\n description?: string;\n // UI metadata only — not a credential contract (spike finding).\n requireAuth: boolean;\n // The reactor access the step asks for; absent when it asks for none.\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n // Output ports the step can leave on; the editor draws only these.\n ports: readonly string[];\n // Carried verbatim: it is what the expression picker builds a later step's\n // field list from, and a package piece has no published listing to read.\n outputSchema?: unknown;\n // Orders the action picker, so a package piece that declares it must be\n // ordered by it too rather than counting as unset.\n audience?: string;\n propertyGroups?: PiecePropertyGroupDescriptor[];\n classification?: string;\n errorHandlingOptions?: PieceErrorHandlingDescriptor;\n}\n\nexport interface PieceTriggerDescriptor {\n name: string;\n displayName: string;\n description?: string;\n strategy: ApTriggerStrategy;\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: string;\n requireAuth: boolean;\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n ports: readonly string[];\n propertyGroups?: PiecePropertyGroupDescriptor[];\n outputSchema?: unknown;\n hasSampleData: boolean;\n // The sample itself, not just whether there is one: a trigger that declares\n // no outputSchema is read for its shape instead.\n sampleData?: unknown;\n // How the sender proves the endpoint exists before it will register it.\n // Absent when the trigger declares no handshake, or declares NONE.\n handshake?: { strategy: string; paramName?: string };\n // When the provider's subscription must be renewed; absent for NONE.\n renew?: TriggerRenew;\n // A trigger feature the engine cannot run; the piece's own is on the piece.\n unsupported?: UnsupportedFeature;\n}\n\nexport interface PieceAuthDescriptor {\n type: ApPropertyType;\n displayName?: string;\n description?: string;\n required?: boolean;\n // CUSTOM_AUTH's own fields. Without them a connection form has nothing to\n // ask for, which is what a piece read from a package rather than a published\n // listing would otherwise leave the editor with.\n props?: PiecePropDescriptor[];\n // OAUTH2 only: where and how the provider signs a user in.\n oauth2?: OAuth2MethodDescriptor;\n // Set when this engine can't sign in this way (OIDC, for one).\n unsupported?: UnsupportedFeature;\n}\n\nexport interface OAuth2MethodDescriptor {\n // May hold `{prop}` placeholders, filled from the connection's props.\n authUrl: string;\n tokenUrl: string;\n scope: string[];\n prompt?: \"none\" | \"consent\" | \"login\" | \"omit\";\n pkce?: boolean;\n pkceMethod?: \"plain\" | \"S256\";\n authorizationMethod?: \"HEADER\" | \"BODY\";\n grantType?: string;\n // Extra authorize-URL parameters, e.g. access_type=offline.\n extra?: Record<string, string>;\n}\n\nfunction describeOAuth2(\n raw: Record<string, unknown>,\n): OAuth2MethodDescriptor | undefined {\n if (typeof raw.authUrl !== \"string\" || typeof raw.tokenUrl !== \"string\") {\n return undefined;\n }\n const strings = (value: unknown) =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n const extra =\n raw.extra && typeof raw.extra === \"object\"\n ? Object.fromEntries(\n Object.entries(raw.extra).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n )\n : undefined;\n return {\n authUrl: raw.authUrl,\n tokenUrl: raw.tokenUrl,\n scope: strings(raw.scope),\n ...(typeof raw.prompt === \"string\"\n ? { prompt: raw.prompt as OAuth2MethodDescriptor[\"prompt\"] }\n : {}),\n ...(typeof raw.pkce === \"boolean\" ? { pkce: raw.pkce } : {}),\n ...(raw.pkceMethod === \"plain\" || raw.pkceMethod === \"S256\"\n ? { pkceMethod: raw.pkceMethod }\n : {}),\n ...(raw.authorizationMethod === \"HEADER\" ||\n raw.authorizationMethod === \"BODY\"\n ? { authorizationMethod: raw.authorizationMethod }\n : {}),\n ...(typeof raw.grantType === \"string\" ? { grantType: raw.grantType } : {}),\n ...(extra && Object.keys(extra).length > 0 ? { extra } : {}),\n };\n}\n\n// NONE is how the framework spells \"no handshake\", so it is not carried:\n// a caller checking the field would otherwise have to know that too.\nfunction describeHandshake(\n trigger: ApTrigger,\n): { strategy: string; paramName?: string } | undefined {\n const strategy = trigger.handshakeConfiguration?.strategy;\n if (!strategy || strategy === \"NONE\") return undefined;\n return { strategy, paramName: trigger.handshakeConfiguration?.paramName };\n}\n\nexport interface PieceSource {\n packageName: string;\n version: string;\n}\n\n// Serializable descriptor of an adapted piece; the engine never learns\n// Activepieces exists (doc 08 §6.2).\nexport interface PieceDescriptor {\n id: string;\n source: PieceSource;\n displayName: string;\n description?: string;\n logoUrl?: string;\n categories?: string[];\n deprecated?: boolean;\n // A list when the piece offers several sign-in methods.\n auth?: PieceAuthDescriptor | PieceAuthDescriptor[];\n minimumSupportedRelease?: string;\n maximumSupportedRelease?: string;\n actions: PieceActionDescriptor[];\n triggers: PieceTriggerDescriptor[];\n // Set when no block of the piece can run here, e.g. an OAuth2 piece.\n unsupported?: UnsupportedFeature;\n}\n\nfunction optional<K extends string, V>(\n key: K,\n value: V | undefined,\n): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\nexport function describeOption(option: ApDropdownOption): ApDropdownOption {\n return {\n label: option.label,\n value: option.value,\n ...(typeof option.description === \"string\" && option.description\n ? { description: option.description }\n : {}),\n ...(typeof option.icon === \"string\" && option.icon\n ? { icon: option.icon }\n : {}),\n };\n}\n\n// Copied only when well-formed: a foreign bundle may carry anything here.\nfunction describeHints(prop: ApProperty): Partial<PiecePropDescriptor> {\n const hints: Partial<PiecePropDescriptor> = {};\n if (prop.width === \"half\" || prop.width === \"full\") hints.width = prop.width;\n const strings = [\"icon\", \"variant\", \"display\", \"formatProperty\"] as const;\n for (const key of strings) {\n const value = prop[key];\n if (typeof value === \"string\" && value !== \"\") hints[key] = value;\n }\n const numbers = [\"min\", \"max\", \"step\"] as const;\n for (const key of numbers) {\n const value = prop[key];\n if (typeof value === \"number\" && Number.isFinite(value)) hints[key] = value;\n }\n if (Array.isArray(prop.reveals)) {\n const reveals = prop.reveals.filter(\n (name): name is string => typeof name === \"string\",\n );\n if (reveals.length > 0) hints.reveals = reveals;\n }\n if (prop.refreshOnSearch === true) hints.refreshOnSearch = true;\n const showWhen = prop.showWhen as { prop?: unknown; oneOf?: unknown } | null;\n if (typeof showWhen?.prop === \"string\" && Array.isArray(showWhen.oneOf)) {\n const oneOf: unknown[] = showWhen.oneOf;\n hints.showWhen = { prop: showWhen.prop, oneOf: [...oneOf] };\n }\n if (typeof prop.emptyChoice === \"string\" && prop.emptyChoice !== \"\") {\n hints.emptyChoice = prop.emptyChoice;\n }\n return hints;\n}\n\nfunction describeGroups(\n groups: ApPropertyGroup[] | undefined,\n): PiecePropertyGroupDescriptor[] | undefined {\n if (!Array.isArray(groups)) return undefined;\n const described = groups\n .filter(\n (group) =>\n typeof group.key === \"string\" &&\n typeof group.display === \"string\" &&\n Array.isArray(group.props),\n )\n .map((group) => ({\n key: group.key!,\n display: group.display!,\n ...(group.label ? { label: group.label } : {}),\n ...(group.description ? { description: group.description } : {}),\n ...(group.icon ? { icon: group.icon } : {}),\n props: group.props!.filter(\n (name): name is string => typeof name === \"string\",\n ),\n }));\n return described.length > 0 ? described : undefined;\n}\n\nfunction hasResolver(prop: ApProperty): boolean {\n return typeof prop.options === \"function\" || typeof prop.props === \"function\";\n}\n\nfunction toPropDescriptor(\n name: string,\n prop: ApProperty,\n resolverId?: string,\n): PiecePropDescriptor {\n const dynamic = hasResolver(prop);\n const descriptor: PiecePropDescriptor = {\n name,\n displayName: prop.displayName ?? name,\n type: prop.type ?? \"UNKNOWN\",\n required: prop.required ?? false,\n hasDynamicResolver: dynamic,\n };\n if (typeof prop.description === \"string\" && prop.description !== \"\") {\n descriptor.description = prop.description;\n }\n if (typeof prop.placeholder === \"string\" && prop.placeholder !== \"\") {\n descriptor.placeholder = prop.placeholder;\n }\n if (prop.defaultValue !== undefined) {\n descriptor.defaultValue = prop.defaultValue;\n }\n if (prop.advanced === true) descriptor.advanced = true;\n if (dynamic && resolverId) {\n descriptor.dynamicResolverId = resolverId;\n }\n if (dynamic && Array.isArray(prop.refreshers)) {\n descriptor.refreshers = prop.refreshers.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n }\n if (typeof prop.options === \"object\" && Array.isArray(prop.options.options)) {\n descriptor.staticOptions = prop.options.options.map(describeOption);\n if (prop.options.disabled === true) descriptor.staticDisabled = true;\n if (typeof prop.options.placeholder === \"string\") {\n descriptor.staticPlaceholder = prop.options.placeholder;\n }\n }\n Object.assign(descriptor, describeHints(prop));\n if (prop.properties && typeof prop.properties === \"object\") {\n const nested = describeProperties(prop.properties);\n if (nested.length > 0) descriptor.properties = nested;\n }\n return descriptor;\n}\n\n// Descriptor list for a props map: nested ARRAY items and what a DYNAMIC\n// resolver returns, so the editor never sees raw piece properties.\nexport function describeProperties(\n props: Record<string, ApProperty> | null | undefined,\n resolverIdFor?: (propName: string) => string,\n): PiecePropDescriptor[] {\n if (!props || typeof props !== \"object\") return [];\n return Object.entries(props)\n .filter((entry): entry is [string, ApProperty] =>\n isPropertyObject(entry[1]),\n )\n .map(([propName, prop]) =>\n toPropDescriptor(propName, prop, resolverIdFor?.(propName)),\n );\n}\n\n// Bundles are duck-typed; a props map may carry non-object junk.\nfunction isPropertyObject(value: unknown): value is ApProperty {\n return value !== null && typeof value === \"object\";\n}\n\nfunction withUnsupported(feature: UnsupportedFeature | undefined): {\n unsupported?: UnsupportedFeature;\n} {\n return feature ? { unsupported: feature } : {};\n}\n\n// Pure translation over a loaded piece; performs no I/O and never executes\n// piece code beyond the actions()/triggers() accessors.\nfunction describeAuthMethod(auth: unknown): PieceAuthDescriptor | undefined {\n if (!auth || typeof auth !== \"object\") return undefined;\n const method = auth as ApProperty;\n // CUSTOM_AUTH carries a record here; a DYNAMIC prop would carry a\n // resolver function, which is not an auth shape at all.\n const props =\n method.props && typeof method.props === \"object\"\n ? describeProperties(method.props)\n : [];\n const oauth2 =\n method.type === \"OAUTH2\"\n ? describeOAuth2(auth as Record<string, unknown>)\n : undefined;\n return {\n type: method.type ?? \"UNKNOWN\",\n displayName: method.displayName,\n description: method.description,\n required: method.required,\n ...(props.length > 0 ? { props } : {}),\n ...(oauth2 ? { oauth2 } : {}),\n ...withUnsupported(unsupportedAuth(method)),\n };\n}\n\nfunction declaredPorts(ports: unknown): readonly string[] | undefined {\n if (!Array.isArray(ports) || ports.length === 0) return undefined;\n return ports.every((port) => typeof port === \"string\")\n ? (ports as string[])\n : undefined;\n}\n\n// Only a well-formed declaration is carried: a foreign bundle may hold anything.\nfunction declaredReactor(value: unknown): RequireReactor | undefined {\n return value === \"read\" || value === \"write\" ? value : undefined;\n}\n\nexport interface BuildDescriptorOptions {\n // Read each action's own `ports`: only a piece whose results the host routes.\n routed?: boolean;\n // The host feeds the triggers itself, so no trigger strategy is refused.\n hostFed?: boolean;\n}\n\nexport function buildDescriptor(\n piece: ApPiece,\n source: PieceSource,\n options: BuildDescriptorOptions = {},\n): PieceDescriptor {\n const actions = Object.entries(getActions(piece)).map(\n ([actionName, action]): PieceActionDescriptor => ({\n name: action.name ?? actionName,\n displayName: action.displayName ?? actionName,\n description: action.description,\n requireAuth: action.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(action.requireReactor)),\n ports:\n (options.routed ? declaredPorts(action.ports) : undefined) ??\n PIECE_ACTION_PORTS,\n props: describeProperties(\n action.props,\n (propName) =>\n `activepieces:${source.packageName}#${actionName}.${propName}`,\n ),\n ...(action.outputSchema !== undefined\n ? { outputSchema: action.outputSchema }\n : {}),\n ...(action.audience !== undefined ? { audience: action.audience } : {}),\n ...optional(\"propertyGroups\", describeGroups(action.propertyGroups)),\n ...optional(\n \"classification\",\n typeof action.classification === \"string\"\n ? action.classification\n : undefined,\n ),\n ...optional(\"errorHandlingOptions\", action.errorHandlingOptions),\n }),\n );\n\n const triggers = Object.entries(getTriggers(piece)).map(\n ([triggerName, trigger]): PieceTriggerDescriptor => ({\n name: trigger.name ?? triggerName,\n displayName: trigger.displayName ?? triggerName,\n description: trigger.description,\n strategy: trigger.type ?? \"UNKNOWN\",\n testStrategy: trigger.testStrategy,\n ...(typeof trigger.display === \"string\" && trigger.display !== \"\"\n ? { display: trigger.display }\n : {}),\n requireAuth: trigger.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(trigger.requireReactor)),\n ports: TRIGGER_PORTS,\n props: describeProperties(\n trigger.props,\n (propName) =>\n `activepieces:${source.packageName}#${triggerName}.${propName}`,\n ),\n ...(trigger.outputSchema !== undefined\n ? { outputSchema: trigger.outputSchema }\n : {}),\n hasSampleData:\n trigger.sampleData !== undefined && trigger.sampleData !== null,\n ...(trigger.sampleData !== undefined && trigger.sampleData !== null\n ? { sampleData: trigger.sampleData }\n : {}),\n handshake: describeHandshake(trigger),\n ...optional(\"renew\", triggerRenew(trigger)),\n ...optional(\"propertyGroups\", describeGroups(trigger.propertyGroups)),\n ...(options.hostFed ? {} : withUnsupported(unsupportedTrigger(trigger))),\n }),\n );\n\n const descriptor: PieceDescriptor = {\n id: `activepieces:${source.packageName}`,\n source,\n displayName: piece.displayName,\n description: piece.description,\n logoUrl: piece.logoUrl,\n categories: piece.categories,\n ...(piece.deprecated === true ? { deprecated: true } : {}),\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n actions,\n triggers,\n ...withUnsupported(unsupportedAuth(piece.auth)),\n };\n // Several methods stay a list, in the piece's order; each says whether this\n // engine can run it.\n if (Array.isArray(piece.auth)) {\n const methods = piece.auth\n .map(describeAuthMethod)\n .filter((method) => method !== undefined);\n if (methods.length > 0) descriptor.auth = methods;\n } else {\n const method = describeAuthMethod(piece.auth);\n if (method) descriptor.auth = method;\n }\n return descriptor;\n}\n","// Where a piece's code comes from: the source a block resolution chose.\n\n// A published piece is a bundle fetched and cached on disk; a package piece\n// ships inside an installed reactor package, on disk or served by a registry.\nimport type { PieceOrigin } from \"../engine/resolution.js\";\nimport { ensurePieceBundle, type BundleSource } from \"./fetch.js\";\nimport type { PieceModuleRef } from \"./worker/protocol.js\";\n\nexport interface ResolvedPiece extends PieceModuleRef {\n name: string;\n version: string;\n // True when the piece is code the operator installed.\n local: boolean;\n}\n\n// One version of one piece, from one source. No source tries every download\n// source in turn, which is what a caller outside a reactor gets.\nexport interface PieceTarget {\n name: string;\n version: string;\n source?: PieceOrigin;\n}\n\nexport interface PieceResolver {\n resolve(target: PieceTarget): Promise<ResolvedPiece>;\n}\n\n// A piece found in an installed reactor package: a module file, or a directory\n// in npm-bundle shape when the package ships one already bundled.\nexport interface LocalPiece {\n name: string;\n version: string;\n entryPath?: string;\n bundleDir?: string;\n // Set instead of the two above when the package was loaded from a registry:\n // the piece is declared and served, but nothing of it is on this disk yet.\n entryUrl?: string;\n}\n\n// May answer asynchronously: a host whose registry loads on first use waits\n// here rather than racing every caller to have loaded it first.\nexport type LocalPieceLookup = (\n name: string,\n) => LocalPiece | undefined | Promise<LocalPiece | undefined>;\n\n// One entry of a reactor package's `pieces` export: which piece it ships and\n// where the built bundle sits, relative to the package root.\nexport type { PackagePiece } from \"@powerhousedao/pieces-framework\";\n\n// Download sources per resolved source. Activepieces bytes are the same on\n// their CDN and on npm, so both serve that source.\nconst DOWNLOADS: Record<Exclude<PieceOrigin, \"local\">, BundleSource[]> = {\n registry: [\"registry\"],\n activepieces: [\"cdn\", \"npm\"],\n npm: [\"npm\"],\n};\n\nexport class PieceNotInstalledError extends Error {\n constructor(name: string, version: string) {\n super(`Piece ${name}@${version} is not installed on this reactor`);\n this.name = \"PieceNotInstalledError\";\n }\n}\n\n// Fetches from the source the resolution chose, and from nowhere else.\nexport function sourcedResolver(options: {\n cacheDir: string;\n lookup?: LocalPieceLookup;\n timeoutMs?: number;\n}): PieceResolver {\n const fetch = (\n target: PieceTarget,\n extra: { entryUrl?: string; sources?: BundleSource[]; scope?: string },\n ) =>\n ensurePieceBundle({\n name: target.name,\n version: target.version,\n cacheDir: options.cacheDir,\n ...(extra.entryUrl ? { entryUrl: extra.entryUrl } : {}),\n ...(extra.sources ? { sources: extra.sources } : {}),\n ...(extra.scope ? { cacheScope: extra.scope } : {}),\n ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n });\n return {\n async resolve(target: PieceTarget): Promise<ResolvedPiece> {\n const { name, version, source } = target;\n if (source === \"local\") {\n const local = await options.lookup?.(name);\n if (!local || local.version !== version) {\n throw new PieceNotInstalledError(name, version);\n }\n if (local.entryPath || local.bundleDir) {\n return {\n name,\n version,\n ...(local.entryPath ? { entryPath: local.entryPath } : {}),\n ...(local.bundleDir ? { bundleDir: local.bundleDir } : {}),\n local: true,\n };\n }\n if (!local.entryUrl) throw new PieceNotInstalledError(name, version);\n // Declared by a package loaded from a registry: served at entryUrl.\n const bundle = await fetch(target, {\n entryUrl: local.entryUrl,\n scope: \"local\",\n });\n return { name, version, bundleDir: bundle.dir, local: true };\n }\n const bundle = await fetch(\n target,\n source ? { sources: DOWNLOADS[source], scope: source } : {},\n );\n return { name, version, bundleDir: bundle.dir, local: false };\n },\n };\n}\n\n// Every download source in turn: registry, CDN, npm.\nexport function bundleResolver(options: {\n cacheDir: string;\n timeoutMs?: number;\n}): PieceResolver {\n return sourcedResolver(options);\n}\n\n// What a request hands the worker, from whichever source answered.\nexport function pieceModuleRef(piece: ResolvedPiece): PieceModuleRef {\n return piece.entryPath\n ? { entryPath: piece.entryPath }\n : { bundleDir: piece.bundleDir };\n}\n","// Everything the child sends crosses a structured-clone boundary. A piece's\n// own objects routinely do not survive it, so they are flattened first.\nexport function jsonSafe(value: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(value)) as unknown;\n } catch {\n return String(value);\n }\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { PropsValidationErrors } from \"../context/normalize.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n // Why the host could not stage it; a FILE prop that needs it fails with this.\n error?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n // Epoch ms at which the host kills the worker for this request.\n deadline?: number;\n // Cap on each host call. Absent leaves the built-in default.\n hostCallTimeoutMs?: number;\n}\n\n// `ctx.reactor` for one request: its RPC messages carry `requestId`, and the\n// host serves them only while the request is in flight.\nexport interface ReactorRequestBinding {\n requestId: string;\n requireReactor: \"read\" | \"write\";\n}\n\nexport interface ReactorScopedRequest {\n // Stamped by PieceWorker when the caller serves the reactor.\n reactor?: ReactorRequestBinding;\n}\n\nexport const REACTOR_RPC = \"reactor-rpc\";\nexport const MODEL_MANIFEST = \"model-manifest\";\n// Host call: a type's entries, or every entry the host knows without one.\nexport const MODEL_ENTRIES = \"model-entries\";\n\n// One reactor RPC message (`@powerhousedao/reactor/rpc`), either direction.\nexport interface ReactorRpcEnvelope {\n type: typeof REACTOR_RPC;\n requestId: string;\n message: unknown;\n}\n\n// Importable document models (the reactor's ModelManifestEntry), host to child\n// on fork. A type loaded later is looked up through MODEL_ENTRIES.\nexport interface ModelEntriesPayload {\n documentType?: string;\n}\n\nexport interface ModelManifestMessage {\n type: typeof MODEL_MANIFEST;\n entries: unknown[];\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n // The delivery that woke a RESUME run, served as ctx.resumePayload. This\n // engine never suspends a run, so nothing sets it yet; absent, the context\n // member keeps throwing by name.\n resumePayload?: unknown;\n // Call the action's test method instead of run, as a single-step test does.\n stepTest?: boolean;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // ctx.project.id, the same one a run of the piece is handed.\n projectId?: string;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\" | \"onRenew\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece's auth declares no validate.\n declared: boolean;\n // validate's verdict; true when none is declared.\n valid: boolean;\n // Why validate failed, when it said so.\n detail?: string;\n // getConnectionIdentifier's label; it runs only once the check passes.\n accountLabel?: string;\n // Why getConnectionIdentifier threw. The check still passes.\n identifierError?: string;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n // Set when the piece or trigger uses a feature this engine does not run.\n unsupportedFeature?: string;\n // Set when the props failed validation, before piece code ran.\n invalidProps?: PropsValidationErrors;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n timings?: WorkerTimings;\n}\n\nexport interface ErrorResponse {\n id: number;\n type: \"error\";\n error: SerializedPieceError;\n tlsPoisoned: boolean;\n timings?: WorkerTimings;\n}\n\n// One part of serving a request, in epoch ms: piece.load, reactor.open,\n// models, action.\nexport interface WorkerPhaseTiming {\n name: string;\n start: number;\n end: number;\n // The phase this one ran inside, e.g. \"action\" for a model loaded mid-action.\n parent?: string;\n attributes?: Record<string, string | boolean>;\n}\n\n// Where a request's time went inside the child, in epoch ms.\nexport interface WorkerTimings {\n received: number;\n sent: number;\n phases: WorkerPhaseTiming[];\n // When the child's entry finished loading; on its first response only.\n ready?: number;\n // The child's process.memoryUsage() as it answered, in bytes.\n memory?: WorkerMemory;\n}\n\nexport interface WorkerMemory {\n rss: number;\n heapUsed: number;\n heapTotal: number;\n external: number;\n}\n\nexport type WorkerResponse = ResultResponse | ErrorResponse;\n\n// A request the child makes of its host while a step is running: the reverse\n// direction of everything above, and the only way a piece reaches durable state.\n\n// Ids are the child's own counter, a separate space from the host's, which is\n// why every handler dispatches on `type` before comparing an id.\nexport interface HostCallMessage {\n id: number;\n type: \"host-call\";\n method: string;\n payload: unknown;\n}\n\n// `error` carries the failure as data: a rejected promise cannot cross IPC,\n// so the reply always arrives and the child rethrows.\nexport interface HostCallResponse {\n id: number;\n type: \"host-result\";\n value?: unknown;\n error?: string;\n}\n\n// What the host will answer for the request in flight. Registered per request,\n// so a call arriving after the step returned finds nothing and is refused.\nexport type HostCallHandlers = Record<\n string,\n (payload: unknown) => Promise<unknown>\n>;\n\n// The one-way half of the channel: a report the host may act on, with no\n// answer to wait for. Their engine splits the same way (rpc vs rpc-notify).\n\n// A tap must never stall the step, so these carry no id and no reply. Node's\n// IPC preserves order, which is what drains them before the result lands.\nexport interface HostNotifyMessage {\n type: \"host-notify\";\n method: string;\n payload: unknown;\n}\n\n// Handlers registered per request, like HostCallHandlers. A throw here is\n// swallowed: a failed tap must not fail the step it was reporting on.\nexport type HostNotifyHandlers = Record<string, (payload: unknown) => void>;\n\n// One console call the piece made, already flattened to a string in the child.\nexport interface PieceLogEntry {\n level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n at: number;\n}\n\nexport const LOG_WRITE = \"log.write\";\nexport const OUTPUT_UPDATE = \"output.update\";\n\n// A store call carries `{ key, value?, scope }`. The scope is a name the host\n// partitions on, never a prefix the child bakes into the key.\nexport const STORE_GET = \"store.get\";\nexport const STORE_PUT = \"store.put\";\nexport const STORE_DELETE = \"store.delete\";\n","// The child's half of the call channel: how piece code reaches durable host\n// state mid-step, instead of handing everything back when the step returns.\n\n// Modelled on their engine RPC (createRpcClient): a method name, a payload, an\n// id, and failures returned as data rather than thrown across the boundary.\nimport { markIndeterminate } from \"../indeterminate.js\";\nimport { STORE_DELETE, STORE_PUT, type HostCallResponse } from \"./protocol.js\";\n\n// A host call is a local IPC round trip, so ten seconds is pathological in the\n// ordinary case. It was not in the field: a reactor dispatch under load, or a\n// store write behind a saturated PGlite, outran it and the step was reported\n// FAILED for a write that had in fact been committed (backlog item 6). The cap\n// is now the host's to set (PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS, and never\n// shorter than the step's own timeoutSeconds), and a mutating call that does\n// time out is INDETERMINATE rather than failed.\nexport const DEFAULT_HOST_CALL_TIMEOUT_MS = 10_000;\n\n/**\n * The host calls that may have committed something by the time they time out.\n *\n * A read that times out is just a read that did not answer. A write is not:\n * the host may have written and simply not got the answer back in time, so\n * reporting it as a failure is a claim nobody can stand behind. Reactor writes\n * go over the reactor RPC, not a host call; their unconfirmed outcome is\n * recognised by error name instead (`../indeterminate.ts`).\n */\nexport const MUTATING_HOST_CALLS: readonly string[] = [STORE_PUT, STORE_DELETE];\n\n// Set per request from the wire; requests are serialized per worker.\nlet fromWire: number | undefined;\n// The request's kill deadline, less a margin to report a timeout before it.\nlet stopAt: number | undefined;\n\nconst MIN_DEADLINE_MARGIN_MS = 250;\nconst MAX_DEADLINE_MARGIN_MS = 2_000;\n\nfunction deadlineMargin(budgetMs: number): number {\n return Math.min(\n Math.max(Math.floor(budgetMs / 10), MIN_DEADLINE_MARGIN_MS),\n MAX_DEADLINE_MARGIN_MS,\n );\n}\n\nexport function setHostCallTimeout(\n timeoutMs: number | undefined,\n deadline?: number,\n): void {\n fromWire = timeoutMs;\n stopAt =\n deadline === undefined\n ? undefined\n : deadline - deadlineMargin(deadline - Date.now());\n}\n\nexport function hostCallTimeoutMs(): number {\n return fromWire ?? DEFAULT_HOST_CALL_TIMEOUT_MS;\n}\n\ninterface Pending {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nconst pending = new Map<number, Pending>();\nlet nextId = 1;\nlet listening = false;\n\nexport class HostCallError extends Error {\n constructor(method: string, detail: string) {\n super(`Host call \"${method}\" failed: ${detail}`);\n this.name = \"HostCallError\";\n }\n}\n\n/** A read-ish host call that did not answer. An ordinary failure. */\nexport class HostCallTimeoutError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(`Host call \"${method}\" got no answer within ${timeoutMs}ms`);\n this.name = \"HostCallTimeoutError\";\n }\n}\n\n/**\n * A WRITING host call that did not answer: the write may have landed.\n *\n * Marked indeterminate (`../indeterminate.ts`), which is what survives the\n * worker boundary — this is thrown in the forked child, where the class does\n * not cross but the error's own enumerable properties do.\n */\nexport const INDETERMINATE_ERROR_NAME = \"HostCallIndeterminateError\";\n\nexport class HostCallIndeterminateError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(\n `Host call \"${method}\" got no answer within ${timeoutMs}ms; it writes, ` +\n \"so whether it was committed is unknown and the step is neither a \" +\n \"success nor a failure\",\n );\n this.name = INDETERMINATE_ERROR_NAME;\n markIndeterminate(this);\n }\n}\n\nfunction timeoutError(method: string, timeoutMs: number): Error {\n return MUTATING_HOST_CALLS.includes(method)\n ? new HostCallIndeterminateError(method, timeoutMs)\n : new HostCallTimeoutError(method, timeoutMs);\n}\n\nfunction isHostCallResponse(value: unknown): value is HostCallResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === \"host-result\"\n );\n}\n\n// Registered once, on the same channel the job messages arrive on. The job\n// dispatcher ignores `host-result` because it only knows its own request types.\nfunction ensureListening(): void {\n if (listening) return;\n listening = true;\n process.on(\"message\", (message: unknown) => {\n if (!isHostCallResponse(message)) return;\n const entry = pending.get(message.id);\n if (!entry) return;\n pending.delete(message.id);\n clearTimeout(entry.timer);\n if (message.error !== undefined) {\n entry.reject(new HostCallError(entry.method, message.error));\n return;\n }\n entry.resolve(message.value);\n });\n}\n\nexport function callHost<T = unknown>(\n method: string,\n payload: unknown,\n timeoutMs: number = hostCallTimeoutMs(),\n): Promise<T> {\n if (!process.send) {\n return Promise.reject(\n new HostCallError(method, \"the worker has no channel to its host\"),\n );\n }\n // Clipped to the step deadline: a call still waiting when the worker is\n // killed would surface as a retryable worker timeout, even for a write.\n const budgetMs =\n stopAt === undefined ? timeoutMs : Math.min(timeoutMs, stopAt - Date.now());\n if (budgetMs <= 0) {\n return Promise.reject(new HostCallTimeoutError(method, 0));\n }\n ensureListening();\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(timeoutError(method, budgetMs));\n }, budgetMs);\n pending.set(id, {\n method,\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n });\n process.send?.({ id, type: \"host-call\", method, payload });\n });\n}\n\n// Test seam: a worker replaced between suites must not inherit pending calls.\nexport function resetHostCalls(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n}\n\n// The one-way half: a report with no answer to wait for. It cannot fail from\n// the piece's side, so a missing channel is dropped rather than raised.\nexport function notifyHost(method: string, payload: unknown): void {\n try {\n process.send?.({ type: \"host-notify\", method, payload });\n } catch {\n // `process.send` stays defined after the channel closes and throws. A tap\n // that threw here would be a tap that changed the step.\n }\n}\n","// One file-size ceiling for both directions. Inbound hydration (a FILE prop\n// that arrives as a URL, a data URI or an attachment ref) and outbound\n// ctx.files.write share it, because a piece that can emit a file the next step\n// cannot ingest is worse than a piece that refuses both.\nimport { Transform, type TransformCallback } from \"node:stream\";\nimport { DEFAULT_HOST_CALL_TIMEOUT_MS } from \"../worker/host-call.js\";\n\nexport const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n// What the environment asks for, or undefined when it asks for nothing usable.\n// Read per call: a host may set it after this module is loaded.\nexport function configuredMaxFileBytes(): number | undefined {\n const raw = process.env.PH_WORKFLOWS_PIECE_MAX_FILE_BYTES;\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : undefined;\n}\n\n// The worker child is forked without an environment, so its limit arrives on\n// the wire instead. Requests are serialized per worker: one value at a time.\nlet fromWire: number | undefined;\n\nexport function setMaxFileBytes(limit: number | undefined): void {\n fromWire = limit;\n}\n\nexport function maxFileBytes(): number {\n return fromWire ?? configuredMaxFileBytes() ?? DEFAULT_MAX_FILE_BYTES;\n}\n\n/** How long a piece's call of its host may take before the step gives up on\n * it. Read per call, like the file ceiling, and travelling on the wire for the\n * same reason: the child is forked with no environment. */\nexport const HOST_CALL_TIMEOUT_ENV = \"PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS\";\n\n/**\n * The host-call cap for one step.\n *\n * The 10s default outran reality for a reactor dispatch under load and the\n * step was reported FAILED for a write that had been committed (backlog item\n * 6). So it is configurable, and it is never shorter than the step's OWN\n * timeout: a step the author gave two minutes should not have its host calls\n * cut off after ten seconds. The child still clips each call to end before\n * the step's kill deadline (`worker/host-call.ts`).\n */\nexport function hostCallTimeoutForStep(\n stepTimeoutMs: number | undefined,\n env: Record<string, string | undefined> = process.env,\n): number {\n const configured = Number(env[HOST_CALL_TIMEOUT_ENV]);\n const base =\n Number.isFinite(configured) && configured > 0\n ? Math.floor(configured)\n : DEFAULT_HOST_CALL_TIMEOUT_MS;\n return Math.max(base, stepTimeoutMs ?? 0);\n}\n\nexport class FileTooLargeError extends Error {\n readonly size: number;\n readonly limit: number;\n\n constructor(size: number, limit: number = maxFileBytes()) {\n super(\n `File of ${size} bytes exceeds the ${limit} byte limit ` +\n `(raise PH_WORKFLOWS_PIECE_MAX_FILE_BYTES to allow more)`,\n );\n this.name = \"FileTooLargeError\";\n this.size = size;\n this.limit = limit;\n }\n}\n\nexport function assertWithinLimit(size: number): void {\n const limit = maxFileBytes();\n if (size > limit) throw new FileTooLargeError(size, limit);\n}\n\n// Counts bytes as they pass and fails the stream past the cap, so an\n// undeclared or understated body never lands whole in memory or on disk.\nexport function byteCap(limit: number = maxFileBytes()): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk: Buffer, _encoding, done: TransformCallback) {\n seen += chunk.byteLength;\n if (seen > limit) done(new FileTooLargeError(seen, limit));\n else done(null, chunk);\n },\n });\n}\n","// Two FilesService implementations plus the staged-file contract that carries\n// bytes back to the host.\n//\n// `ctx.files.write()` is called *during* action.run(), inside the forked\n// worker, and the worker protocol has no worker-to-host request channel. So\n// this follows the pattern storeState already establishes — push in, return\n// whole — using the one thing a fork shares with its parent: the filesystem.\n// The worker writes bytes to a staging directory and returns a provisional\n// `apfile://<token>`; the host ingests each staged file after the step returns\n// and rewrites the tokens in the output before journalling it.\nimport { randomUUID } from \"node:crypto\";\nimport { createWriteStream } from \"node:fs\";\nimport { mkdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n assertWithinLimit,\n byteCap,\n FileTooLargeError,\n maxFileBytes,\n} from \"./limits.js\";\n\nexport { FileTooLargeError, maxFileBytes };\n\nexport const APFILE_SCHEME = \"apfile://\";\n\n// One file the piece wrote, as it crosses back on ResultResponse.files.\nexport interface StagedFile {\n // The provisional ref handed to the piece; the host rewrites it in place.\n token: string;\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n}\n\n// What a piece may hand ctx.files.write: upstream takes a Buffer or a Readable.\nexport type ApFileData = Buffer | Uint8Array | Readable;\n\n// The framework's FilesService for both actions and triggers, with fileName\n// optional.\nexport interface ApFilesService {\n write(file: { fileName?: string; data: ApFileData }): Promise<string>;\n}\n\n// A Readable drained into memory under the cap, for the inline fallback.\nasync function drain(data: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of data.pipe(byteCap())) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks);\n}\n\n// Default for both actions and triggers when the host injects nothing: inline\n// the bytes as a data URI so the payload stays self-contained. Bounded by the\n// shared cap, since a data URI lands in the run journal.\nexport class DataUriFilesService implements ApFilesService {\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const data =\n file.data instanceof Readable\n ? await drain(file.data)\n : Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n if (data.byteLength > maxFileBytes()) {\n throw new FileTooLargeError(data.byteLength);\n }\n return `data:application/octet-stream;base64,${data.toString(\"base64\")}`;\n }\n}\n\nconst EXTENSION_TYPES: Record<string, string> = {\n pdf: \"application/pdf\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n tif: \"image/tiff\",\n tiff: \"image/tiff\",\n txt: \"text/plain\",\n json: \"application/json\",\n csv: \"text/csv\",\n};\n\nfunction contentTypeFor(fileName: string): string | undefined {\n const extension = fileName.split(\".\").pop()?.toLowerCase();\n return extension ? EXTENSION_TYPES[extension] : undefined;\n}\n\n// Worker-side service: writes into `<stagingDir>/<uuid>` and remembers what it\n// wrote so the worker can report it on the response.\nexport class StagedFilesService implements ApFilesService {\n private readonly files: StagedFile[] = [];\n\n constructor(private readonly stagingDir: string) {}\n\n staged(): StagedFile[] {\n return [...this.files];\n }\n\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const token = randomUUID();\n const fileName =\n file.fileName && file.fileName !== \"\" ? file.fileName : token;\n const target = path.join(this.stagingDir, token);\n let size: number;\n if (file.data instanceof Readable) {\n // Capped while it streams to disk: a piece cannot fill the disk with a\n // file the host would refuse anyway.\n await mkdir(this.stagingDir, { recursive: true });\n try {\n await pipeline(file.data, byteCap(), createWriteStream(target));\n } catch (error) {\n await rm(target, { force: true });\n throw error;\n }\n size = (await stat(target)).size;\n } else {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n // Checked before anything touches the disk, for the same reason.\n assertWithinLimit(data.byteLength);\n await mkdir(this.stagingDir, { recursive: true });\n await writeFile(target, data);\n size = data.byteLength;\n }\n this.files.push({\n token: `${APFILE_SCHEME}${token}`,\n path: target,\n fileName,\n size,\n contentType: contentTypeFor(fileName),\n });\n return `${APFILE_SCHEME}${token}`;\n }\n}\n\n// Replaces every provisional token in a step output with the real ref the host\n// got back from its attachment store. Walks the whole value: a piece may nest\n// the ref anywhere, and a plain string replace over the serialized JSON would\n// corrupt any base64 that happens to contain the token.\nexport function rewriteFileRefs(\n value: unknown,\n refs: Map<string, string>,\n): unknown {\n if (refs.size === 0) return value;\n if (typeof value === \"string\") return refs.get(value) ?? value;\n if (Array.isArray(value)) {\n return value.map((entry) => rewriteFileRefs(entry, refs));\n }\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = rewriteFileRefs(entry, refs);\n }\n return out;\n }\n return value;\n}\n","// Our TriggerHookContext → theirs (doc 06 §2.8): one builder covering the\n// strategy variants; identity/payload as data, capabilities injected or stubbed.\nimport { Cron } from \"croner\";\nimport { DEDUPE_KEY_PROPERTY, type ApTrigger } from \"../types.js\";\nimport {\n InMemoryKeyValueStore,\n type ActionContextIdentity,\n type KeyValueStore,\n} from \"./action.js\";\nimport type { ConnectionsProvider, FlowsProvider } from \"./props.js\";\nimport type { ReactorOption } from \"./reactor-option.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport type TriggerContextOptions = TriggerContextBaseOptions & ReactorOption;\n\ninterface TriggerContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\n\n// The affixed form is anchored on the literal \"signature\", with the prefix\n// matched by a lookbehind placed after it. A leading prefix pattern\n// ((?:[a-z0-9]+[-_])*signature) retries from every segment of a long\n// hyphen-separated run that never ends in \"signature\", which is quadratic:\n// whole seconds over a few hundred kilobytes of journaled text. The\n// lookbehind runs once per occurrence of the literal instead, and captures\n// the prefix so the marker still names the whole header.\nconst TEXT_FIELD = new RegExp(\n String.raw`(\\b(?:authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token)|signature(?<=\\b((?:[a-z0-9]+[-_])*)signature)(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\5`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\n\n// Anchored on \"://\" with the scheme checked by the lookbehind behind it: a\n// leading scheme pattern ([a-z][a-z0-9+.-]*) rescans a long unbroken\n// alphanumeric run from every offset, which is quadratic — tens of seconds\n// over a 256 KiB run. The scheme is not consumed, and not rewritten either\n// way; only the password half is replaced.\nconst URL_USERINFO =\n /:\\/\\/(?<=[a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, user: string) => `://${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n\n // signaturePrefix is the lookbehind's capture: the affixes before\n // \"signature\" sit outside the match, so they are stitched back onto the\n // name only for the marker — the text keeps them where they were.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n signaturePrefix: string | undefined,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(`${signaturePrefix ?? \"\"}${name}`)}${quote}`,\n );\n}\n\n// A document header's or reference's operation counts per scope. Scope names\n// such as \"auth\" are not credentials, and the counts are numbers.\nfunction isScopeRevision(\n parent: Record<string, unknown>,\n key: string,\n entry: unknown,\n): boolean {\n return (\n key === \"revision\" &&\n typeof parent.documentType === \"string\" &&\n typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n Object.values(entry).every(\n (count) => typeof count === \"number\" && Number.isFinite(count),\n )\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n const record = value as Record<string, unknown>;\n for (const [key, entry] of Object.entries(record)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : isScopeRevision(record, key, entry)\n ? { ...(entry as Record<string, number>) }\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\n\n// TRUNCATED_MARKER is matched whole, not as a substring: walk() only ever\n// writes it in place of an entire capped node, so prose that merely mentions\n// the word keeps replaying.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") {\n return value.includes(REDACTED_PREFIX) || value === TRUNCATED_MARKER;\n }\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n","// The reactor RPC on a piece child's IPC channel, bound to one request. It owns\n// only `reactor-rpc` envelopes carrying that request's id.\nimport {\n REACTOR_RPC,\n type ReactorRpcEnvelope,\n type ReactorRequestBinding,\n} from \"./protocol.js\";\nimport type { IPieceWorkerTransport } from \"./transport.js\";\n\n// Structurally `IRpcTransport` from `@powerhousedao/reactor/rpc`.\nexport interface ReactorRpcTransport {\n post(message: never): void;\n onMessage(listener: (message: never) => void): () => void;\n close(): void;\n}\n\n// Serves ctx.reactor for one request; `open` returns the stop run when it settles.\nexport interface ReactorTap {\n requireReactor: ReactorRequestBinding[\"requireReactor\"];\n open(\n transport: ReactorRpcTransport,\n request: { requestId: string; deadline: number },\n ): () => void;\n}\n\nexport function isReactorRpcEnvelope(\n value: unknown,\n requestId: string,\n): value is ReactorRpcEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n const envelope = value as Partial<ReactorRpcEnvelope>;\n return envelope.type === REACTOR_RPC && envelope.requestId === requestId;\n}\n\nfunction isRpcMessage(value: unknown): boolean {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { k?: unknown }).k === \"string\"\n );\n}\n\n// The host's end. The child runs piece code: another request's id, or a\n// message without a kind, is dropped.\nexport function createIpcTransport(\n worker: IPieceWorkerTransport,\n requestId: string,\n): ReactorRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: unknown) {\n if (closed || !worker.connected) return;\n worker.send({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener: (message: never) => void) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n if (!isRpcMessage(value.message)) return;\n listener(value.message as never);\n };\n worker.on(\"message\", handler);\n const detach = () => {\n worker.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n","// What PieceWorker needs from a connection to a worker, and nothing else.\n\n// Written against this rather than a ChildProcess so a later transport — a\n// pooled fork, a socket to another machine — slots in underneath unchanged.\nimport { fork, type ChildProcess } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n lstatSync,\n mkdirSync,\n} from \"node:fs\";\nimport { tmpdir, userInfo } from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport interface TransportExit {\n code: number | null;\n signal: NodeJS.Signals | null;\n}\n\nexport type TransportEventMap = {\n message: unknown;\n exit: TransportExit;\n};\n\nexport type TransportEvent = keyof TransportEventMap;\n\nexport type TransportListener<E extends TransportEvent> = (\n payload: TransportEventMap[E],\n) => void;\n\n// One worker's connection. An implementation must deliver `message` payloads\n// faithfully enough for the protocol above, and emit `exit` exactly once.\n\n// \"Faithfully enough\" means JSON-shaped, deliberately: the fork's structured\n// clone would carry a Date or a Map, but nothing may depend on that, because\n// no other carrier could honour it.\n\n// PieceWorker flattens what it sends and the child flattens what it answers,\n// so this is a contract a socket could meet too — a transport is not required\n// to preserve anything JSON would lose.\nexport interface IPieceWorkerTransport {\n send(message: unknown): void;\n on<E extends TransportEvent>(event: E, listener: TransportListener<E>): void;\n off<E extends TransportEvent>(event: E, listener: TransportListener<E>): void;\n // Ends the worker now; it takes any pending host calls with it.\n kill(): void;\n // False once the worker cannot receive: a send after this is dropped.\n readonly connected: boolean;\n}\n\n// Builds a fresh connection. Called on first use and again after a worker is\n// killed, so a factory must be able to produce more than one.\nexport type PieceWorkerTransportFactory = () => IPieceWorkerTransport;\n\nexport function defaultEntryPath(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n while (!existsSync(path.join(dir, \"package.json\"))) {\n const parent = path.dirname(dir);\n if (parent === dir) throw new Error(\"Could not locate package root\");\n dir = parent;\n }\n const entry = path.join(dir, \"dist\", \"worker-entry.js\");\n if (!existsSync(entry)) {\n throw new Error(`Worker entry not built at ${entry} — run pnpm build`);\n }\n return entry;\n}\n\n// How long a profiling child gets to write its profile before SIGKILL.\nconst PROFILE_EXIT_MS = 2_000;\n\n// Each child writes a V8 CPU profile here; for benchmarks.\nfunction workerProfileDir(): string | undefined {\n return process.env.PH_WORKFLOWS_WORKER_CPU_PROF_DIR || undefined;\n}\n\nlet compileCache: string | null | undefined;\n\n// A planted cache is code the child runs, so the directory must be ours alone:\n// mkdirSync leaves an existing one, whoever owns it, as it found it.\nexport function privateDirectory(dir: string): boolean {\n const stat = lstatSync(dir);\n if (!stat.isDirectory()) return false;\n // No uids on Windows; there the directory sits in the user's own temp.\n if (typeof process.getuid !== \"function\") return true;\n return stat.uid === process.getuid() && (stat.mode & 0o077) === 0;\n}\n\n// Children run piece code as our uid and can write the cache, so by default it\n// is used only where they could already rewrite the entry it caches.\nexport function writable(file: string): boolean {\n try {\n accessSync(file, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n// V8 code cache every child shares, so a fork skips compiling what an earlier\n// one did. PH_WORKFLOWS_WORKER_COMPILE_CACHE names the directory; \"off\" disables.\nfunction workerCompileCache(entryPath: string): string | undefined {\n if (compileCache === undefined) {\n const configured = process.env.PH_WORKFLOWS_WORKER_COMPILE_CACHE;\n try {\n if (configured === \"off\") throw new Error(\"disabled\");\n if (!configured && !writable(entryPath)) throw new Error(\"read-only\");\n // userInfo throws in a container whose uid has no passwd entry.\n const base = configured\n ? undefined\n : path.join(tmpdir(), `ph-workflows-${userInfo().uid}`);\n const dir = configured || path.join(base!, \"compile-cache\");\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n // In a shared tmp the parent counts too: its owner could swap the cache out.\n const owned = privateDirectory(dir) && (!base || privateDirectory(base));\n compileCache = owned ? dir : null;\n } catch {\n // Unwritable or disabled: children compile from source.\n compileCache = null;\n }\n }\n return compileCache ?? undefined;\n}\n\n// A forked node child on this machine, over its IPC channel.\nexport interface ForkTransportOptions {\n // `--max-old-space-size` for the child.\n heapMb?: number;\n}\n\nexport function createForkTransport(\n entryPath: string,\n options: ForkTransportOptions = {},\n): IPieceWorkerTransport {\n const profileDir = workerProfileDir();\n const cacheDir = workerCompileCache(entryPath);\n const execArgv = profileDir\n ? [\"--cpu-prof\", `--cpu-prof-dir=${profileDir}`]\n : [];\n if (options.heapMb) {\n execArgv.push(`--max-old-space-size=${Math.trunc(options.heapMb)}`);\n }\n const child: ChildProcess = fork(entryPath, [], {\n // No host env: the child gets no secrets and no inherited TLS overrides.\n env: cacheDir ? { NODE_COMPILE_CACHE: cacheDir } : {},\n execArgv,\n // Structured clone rather than JSON, so a Buffer in a payload survives.\n serialization: \"advanced\",\n // Piece stdout/stderr are dropped for now; log capture arrives with journaling.\n stdio: [\"ignore\", \"ignore\", \"ignore\", \"ipc\"],\n });\n\n // Node reports exit as two positional arguments; the interface carries one\n // payload, so the adaptation lives here rather than in every listener.\n const exitListeners = new Map<\n TransportListener<\"exit\">,\n (code: number | null, signal: NodeJS.Signals | null) => void\n >();\n\n return {\n get connected() {\n return child.connected;\n },\n send(message) {\n child.send(message as never);\n },\n on(event, listener) {\n if (event === \"exit\") {\n const adapted = (code: number | null, signal: NodeJS.Signals | null) =>\n (listener as TransportListener<\"exit\">)({ code, signal });\n exitListeners.set(listener as TransportListener<\"exit\">, adapted);\n child.on(\"exit\", adapted);\n return;\n }\n child.on(\"message\", listener as (value: unknown) => void);\n },\n off(event, listener) {\n if (event === \"exit\") {\n const adapted = exitListeners.get(\n listener as TransportListener<\"exit\">,\n );\n if (adapted) {\n child.off(\"exit\", adapted);\n exitListeners.delete(listener as TransportListener<\"exit\">);\n }\n return;\n }\n child.off(\"message\", listener as (value: unknown) => void);\n },\n kill() {\n if (!profileDir) {\n child.kill(\"SIGKILL\");\n return;\n }\n // SIGTERM lets it write its CPU profile; a blocked loop never handles it.\n child.kill(\"SIGTERM\");\n const force = setTimeout(() => child.kill(\"SIGKILL\"), PROFILE_EXIT_MS);\n force.unref();\n child.once(\"exit\", () => clearTimeout(force));\n },\n };\n}\n","// Wall-clock marks a child takes while serving one request, sent back with its\n// response so the host can draw them as spans. The child carries no tracer.\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { WorkerPhaseTiming, WorkerTimings } from \"./protocol.js\";\n\nconst ANCHOR_MS = 1_000;\n// Date.now() rounds to the ms: a smaller drift is that, not a clock step, and\n// following it would step time backwards.\nconst STEP_MS = 5;\n\n// Epoch ms, sub-ms precise, comparable across processes. Re-anchored each second:\n// timeOrigin is fixed at start, so a clock step would skew host against child.\nexport function wallClock(): () => number {\n let anchoredAt = performance.now();\n let anchor = Date.now() - anchoredAt;\n return () => {\n const now = performance.now();\n if (now - anchoredAt >= ANCHOR_MS) {\n anchoredAt = now;\n const next = Date.now() - now;\n if (Math.abs(next - anchor) > STEP_MS) anchor = next;\n }\n return anchor + now;\n };\n}\n\nexport const epochNow = wallClock();\n\nlet readyAt: number | undefined;\nlet bootReported = false;\n\n// When the entry finished loading; reported once, with the first response.\nexport function markWorkerReady(): void {\n readyAt ??= epochNow();\n}\n\nexport interface RequestTimings {\n received: number;\n phases: WorkerPhaseTiming[];\n}\n\nconst current = new AsyncLocalStorage<RequestTimings>();\n// The phase `fn` runs inside, so a nested one (models in action) names its parent.\nconst currentPhase = new AsyncLocalStorage<string>();\n\nexport function startRequestTimings(): RequestTimings {\n return { received: epochNow(), phases: [] };\n}\n\nexport function withRequestTimings<T>(\n timings: RequestTimings,\n fn: () => Promise<T>,\n): Promise<T> {\n return current.run(timings, fn);\n}\n\n// Records `fn` as a phase of the request being served, if any.\nexport async function timed<T>(\n name: string,\n fn: () => Promise<T>,\n attributes?: Record<string, string | boolean>,\n): Promise<T> {\n const timings = current.getStore();\n if (!timings) return fn();\n const parent = currentPhase.getStore();\n const start = epochNow();\n try {\n return await currentPhase.run(name, fn);\n } finally {\n timings.phases.push({\n name,\n start,\n end: epochNow(),\n ...(parent ? { parent } : {}),\n ...(attributes ? { attributes } : {}),\n });\n }\n}\n\nexport function finishRequestTimings(timings: RequestTimings): WorkerTimings {\n const boot = !bootReported && readyAt !== undefined;\n bootReported = true;\n const { rss, heapUsed, heapTotal, external } = process.memoryUsage();\n return {\n received: timings.received,\n sent: epochNow(),\n phases: timings.phases,\n memory: { rss, heapUsed, heapTotal, external },\n ...(boot ? { ready: readyAt } : {}),\n };\n}\n","import {\n configuredMaxFileBytes,\n hostCallTimeoutForStep,\n} from \"../context/limits.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\nimport { jsonSafe } from \"./json-safe.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { createIpcTransport, type ReactorTap } from \"./reactor-rpc.js\";\nimport type { WorkflowTelemetry } from \"../../../telemetry.js\";\nimport {\n createForkTransport,\n defaultEntryPath,\n type IPieceWorkerTransport,\n type PieceWorkerTransportFactory,\n type TransportExit,\n} from \"./transport.js\";\nimport {\n MODEL_ENTRIES,\n MODEL_MANIFEST,\n type CheckConnectionRequest,\n type DescribePieceRequest,\n type HostCallHandlers,\n type HostCallMessage,\n type HostCallResponse,\n type HostNotifyHandlers,\n type HostNotifyMessage,\n type ModelEntriesPayload,\n type ModelManifestMessage,\n type ReactorRequestBinding,\n type ReactorRpcEnvelope,\n type ResolveOptionsRequest,\n type RunActionRequest,\n type SerializedPieceError,\n type TriggerHookRequest,\n type WorkerMemory,\n type WorkerResponse,\n type WorkerTimings,\n} from \"./protocol.js\";\nimport { epochNow } from \"./timings.js\";\n\ntype WorkerRequestType =\n | \"run\"\n | \"resolve-options\"\n | \"trigger-hook\"\n | \"check-connection\"\n | \"describe\";\n\ntype WorkerRequest =\n | RunActionRequest\n | ResolveOptionsRequest\n | TriggerHookRequest\n | CheckConnectionRequest\n | DescribePieceRequest;\n\nexport class PieceWorkerError extends Error {\n readonly serialized: SerializedPieceError;\n\n constructor(serialized: SerializedPieceError) {\n super(`${serialized.name}: ${serialized.message}`);\n this.name = \"PieceWorkerError\";\n this.serialized = serialized;\n }\n}\n\nexport class PieceWorkerTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Piece action timed out after ${timeoutMs}ms; worker was replaced`);\n this.name = \"PieceWorkerTimeoutError\";\n }\n}\n\nexport class PieceWorkerExitError extends Error {\n constructor(code: number | null, signal: string | null) {\n super(`Piece worker exited unexpectedly (code=${code}, signal=${signal})`);\n this.name = \"PieceWorkerExitError\";\n }\n}\n\nexport class PieceWorkerDisposedError extends Error {\n constructor() {\n super(\"This piece worker is disposed\");\n this.name = \"PieceWorkerDisposedError\";\n }\n}\n\nexport interface PieceWorkerResult {\n output: unknown;\n touched: string[];\n tlsPoisoned: boolean;\n // run only: files the piece wrote through ctx.files, staged on disk for the\n // host to ingest before the output is journalled.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n}\n\n// Handlers the host offers for the duration of one request: calls it answers,\n// and one-way reports it receives.\nexport interface RequestTaps {\n hostCalls?: HostCallHandlers;\n notifications?: HostNotifyHandlers;\n // ctx.reactor over the reactor RPC; ignored by check-connection and describe.\n reactor?: ReactorTap;\n}\n\n// Every request that can serve a piece takes the same shape: a deadline plus\n// the taps the host offers while it runs.\nexport interface RequestOptions extends RequestTaps {\n timeoutMs?: number;\n // Cap on each call the child makes of its host, for THIS request. Per\n // request rather than per worker because it follows the step's own timeout\n // (`hostCallTimeoutForStep`), and one worker serves many steps.\n hostCallTimeoutMs?: number;\n}\n\n/** @deprecated Named for the one request that had it; every request takes it\n * now. Kept because the old name is on main, in this package's public types. */\nexport type RunActionOptions = RequestOptions;\n\n// The child's marks, plus when the host sent the request and got the reply.\nexport type OnWorkerTimings = (\n timings: WorkerTimings,\n ipc: { sent: number; received: number },\n) => void;\n\ntype ChildMessage =\n | WorkerResponse\n | HostCallMessage\n | HostNotifyMessage\n | ReactorRpcEnvelope;\n\ninterface OpenReactor {\n binding: ReactorRequestBinding;\n stop: () => void;\n}\n\n// Importable document models for the child (the reactor's ModelManifestEntry).\nexport interface ModelManifestSource {\n // Sent on fork.\n entries(): unknown[];\n // The child's lookup on a miss; without a type, every entry the host knows.\n lookup?(documentType?: string): unknown[] | Promise<unknown[]>;\n}\n\n// A tap reports on the step; it never decides its outcome. Node delivers these\n// before the result, so no draining step is needed at teardown.\nfunction serveNotify(\n message: HostNotifyMessage,\n handlers: HostNotifyHandlers | undefined,\n): void {\n const handler = handlers?.[message.method];\n if (!handler) return;\n try {\n // Declared void, but TypeScript admits an async function here, and its\n // rejection would take the host down rather than the tap.\n void Promise.resolve(handler(message.payload)).catch(() => undefined);\n } catch {\n // A broken tap is not the step's problem.\n }\n}\n\nexport interface PieceWorkerOptions {\n // Absolute path to the compiled worker entry; defaults to dist/worker-entry.js.\n entryPath?: string;\n telemetry?: WorkflowTelemetry;\n defaultTimeoutMs?: number;\n // How to reach a worker. Defaults to a forked child on this machine; a\n // remote transport replaces it without touching the protocol above.\n transport?: PieceWorkerTransportFactory;\n // Cap on each call the child makes of its host; the child's default if unset.\n hostCallTimeoutMs?: number;\n // Sent to each child on fork, and looked up by type on a miss.\n models?: ModelManifestSource;\n // The child's V8 heap limit (`--max-old-space-size`); Node's default if unset.\n heapMb?: number;\n}\n\n// What a pool needs to decide whether a child can serve another request.\nexport interface PieceWorkerHealth {\n // A child is running; false before the first request and after it exits.\n alive: boolean;\n // From the child's last reply; absent until it has replied once.\n memory?: WorkerMemory;\n // A request switched TLS verification off, which the child may have cached.\n tlsPoisoned: boolean;\n}\n\n// The five requests a worker serves, plus teardown. Callers hold this rather\n// than PieceWorker itself, so a child that outlives every request and a child\n// that lives for one run are interchangeable to them.\nexport interface IPieceWorker {\n runAction(\n request: RunActionRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult>;\n resolveOptions(\n request: ResolveOptionsRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult>;\n checkConnection(\n request: CheckConnectionRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult>;\n describePiece(\n request: DescribePieceRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult>;\n runTriggerHook(\n request: TriggerHookRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult>;\n // Ends the worker. A caller that was handed one it does not own must not\n // call this; PieceWorkerPool disposes the workers it hands out.\n dispose(): void;\n // Absent on a worker a pool can't inspect; the pool then trusts it.\n health?(): PieceWorkerHealth;\n}\n\n// Executes piece actions in a child process. Side-effects (TLS env poisoning,\n// crashes) stay in the child; a timed-out or crashed worker is replaced.\nexport class PieceWorker implements IPieceWorker {\n private readonly connect: PieceWorkerTransportFactory;\n private readonly defaultTimeoutMs: number;\n private readonly hostCallTimeoutMs: number | undefined;\n private readonly models: ModelManifestSource | undefined;\n private readonly telemetry: WorkflowTelemetry | undefined;\n private worker: IPieceWorkerTransport | undefined;\n // When the current child was forked, in epoch ms.\n private forkedAt = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private nextId = 1;\n private disposed = false;\n private memory: WorkerMemory | undefined;\n private tlsPoisoned = false;\n\n constructor(options: PieceWorkerOptions = {}) {\n const entryPath = options.entryPath;\n const { heapMb } = options;\n this.connect =\n options.transport ??\n (() => createForkTransport(entryPath ?? defaultEntryPath(), { heapMb }));\n this.defaultTimeoutMs = options.defaultTimeoutMs ?? 30_000;\n this.hostCallTimeoutMs = options.hostCallTimeoutMs;\n this.models = options.models;\n this.telemetry = options.telemetry;\n }\n\n // Requests are serialized per worker; concurrency comes from holding more\n // than one, which is what PieceWorkerPool does.\n runAction(\n request: RunActionRequest,\n options: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"run\", request, options.timeoutMs, options);\n }\n\n // Design-time DROPDOWN options() / DYNAMIC props() resolution. It takes the\n // same taps a run does: a package piece's resolver may read the reactor.\n resolveOptions(\n request: ResolveOptionsRequest,\n options: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"resolve-options\", request, options.timeoutMs, options);\n }\n\n // The piece's auth.validate and auth.getConnectionIdentifier over resolved\n // credentials; the output is a CheckConnectionOutcome.\n checkConnection(\n request: CheckConnectionRequest,\n options: { timeoutMs?: number } = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"check-connection\", request, options.timeoutMs);\n }\n\n // The piece's design-time descriptor; the output is a PieceDescriptor.\n describePiece(\n request: DescribePieceRequest,\n options: { timeoutMs?: number } = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"describe\", request, options.timeoutMs);\n }\n\n // One trigger lifecycle hook. It takes the same taps a run does, so a\n // `durableStore` hook reaches the host's store while it is still running.\n runTriggerHook(\n request: TriggerHookRequest,\n options: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"trigger-hook\", request, options.timeoutMs, options);\n }\n\n private enqueue(\n type: WorkerRequestType,\n request: WorkerRequest,\n timeoutMs?: number,\n taps: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n const run = this.queue.then(() => {\n const execute = (onTimings?: OnWorkerTimings) =>\n this.execute(\n type,\n request,\n timeoutMs ?? this.defaultTimeoutMs,\n taps,\n onTimings,\n );\n const telemetry = this.telemetry;\n if (!telemetry) return execute();\n // Named apart, not just attributed: the phase metric keys on the name,\n // and a cold request pays for the fork and the child's module loading.\n const cold = !this.worker;\n return telemetry.phase(\n `worker.${type}${cold ? \".cold\" : \"\"}`,\n { \"worker.cold\": cold },\n (span) =>\n execute((timings, ipc) =>\n telemetry.workerTimings(span, timings, this.forkedAt, ipc),\n ),\n );\n });\n this.queue = run.catch(() => undefined);\n return run;\n }\n\n // For good: a request still queued, or made later, forks nothing.\n dispose(): void {\n this.disposed = true;\n this.worker?.kill();\n this.worker = undefined;\n }\n\n health(): PieceWorkerHealth {\n return {\n alive: this.worker !== undefined,\n ...(this.memory ? { memory: this.memory } : {}),\n tlsPoisoned: this.tlsPoisoned,\n };\n }\n\n // A fresh child starts clean, so what the last one reported no longer holds.\n private forgetChild(): void {\n this.memory = undefined;\n this.tlsPoisoned = false;\n }\n\n // Read from piece-controlled output, so only well-formed numbers count.\n private noteReply(response: ChildMessage): void {\n if (\"tlsPoisoned\" in response && response.tlsPoisoned === true) {\n this.tlsPoisoned = true;\n }\n const memory = (response as { timings?: WorkerTimings }).timings?.memory;\n if (\n memory &&\n [memory.rss, memory.heapUsed, memory.heapTotal, memory.external].every(\n (value) => Number.isFinite(value),\n )\n ) {\n this.memory = memory;\n }\n }\n\n private spawn(): IPieceWorkerTransport {\n if (this.worker) return this.worker;\n this.forgetChild();\n this.forkedAt = epochNow();\n const worker = this.connect();\n this.sendModels(worker);\n const forget = () => {\n if (this.worker === worker) this.worker = undefined;\n worker.off(\"exit\", forget);\n };\n worker.on(\"exit\", forget);\n this.worker = worker;\n return worker;\n }\n\n private sendModels(worker: IPieceWorkerTransport): void {\n const entries = this.models?.entries() ?? [];\n if (entries.length === 0 || !worker.connected) return;\n const message: ModelManifestMessage = { type: MODEL_MANIFEST, entries };\n worker.send(jsonSafe(message));\n }\n\n private async modelEntries(payload: unknown): Promise<unknown[]> {\n const documentType = (payload as ModelEntriesPayload | undefined)\n ?.documentType;\n return (await this.models?.lookup?.(documentType)) ?? [];\n }\n\n // Starts serving ctx.reactor for one request; the returned stop closes it.\n private openReactor(\n worker: IPieceWorkerTransport,\n tap: ReactorTap,\n deadline: number,\n ): OpenReactor {\n const requestId = randomUUID();\n const transport = createIpcTransport(worker, requestId);\n let stopServing: () => void;\n try {\n stopServing = tap.open(transport, { requestId, deadline });\n } catch (error) {\n transport.close();\n throw error;\n }\n return {\n binding: { requestId, requireReactor: tap.requireReactor },\n stop: () => {\n transport.close();\n stopServing();\n },\n };\n }\n\n private execute(\n type: WorkerRequestType,\n request: WorkerRequest,\n timeoutMs: number,\n taps: RequestOptions,\n onTimings?: OnWorkerTimings,\n ): Promise<PieceWorkerResult> {\n if (this.disposed) return Promise.reject(new PieceWorkerDisposedError());\n const worker = this.spawn();\n const id = this.nextId++;\n // An explicit per-worker cap is the host's own decision and wins. With\n // none — which is how the pool builds them — each request carries the cap\n // derived from its step (`hostCallTimeoutForStep`), because one worker\n // serves many steps and the cap follows the step's own timeout.\n // A request with no cap of its own (a trigger hook, a design-time call)\n // takes the operator's, raised to its own timeout, as a step does.\n const hostCallTimeoutMs =\n this.hostCallTimeoutMs ??\n taps.hostCallTimeoutMs ??\n hostCallTimeoutForStep(timeoutMs);\n\n // When the request was handed to IPC, for the ipc.in span.\n let sentAt = 0;\n return new Promise<PieceWorkerResult>((resolve, reject) => {\n // The kill timer's own reading, so the child can give up in time to say why.\n const deadline = Date.now() + timeoutMs;\n let reactor: OpenReactor | undefined;\n if (taps.reactor && type !== \"check-connection\" && type !== \"describe\") {\n try {\n reactor = this.openReactor(worker, taps.reactor, deadline);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n }\n const timer = setTimeout(() => {\n cleanup();\n worker.kill();\n this.worker = undefined;\n reject(new PieceWorkerTimeoutError(timeoutMs));\n }, timeoutMs);\n\n const onMessage = (value: unknown) => {\n const response = value as ChildMessage;\n // Ids come from two counters; dispatch on type before comparing them.\n if (\n response.type === \"host-call\" ||\n response.type === \"host-notify\" ||\n response.type === \"reactor-rpc\"\n ) {\n return;\n }\n if (response.id !== id) return;\n cleanup();\n const received = epochNow();\n this.noteReply(response);\n if (response.type === \"result\") {\n resolve({\n output: response.output,\n touched: response.touched,\n tlsPoisoned: response.tlsPoisoned,\n files: response.files,\n storeState: response.storeState,\n schedules: response.schedules,\n listeners: response.listeners,\n });\n } else {\n reject(new PieceWorkerError(response.error));\n }\n // After settling: the child is piece code and its timings may be junk.\n if (response.timings && onTimings) {\n try {\n onTimings(response.timings, { sent: sentAt, received });\n } catch {\n // Tracing must never fail the request it describes.\n }\n }\n };\n\n const onExit = ({ code, signal }: TransportExit) => {\n cleanup();\n reject(new PieceWorkerExitError(code, signal));\n };\n\n // Served outside the request queue: the queue is held by this very\n // request, so routing a call through it would deadlock the step.\n const onHostCall = (value: unknown) => {\n const message = value as ChildMessage;\n if (message.type === \"host-call\") {\n void this.serveHostCall(worker, message, taps.hostCalls);\n return;\n }\n if (message.type === \"host-notify\") {\n serveNotify(message, taps.notifications);\n }\n };\n\n const cleanup = () => {\n reactor?.stop();\n reactor = undefined;\n clearTimeout(timer);\n worker.off(\"message\", onMessage);\n worker.off(\"message\", onHostCall);\n worker.off(\"exit\", onExit);\n };\n\n worker.on(\"message\", onMessage);\n worker.on(\"message\", onHostCall);\n worker.on(\"exit\", onExit);\n // Flattened here rather than per caller: config, auth and connection\n // values are piece-authored, and the contract is JSON-shaped both ways.\n // The file ceiling is stamped on the same way the egress policy is passed\n // in: the child reads no environment of its own.\n sentAt = epochNow();\n worker.send(\n jsonSafe({\n id,\n type,\n request: {\n maxFileBytes: configuredMaxFileBytes(),\n deadline,\n ...(hostCallTimeoutMs ? { hostCallTimeoutMs } : {}),\n ...request,\n ...(reactor ? { reactor: reactor.binding } : {}),\n },\n }),\n );\n });\n }\n\n // Answers one call from the child. The handler set belongs to the request in\n // flight, so a call arriving after the step returned is refused, not served.\n private async serveHostCall(\n worker: IPieceWorkerTransport,\n message: HostCallMessage,\n handlers: HostCallHandlers | undefined,\n ): Promise<void> {\n let response: HostCallResponse;\n try {\n const handler =\n message.method === MODEL_ENTRIES\n ? (payload: unknown) => this.modelEntries(payload)\n : handlers?.[message.method];\n if (!handler) {\n throw new Error(`No host handler for \"${message.method}\"`);\n }\n response = {\n id: message.id,\n type: \"host-result\",\n value: await handler(message.payload),\n };\n } catch (error) {\n response = {\n id: message.id,\n type: \"host-result\",\n error: error instanceof Error ? error.message : String(error),\n };\n }\n // A worker killed on timeout takes its pending calls with it.\n if (worker.connected) worker.send(response);\n }\n}\n","// One warm pool of piece children, leased per request (ADR 0007).\n\n// A request takes an idle child that has its piece loaded, then any idle\n// child, then a new child, then a place in a FIFO queue.\n\n// Trigger hooks get children of their own, so a burst of runs can't delay\n// polls. A child that dies, grows or poisons TLS is retired.\nimport { readFileSync } from \"node:fs\";\nimport os from \"node:os\";\nimport {\n PieceWorker,\n PieceWorkerDisposedError,\n type IPieceWorker,\n type PieceWorkerHealth,\n type PieceWorkerOptions,\n type PieceWorkerResult,\n type RequestOptions,\n} from \"./host.js\";\nimport type {\n CheckConnectionRequest,\n DescribePieceRequest,\n ResolveOptionsRequest,\n RunActionRequest,\n TriggerHookRequest,\n} from \"./protocol.js\";\nimport type { WorkflowTelemetry } from \"../../../telemetry.js\";\n\n// Thrown when a request asks for a child the pool will not queue.\n\n// The pool queues without limit unless an operator caps it, so this only\n// appears where someone chose failing fast over waiting.\nexport class PieceWorkerPoolBusyError extends Error {\n constructor(size: number, waiting: number) {\n super(\n `All ${size} piece workers are busy and ${waiting} requests are already waiting`,\n );\n this.name = \"PieceWorkerPoolBusyError\";\n }\n}\n\nexport class PieceWorkerSessionClosedError extends Error {\n constructor() {\n super(\"This piece worker session is closed\");\n this.name = \"PieceWorkerSessionClosedError\";\n }\n}\n\n// Runs, trigger hooks, and the editor: each waits only behind its own lane.\nexport type PieceWorkerLane = \"run\" | \"trigger\" | \"design\";\n\nexport interface PieceWorkerPoolOptions extends PieceWorkerOptions {\n // Most children serving runs and design-time requests at once. Sized from\n // the container's cores and memory when unset.\n size?: number;\n // How many requests may wait for a child. 0 is unbounded: latency rather\n // than failure.\n maxQueueDepth?: number;\n // Children reserved for trigger hooks.\n triggerSlots?: number;\n // Children reserved for the editor's describe, options and connection checks.\n designSlots?: number;\n // Idle run children kept warm rather than retired.\n minWarm?: number;\n // Requests a child serves before it is retired, for leaks outside the heap.\n maxRequests?: number;\n // An idle child above the warm minimum exits after this long.\n idleMs?: number;\n // Children booting at once; more forks than this slow every boot.\n maxConcurrentForks?: number;\n // The reactor's own worker threads, which share the container's cores.\n reactorThreads?: number;\n // The container's memory, checked before each fork. Read from the cgroup by\n // default; a test substitutes its own.\n memory?: () => ContainerMemory | undefined;\n // Builds one worker. Defaults to a forked child; a test or a remote\n // deployment substitutes its own.\n createWorker?: (options: PieceWorkerOptions) => IPieceWorker;\n}\n\nexport interface ContainerMemory {\n limit: number;\n // Anonymous memory in use: what an out-of-memory kill counts.\n used: number;\n}\n\nexport interface PieceWorkerPoolStats {\n size: number;\n active: number;\n idle: number;\n waiting: number;\n}\n\nexport const DEFAULT_WORKER_HEAP_MB = 256;\n// Host-bound runs peak at 4-8 children; past this, a large host with no memory\n// limit could fork until it runs out.\nexport const DEFAULT_POOL_MAX = 32;\nconst DEFAULT_TRIGGER_SLOTS = 1;\nconst DEFAULT_DESIGN_SLOTS = 1;\nconst DEFAULT_MIN_WARM = 1;\nconst DEFAULT_MAX_REQUESTS = 1_000;\nconst DEFAULT_IDLE_MS = 60_000;\nconst DEFAULT_MAX_CONCURRENT_FORKS = 4;\n// A child is retired between requests past this share of its heap budget.\nconst HEAP_RETIREMENT = 0.8;\n// RSS over V8 heap total, measured on children with 1 to 14 pieces loaded.\nconst RSS_PER_HEAP = 1.6;\n// Forks stop while anonymous memory plus one child would pass this share.\nconst FORK_HEADROOM = 0.9;\n// About 0.3 cores per busy reactor executor thread.\nconst REACTOR_THREADS_PER_CORE = 3;\n// A fresh child's RSS, until a child has reported its own.\nconst FRESH_CHILD_BYTES = 80 * 1024 * 1024;\nconst MIB = 1024 * 1024;\n// A fork counts against the cap this long at most; boots measured 20-75ms.\nconst BOOT_WINDOW_MS = 1_000;\nconst LANES = [\"run\", \"trigger\", \"design\"] as const;\n\ninterface Child {\n readonly worker: IPieceWorker;\n readonly lane: PieceWorkerLane;\n // Bundles this child has loaded, so a request can find one already warm.\n readonly loaded: Set<string>;\n requests: number;\n busy: boolean;\n // Booting until its first reply or BOOT_WINDOW_MS, whichever comes first.\n forkedAt: number;\n replied: boolean;\n // Killed by a session closing mid-request; never handed out again.\n doomed: boolean;\n idleSince: number;\n session: PieceWorkerSession | undefined;\n}\n\ninterface Waiter {\n session: PieceWorkerSession;\n key: string | undefined;\n resolve: (child: Child) => void;\n reject: (error: unknown) => void;\n}\n\nfunction pieceKey(request: { bundleDir?: string; entryPath?: string }) {\n return request.bundleDir ?? request.entryPath;\n}\n\n// The most children the host can carry: the cores left after the reactor's\n// threads, or the memory left after the host, whichever is smaller.\nexport function defaultPoolSize(\n options: { reactorThreads?: number; heapMb?: number } = {},\n): number {\n const reactorThreads = Math.max(0, options.reactorThreads ?? 0);\n const cores =\n 2 * os.availableParallelism() -\n 1 -\n Math.floor(reactorThreads / REACTOR_THREADS_PER_CORE);\n const constrained = process.constrainedMemory();\n const limit =\n constrained > 0 && constrained < os.totalmem()\n ? constrained\n : os.totalmem();\n const perChild =\n RSS_PER_HEAP * (options.heapMb ?? DEFAULT_WORKER_HEAP_MB) * MIB;\n const memory = Math.floor((limit - process.memoryUsage.rss()) / perChild);\n return Math.max(1, Math.min(cores, memory, DEFAULT_POOL_MAX));\n}\n\n// cgroup v2 only; undefined outside a memory-limited container.\nexport function cgroupMemory(): ContainerMemory | undefined {\n try {\n const max = readFileSync(\"/sys/fs/cgroup/memory.max\", \"utf8\").trim();\n if (max === \"max\") return undefined;\n const stat = readFileSync(\"/sys/fs/cgroup/memory.stat\", \"utf8\");\n const anon = /^anon (\\d+)$/m.exec(stat)?.[1];\n if (!anon) return undefined;\n return { limit: Number(max), used: Number(anon) };\n } catch {\n return undefined;\n }\n}\n\n// At most one read a second: the reads are synchronous, on the main thread\n// the run dispatcher admits against.\nfunction cachedCgroupMemory(): () => ContainerMemory | undefined {\n let readAt = -Infinity;\n let last: ContainerMemory | undefined;\n return () => {\n const now = performance.now();\n if (now - readAt >= 1_000) {\n last = cgroupMemory();\n readAt = now;\n }\n return last;\n };\n}\n\n// A run's or a caller's handle on the pool. Holds no child of its own: each\n// request leases one, so a run whose steps are all core blocks forks nothing.\nexport class PieceWorkerSession implements IPieceWorker {\n private closed = false;\n\n constructor(\n private readonly pool: PieceWorkerPool,\n /** @internal */\n readonly lane: PieceWorkerLane,\n ) {}\n\n runAction(\n request: RunActionRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.runAction(request, options),\n );\n }\n\n resolveOptions(\n request: ResolveOptionsRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.resolveOptions(request, options),\n );\n }\n\n checkConnection(\n request: CheckConnectionRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.checkConnection(request, options),\n );\n }\n\n describePiece(\n request: DescribePieceRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.describePiece(request, options),\n );\n }\n\n runTriggerHook(\n request: TriggerHookRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.runTriggerHook(request, options),\n );\n }\n\n // Refuses this session's queued requests and kills any child serving one:\n // a run cancelled mid-step stops its piece code. Idempotent.\n close(): void {\n if (this.closed) return;\n this.closed = true;\n this.pool.closeSession(this);\n }\n\n /** @internal */\n isClosed(): boolean {\n return this.closed;\n }\n\n // IPieceWorker's teardown is this session's close: a caller holding one\n // through the interface ends its own requests, not the pool.\n dispose(): void {\n this.close();\n }\n}\n\nexport class PieceWorkerPool {\n readonly size: number;\n /** @internal */\n readonly telemetry: WorkflowTelemetry | undefined;\n private readonly maxQueueDepth: number;\n // Children reserved for trigger hooks; the supervisor runs as many at once.\n readonly triggerSlots: number;\n private readonly designSlots: number;\n private readonly minWarm: number;\n private readonly maxRequests: number;\n private readonly idleMs: number;\n private readonly maxConcurrentForks: number;\n private readonly heapMb: number;\n private readonly memory: () => ContainerMemory | undefined;\n private readonly createWorker: (options: PieceWorkerOptions) => IPieceWorker;\n private readonly workerOptions: PieceWorkerOptions;\n private readonly children = new Set<Child>();\n private readonly waiters: Record<PieceWorkerLane, Waiter[]> = {\n run: [],\n trigger: [],\n design: [],\n };\n private largestChild = FRESH_CHILD_BYTES;\n private idleTimer: NodeJS.Timeout | undefined;\n private bootTimer: NodeJS.Timeout | undefined;\n private disposed = false;\n\n constructor(options: PieceWorkerPoolOptions = {}) {\n const {\n size,\n maxQueueDepth,\n triggerSlots,\n designSlots,\n minWarm,\n maxRequests,\n idleMs,\n maxConcurrentForks,\n reactorThreads,\n memory,\n createWorker,\n ...workerOptions\n } = options;\n this.heapMb = workerOptions.heapMb ?? DEFAULT_WORKER_HEAP_MB;\n this.size = Math.max(\n 1,\n Math.trunc(\n size ?? defaultPoolSize({ reactorThreads, heapMb: this.heapMb }),\n ),\n );\n this.maxQueueDepth = Math.max(0, Math.trunc(maxQueueDepth ?? 0));\n this.triggerSlots = Math.max(\n 1,\n Math.trunc(triggerSlots ?? DEFAULT_TRIGGER_SLOTS),\n );\n this.designSlots = Math.max(\n 1,\n Math.trunc(designSlots ?? DEFAULT_DESIGN_SLOTS),\n );\n this.minWarm = Math.max(0, Math.trunc(minWarm ?? DEFAULT_MIN_WARM));\n this.maxRequests = Math.max(1, maxRequests ?? DEFAULT_MAX_REQUESTS);\n this.idleMs = Math.max(0, idleMs ?? DEFAULT_IDLE_MS);\n this.maxConcurrentForks = Math.max(\n 1,\n maxConcurrentForks ?? DEFAULT_MAX_CONCURRENT_FORKS,\n );\n this.memory = memory ?? cachedCgroupMemory();\n this.createWorker = createWorker ?? ((o) => new PieceWorker(o));\n this.workerOptions = { ...workerOptions, heapMb: this.heapMb };\n this.telemetry = workerOptions.telemetry;\n }\n\n // A handle for one run, the design-time editor, or the trigger supervisor.\n // Free until it makes a request; on a disposed pool every request rejects.\n session(lane: PieceWorkerLane = \"run\"): PieceWorkerSession {\n return new PieceWorkerSession(this, lane);\n }\n\n // Run children serving a request or idle, and requests waiting for one. The\n // wait is what a queue-depth alarm watches.\n stats(): PieceWorkerPoolStats {\n let active = 0;\n let idle = 0;\n for (const child of this.children) {\n if (child.lane !== \"run\") continue;\n if (child.busy) active++;\n else idle++;\n }\n return { size: this.size, active, idle, waiting: this.waiters.run.length };\n }\n\n // Kills every child, mid-request ones too, and refuses queued requests.\n // For shutdown; a live run does not survive it.\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n clearTimeout(this.bootTimer);\n this.bootTimer = undefined;\n for (const lane of LANES) {\n for (const waiter of this.waiters[lane].splice(0)) {\n waiter.reject(new PieceWorkerDisposedError());\n }\n }\n for (const child of this.children) child.worker.dispose();\n this.children.clear();\n }\n\n /** @internal — one request on a leased child. */\n async request<T>(\n session: PieceWorkerSession,\n key: string | undefined,\n fn: (worker: IPieceWorker) => Promise<T>,\n ): Promise<T> {\n if (session.isClosed()) throw new PieceWorkerSessionClosedError();\n const child = await this.lease(session, key);\n // Closed or disposed while it waited: the child is killed, not used.\n if (this.disposed) {\n this.giveBack(child, key);\n throw new PieceWorkerDisposedError();\n }\n if (session.isClosed()) {\n this.giveBack(child, key);\n throw new PieceWorkerSessionClosedError();\n }\n try {\n return await fn(child.worker);\n } finally {\n this.giveBack(child, key);\n }\n }\n\n /** @internal — a session that closed. */\n closeSession(session: PieceWorkerSession): void {\n const queue = this.waiters[session.lane];\n for (let i = queue.length - 1; i >= 0; i--) {\n if (queue[i].session !== session) continue;\n const [waiter] = queue.splice(i, 1);\n waiter.reject(new PieceWorkerSessionClosedError());\n }\n for (const child of this.children) {\n if (child.busy && child.session === session) {\n child.doomed = true;\n child.worker.dispose();\n }\n }\n }\n\n private lease(\n session: PieceWorkerSession,\n key: string | undefined,\n ): Promise<Child> {\n if (this.disposed) {\n return Promise.reject(new PieceWorkerDisposedError());\n }\n const queue = this.waiters[session.lane];\n // FIFO: a request arriving behind waiters must not overtake them.\n const child = queue.length === 0 ? this.take(session.lane, key) : undefined;\n if (child) {\n child.session = session;\n return Promise.resolve(child);\n }\n if (\n session.lane === \"run\" &&\n this.maxQueueDepth > 0 &&\n queue.length >= this.maxQueueDepth\n ) {\n return Promise.reject(\n new PieceWorkerPoolBusyError(this.size, queue.length),\n );\n }\n const wait = new Promise<Child>((resolve, reject) => {\n queue.push({ session, key, resolve, reject });\n });\n // The wait for a child; a run's own timings can't show it.\n return this.telemetry\n ? this.telemetry.phase(\"worker.acquire\", {}, () => wait)\n : wait;\n }\n\n // An idle child with the piece loaded, then the most recently used idle\n // child so the rest can idle out, then a new child.\n private take(lane: PieceWorkerLane, key: string | undefined) {\n let warm: Child | undefined;\n let recent: Child | undefined;\n for (const child of this.children) {\n if (child.lane !== lane || child.busy) continue;\n if (key && child.loaded.has(key)) {\n warm = child;\n break;\n }\n if (!recent || child.idleSince > recent.idleSince) recent = child;\n }\n const child = warm ?? recent ?? this.fork(lane);\n if (child) child.busy = true;\n return child;\n }\n\n private fork(lane: PieceWorkerLane): Child | undefined {\n let inLane = 0;\n let booting = 0;\n let firstBootEnds = Infinity;\n const now = performance.now();\n for (const child of this.children) {\n if (child.lane === lane) inLane++;\n if (!child.replied && now - child.forkedAt < BOOT_WINDOW_MS) {\n booting++;\n firstBootEnds = Math.min(\n firstBootEnds,\n child.forkedAt + BOOT_WINDOW_MS,\n );\n }\n }\n const capacity = {\n run: this.size,\n trigger: this.triggerSlots,\n design: this.designSlots,\n }[lane];\n if (inLane >= capacity) return undefined;\n // A lane's first child forks regardless of either limit, or its requests\n // would wait on another lane's. An out-of-memory kill takes the host.\n if (inLane > 0) {\n if (booting >= this.maxConcurrentForks) {\n this.redispatchAt(firstBootEnds - now);\n return undefined;\n }\n if (!this.roomForChild()) return undefined;\n }\n const child: Child = {\n worker: this.createWorker(this.workerOptions),\n lane,\n loaded: new Set(),\n requests: 0,\n busy: false,\n forkedAt: now,\n replied: false,\n doomed: false,\n idleSince: 0,\n session: undefined,\n };\n this.children.add(child);\n return child;\n }\n\n private roomForChild(): boolean {\n const memory = this.memory();\n if (!memory) return true;\n return memory.used + this.largestChild <= FORK_HEADROOM * memory.limit;\n }\n\n private giveBack(child: Child, key: string | undefined): void {\n child.busy = false;\n child.replied = true;\n child.session = undefined;\n child.requests++;\n child.idleSince = performance.now();\n const health = child.worker.health?.();\n if (health?.memory) {\n this.largestChild = Math.max(this.largestChild, health.memory.rss);\n }\n if (this.spent(child, health)) {\n this.retire(child);\n } else if (key) {\n child.loaded.add(key);\n }\n this.dispatch();\n this.scheduleIdleSweep();\n }\n\n private spent(child: Child, health: PieceWorkerHealth | undefined): boolean {\n if (this.disposed || child.doomed) return true;\n if (child.requests >= this.maxRequests) return true;\n if (!health) return false;\n // Dead or timed out: the next request would fork a stranger anyway.\n if (!health.alive || health.tlsPoisoned) return true;\n return (\n health.memory !== undefined &&\n health.memory.heapUsed > HEAP_RETIREMENT * this.heapMb * MIB\n );\n }\n\n private retire(child: Child): void {\n this.children.delete(child);\n child.worker.dispose();\n }\n\n // Serves waiters in order, each lane on its own.\n private dispatch(): void {\n if (this.disposed) return;\n for (const lane of LANES) {\n const queue = this.waiters[lane];\n while (queue.length > 0) {\n const child = this.take(lane, queue[0].key);\n if (!child) break;\n const waiter = queue.shift()!;\n child.session = waiter.session;\n waiter.resolve(child);\n }\n }\n }\n\n // A boot window that closes with no reply frees a fork; nothing else would\n // tell the waiters.\n private redispatchAt(ms: number): void {\n if (this.bootTimer || this.disposed) return;\n this.bootTimer = setTimeout(\n () => {\n this.bootTimer = undefined;\n this.dispatch();\n },\n Math.max(1, ms),\n );\n this.bootTimer.unref();\n }\n\n private scheduleIdleSweep(): void {\n if (this.idleTimer || this.disposed || this.idleMs === 0) return;\n if (this.retirable().length === 0) return;\n this.idleTimer = setTimeout(() => {\n this.idleTimer = undefined;\n this.sweepIdle();\n }, this.idleMs);\n this.idleTimer.unref();\n }\n\n // Retires children idle past idleMs. Trigger children stay: polls come back\n // on a schedule.\n private sweepIdle(): void {\n const now = performance.now();\n for (const child of this.retirable()) {\n if (now - child.idleSince >= this.idleMs) this.retire(child);\n }\n this.scheduleIdleSweep();\n }\n\n // Idle run children above the warm minimum, oldest first, and every idle\n // editor child: the editor is used now and then.\n private retirable(): Child[] {\n const idle = (lane: PieceWorkerLane) =>\n [...this.children]\n .filter((child) => child.lane === lane && !child.busy)\n .sort((a, b) => a.idleSince - b.idleSince);\n const run = idle(\"run\");\n return [\n ...run.slice(0, Math.max(0, run.length - this.minWarm)),\n ...idle(\"design\"),\n ];\n }\n}\n","// Structural mirror of the powerhouse/workflow document state (doc 08 §5.1).\n// The engine stays decoupled from the generated document-model types.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport type { BlockResolution, StepPieceRecord } from \"./resolution.js\";\n\n// `schema` is a DYNAMIC prop's resolved child props, keyed by child name.\nexport interface PropertySettingDef {\n prop: string;\n mode?: string;\n schema?: unknown;\n}\n\nexport interface WorkflowTriggerDef {\n id: string;\n pieceName: string;\n pieceVersion: string;\n triggerName: string;\n connectionId?: string | null;\n // A REACTOR connection, for a trigger that declares requireReactor.\n reactorConnectionId?: string | null;\n config?: unknown;\n propertySettings?: PropertySettingDef[] | null;\n}\n\nexport interface WorkflowStepDef {\n id: string;\n key: string;\n name?: string;\n pieceName: string;\n pieceVersion: string;\n actionName: string;\n connectionId?: string | null;\n // A REACTOR connection, for an action that declares requireReactor.\n reactorConnectionId?: string | null;\n config: unknown;\n timeoutSeconds?: number | null;\n propertySettings?: PropertySettingDef[] | null;\n // Passed over at run time: not executed, continues on \"next\" with a null output.\n skip?: boolean | null;\n // The author's retry block, unresolved; `effectiveRetryPolicy` reads it.\n // Falls back to the workflow policy's `defaultRetry`.\n retry?: unknown;\n}\n\nexport interface WorkflowEdgeDef {\n id: string;\n from: string;\n to: string;\n port: string;\n condition?: string | null;\n}\n\nexport interface WorkflowVariableDef {\n key: string;\n value?: unknown;\n}\n\nexport interface WorkflowDefinition {\n name?: string;\n trigger?: WorkflowTriggerDef | null;\n steps: WorkflowStepDef[];\n edges: WorkflowEdgeDef[];\n variables?: WorkflowVariableDef[];\n}\n\nexport interface BlockExecution {\n block: BlockRef;\n // Step config with expressions already resolved against the run scope.\n config: unknown;\n connectionId?: string | null;\n reactorConnectionId?: string | null;\n step: WorkflowStepDef;\n // Run-wide secret values (SECRET variables) the executor redacts as well.\n redactValues?: string[];\n}\n\nexport interface BlockResult {\n output: unknown;\n // Output port routing the step's outgoing edges; defaults to \"next\".\n port?: string;\n // Secret values this step ran with. The live output keeps them, so the next\n // step still works; only the journaled copy has them replaced.\n redactValues?: string[];\n // The piece version this step ran, when a piece ran it.\n resolution?: BlockResolution;\n}\n\nexport interface BlockExecutor {\n execute(execution: BlockExecution): Promise<BlockResult>;\n}\n\n// REPLAYED: output reused from a prior run's journal instead of executing.\n// SKIPPED: never reached, or flagged `skip` (then it carries port \"next\").\n// INDETERMINATE: the step neither returned nor failed — a host call it made\n// timed out, so a write it asked for may well have been committed. Reporting\n// that as FAILED would be a claim nobody can stand behind, so it is its own\n// state: it takes no port, ends the run, and never replays on rerun.\nexport type StepExecutionStatus =\n | \"SUCCEEDED\"\n | \"FAILED\"\n | \"SKIPPED\"\n | \"REPLAYED\"\n | \"INDETERMINATE\";\n\nexport interface StepExecutionRecord {\n stepId: string;\n key: string;\n pieceName: string;\n // The step's action, or the trigger's name for a trigger test.\n blockName: string;\n status: StepExecutionStatus;\n // Resolved config the block ran with; absent for skipped steps.\n input?: unknown;\n output?: unknown;\n /**\n * Journaled in the output column in place of `output`, when there is no\n * output to hand a caller but the row still has to say something.\n *\n * One use today: a REPLAYED step whose journaled output the payload cap\n * truncated. The record's `output` stays absent — a caller must not be\n * handed a marker where real data goes — while the row keeps the marker, so\n * a SECOND rerun still knows the output is gone and tells a downstream step\n * by name instead of resolving it to nothing.\n */\n journaledOutput?: unknown;\n port?: string;\n error?: string;\n // The thrown error's name, e.g. ReactorAccessDeniedError.\n errorName?: string;\n // ISO times the block ran between; absent for skipped and replayed steps.\n startedAt?: string;\n endedAt?: string;\n // The piece version that ran; absent for an unresolved block.\n piece?: StepPieceRecord;\n // Hash of the step definition it ran from; rerun replays only an unchanged one.\n configHash?: string;\n // How many times the block ran, when its retry policy let it run more than\n // once. Absent for a single attempt, so an unretried step journals as it did.\n attempts?: number;\n}\n\n// CANCELLED: the run passed its `runTimeoutSeconds`, or a firing was skipped\n// because the workflow's concurrency mode is SINGLETON and a run was active.\n// Neither is a failure of the workflow, which is why it is not FAILED.\nexport type WorkflowRunStatus = \"SUCCEEDED\" | \"FAILED\" | \"CANCELLED\";\n\nexport interface WorkflowRunResult {\n status: WorkflowRunStatus;\n steps: StepExecutionRecord[];\n error?: string;\n errorName?: string;\n // What ran but deserves a look, e.g. an edge on a port nothing emits.\n warnings?: string[];\n}\n\nexport function stepBlock(\n step: Pick<WorkflowStepDef, \"pieceName\" | \"pieceVersion\" | \"actionName\">,\n): BlockRef {\n return {\n pieceName: step.pieceName,\n pieceVersion: step.pieceVersion,\n kind: \"action\",\n name: step.actionName,\n };\n}\n\nexport function triggerBlock(\n trigger: Pick<\n WorkflowTriggerDef,\n \"pieceName\" | \"pieceVersion\" | \"triggerName\"\n >,\n): BlockRef {\n return {\n pieceName: trigger.pieceName,\n pieceVersion: trigger.pieceVersion,\n kind: \"trigger\",\n name: trigger.triggerName,\n };\n}\n","// Secret references and the provider/store seams. Refs are server-minted\n// random ids — stable handles over mutable values, never content hashes.\n\nexport const SECRET_REF_PREFIX = \"secret://v1:\";\n\nconst SECRET_ID_PATTERN = /^[0-9a-f]{32}$/;\n\n// Read seam consumed by the engine (connection resolution).\nexport interface SecretProvider {\n get(ref: string): Promise<string>;\n}\n\nexport interface SecretStat {\n ref: string;\n label: string | null;\n version: number;\n status: \"ACTIVE\" | \"DELETED\";\n createdAt: string;\n updatedAt: string;\n}\n\n// Full lifecycle, implemented by managed backends. `get` is execution-context\n// only and must never be exposed over a transport.\nexport interface SecretStore extends SecretProvider {\n create(input: { value: string; label?: string }): Promise<SecretStat>;\n rotate(ref: string, value: string): Promise<SecretStat>;\n stat(ref: string): Promise<SecretStat>;\n list(): Promise<SecretStat[]>;\n delete(ref: string): Promise<void>;\n}\n\nexport class SecretNotFoundError extends Error {\n constructor(ref: string) {\n super(`No secret found for ref \"${ref}\"`);\n this.name = \"SecretNotFoundError\";\n }\n}\n\nexport class SecretDeletedError extends Error {\n constructor(ref: string) {\n super(`Secret \"${ref}\" has been deleted`);\n this.name = \"SecretDeletedError\";\n }\n}\n\nexport class InvalidSecretRefError extends Error {\n constructor(ref: string) {\n super(\n `Invalid secret ref \"${ref}\"; expected ${SECRET_REF_PREFIX}<32 hex chars>`,\n );\n this.name = \"InvalidSecretRefError\";\n }\n}\n\nexport function isSecretRef(ref: string): boolean {\n return (\n ref.startsWith(SECRET_REF_PREFIX) &&\n SECRET_ID_PATTERN.test(ref.slice(SECRET_REF_PREFIX.length))\n );\n}\n\n// Returns the 32-hex id; throws on anything else.\nexport function parseSecretRef(ref: string): string {\n if (!isSecretRef(ref)) throw new InvalidSecretRefError(ref);\n return ref.slice(SECRET_REF_PREFIX.length);\n}\n\nexport function secretRefFromId(id: string): string {\n if (!SECRET_ID_PATTERN.test(id)) throw new InvalidSecretRefError(id);\n return `${SECRET_REF_PREFIX}${id}`;\n}\n\nexport class InMemorySecretProvider implements SecretProvider {\n private readonly secrets: Map<string, string>;\n\n constructor(secrets: Record<string, string>) {\n this.secrets = new Map(Object.entries(secrets));\n }\n\n get(ref: string): Promise<string> {\n const value = this.secrets.get(ref);\n if (value === undefined)\n return Promise.reject(new SecretNotFoundError(ref));\n return Promise.resolve(value);\n }\n}\n","// {{…}} expressions over the run scope. Grammar and rules: README, \"Expressions\".\n\nexport interface ExpressionScope {\n trigger?: unknown;\n // A step contributes `output` when it succeeded and `error` when it did not.\n // The failed entry is what an error-port branch reads.\n steps: Record<string, { output?: unknown; error?: string }>;\n variables: Record<string, unknown>;\n}\n\nexport type PathSegment = string | number;\n\nexport interface PathTerm {\n kind: \"path\";\n segments: PathSegment[];\n // `?` suffix: a missing value resolves to null instead of failing.\n optional: boolean;\n source: string;\n}\n\nexport interface LiteralTerm {\n kind: \"literal\";\n value: string;\n}\n\nexport type ExpressionTerm = PathTerm | LiteralTerm;\n\n// `a || b || 'x'`: the first term with a value other than null or \"\".\nexport interface Expression {\n terms: ExpressionTerm[];\n source: string;\n}\n\nexport class ExpressionSyntaxError extends Error {\n constructor(source: string, detail: string) {\n super(`Invalid expression {{${source}}}: ${detail}`);\n this.name = \"ExpressionSyntaxError\";\n }\n}\n\nexport class UnresolvedReferenceError extends Error {\n constructor(readonly reference: string) {\n super(`Unresolved reference {{${reference}}}`);\n this.name = \"UnresolvedReferenceError\";\n }\n}\n\n/**\n * A value that exists but cannot be read, with the reason attached.\n *\n * The case it was written for: a rerun replaying a SUCCEEDED step whose\n * journaled output the payload cap truncated. The step must NOT run again — it\n * had side effects — but its output is genuinely gone, so a downstream step\n * that reads it has to be told, by name, rather than handed a truncation\n * marker or quietly made to re-run the step that produced it.\n *\n * The reason hangs off a SYMBOL key, so `JSON.stringify` drops it and nothing\n * can leak the wrapper into a payload as data.\n */\nconst UNAVAILABLE = Symbol(\"unavailable\");\n\nexport class UnavailableValueError extends Error {\n constructor(reason: string) {\n super(reason);\n this.name = \"UnavailableValueError\";\n }\n}\n\nexport function unavailableValue(reason: string): unknown {\n return { [UNAVAILABLE]: reason };\n}\n\nfunction unavailableReason(value: unknown): string | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const reason = (value as Record<symbol, unknown>)[UNAVAILABLE];\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/**\n * The reason of the first {@link unavailableValue} anywhere inside a value,\n * however deep, or undefined when there is none.\n *\n * A shallow check is not enough, and that was the hole: `{{steps.charge}}`\n * lands on the step's whole entry rather than on the wrapper, so the wrapper\n * sits one level down as `{ output: <wrapper> }`. The path check saw an\n * ordinary object, handed it over as data, and `JSON.stringify` then dropped\n * the symbol on the way to the piece — the downstream step received `{}` and\n * the reason was gone. Refusing by name is the whole point of the wrapper.\n */\nexport function unavailableValueReason(value: unknown): string | undefined {\n const own = unavailableReason(value);\n if (own !== undefined) return own;\n if (Array.isArray(value)) {\n for (const item of value) {\n const nested = unavailableValueReason(item);\n if (nested !== undefined) return nested;\n }\n return undefined;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const entry of Object.values(value)) {\n const nested = unavailableValueReason(entry);\n if (nested !== undefined) return nested;\n }\n }\n return undefined;\n}\n\n/** True for anything {@link unavailableValue} produced, at any depth of a\n * resolved value. Lets a caller refuse before a piece is handed it. */\nexport function containsUnavailableValue(value: unknown): boolean {\n return unavailableValueReason(value) !== undefined;\n}\n\n/** Throws {@link UnavailableValueError} when a resolved value holds an\n * unavailable wrapper at any depth; the gate every resolved input passes. */\nexport function assertNoUnavailableValue(value: unknown): void {\n const reason = unavailableValueReason(value);\n if (reason !== undefined) throw new UnavailableValueError(reason);\n}\n\nconst IDENT = /[A-Za-z0-9_$-]/;\n\n// A hand-rolled tokenizer: dot and bracket paths, quoted literals, `||`, `?`.\nexport function parseExpression(source: string): Expression {\n let i = 0;\n const fail = (detail: string): never => {\n throw new ExpressionSyntaxError(source, detail);\n };\n const skipSpace = () => {\n while (i < source.length && /\\s/.test(source[i])) i++;\n };\n const readString = (): string => {\n const quote = source[i++];\n let out = \"\";\n while (i < source.length && source[i] !== quote) {\n if (source[i] === \"\\\\\" && i + 1 < source.length) {\n out += source[i + 1];\n i += 2;\n continue;\n }\n out += source[i++];\n }\n if (source[i] !== quote) fail(\"unterminated string\");\n i++;\n return out;\n };\n const readIdent = (): string => {\n const start = i;\n while (i < source.length && IDENT.test(source[i])) i++;\n if (i === start) fail(`expected a name at position ${start}`);\n return source.slice(start, i);\n };\n const readTerm = (): ExpressionTerm => {\n skipSpace();\n const start = i;\n if (source[i] === \"'\" || source[i] === '\"') {\n return { kind: \"literal\", value: readString() };\n }\n const segments: PathSegment[] = [readIdent()];\n for (;;) {\n if (source[i] === \".\") {\n i++;\n segments.push(readIdent());\n continue;\n }\n if (source[i] === \"[\") {\n i++;\n skipSpace();\n if (source[i] === \"'\" || source[i] === '\"') {\n segments.push(readString());\n } else {\n const digits = /^\\d+/.exec(source.slice(i));\n if (!digits) fail(\"a bracket takes a quoted key or an index\");\n segments.push(Number(digits![0]));\n i += digits![0].length;\n }\n skipSpace();\n if (source[i] !== \"]\") fail(\"expected ]\");\n i++;\n continue;\n }\n break;\n }\n const optional = source[i] === \"?\";\n if (optional) i++;\n return {\n kind: \"path\",\n segments,\n optional,\n source: source.slice(start, i),\n };\n };\n\n const terms: ExpressionTerm[] = [readTerm()];\n for (;;) {\n skipSpace();\n if (i >= source.length) break;\n if (source.startsWith(\"||\", i)) {\n i += 2;\n terms.push(readTerm());\n continue;\n }\n fail(`unexpected \"${source[i]}\" at position ${i}`);\n }\n return { terms, source: source.trim() };\n}\n\ninterface Segment {\n kind: \"text\" | \"expression\";\n text: string;\n}\n\n// Splits text into literal runs and {{…}} bodies. `\\{{` is a literal `{{`;\n// `}}` inside a quoted literal does not close; an unclosed `{{` is text.\nexport function splitTemplate(text: string): Segment[] {\n const out: Segment[] = [];\n let pending = \"\";\n let cursor = 0;\n const flush = () => {\n if (pending) out.push({ kind: \"text\", text: pending });\n pending = \"\";\n };\n for (;;) {\n const open = text.indexOf(\"{{\", cursor);\n if (open < 0) break;\n if (open > 0 && text[open - 1] === \"\\\\\") {\n pending += text.slice(cursor, open - 1) + \"{{\";\n cursor = open + 2;\n continue;\n }\n let i = open + 2;\n let quote: string | undefined;\n let close = -1;\n for (; i < text.length; i++) {\n const char = text[i];\n if (quote) {\n if (char === \"\\\\\") i++;\n else if (char === quote) quote = undefined;\n continue;\n }\n if (char === \"'\" || char === '\"') quote = char;\n else if (text.startsWith(\"}}\", i)) {\n close = i;\n break;\n }\n }\n if (close < 0) break;\n pending += text.slice(cursor, open);\n flush();\n out.push({ kind: \"expression\", text: text.slice(open + 2, close) });\n cursor = close + 2;\n }\n pending += text.slice(cursor);\n flush();\n return out;\n}\n\n/** Every expression a string holds, parsed. */\nexport function expressionsIn(text: string): Expression[] {\n return splitTemplate(text)\n .filter((segment) => segment.kind === \"expression\")\n .map((segment) => parseExpression(segment.text));\n}\n\nconst MISSING = Symbol(\"missing\");\n\nexport function lookupPath(\n scope: ExpressionScope,\n segments: readonly PathSegment[],\n): unknown {\n let current: unknown = scope;\n for (const segment of segments) {\n if (current === null || typeof current !== \"object\") return MISSING;\n // Not missing and not readable: say which, before the path walks into it.\n // Shallow on purpose — a container holding one unavailable entry is still\n // readable for every other path through it.\n const blocked = unavailableReason(current);\n if (blocked !== undefined) throw new UnavailableValueError(blocked);\n const record = current as Record<string | number, unknown>;\n if (!Object.prototype.hasOwnProperty.call(record, segment)) return MISSING;\n current = record[segment];\n }\n // What the path landed on is what leaves resolution, so the check here is\n // DEEP: `steps.x.output` lands on the wrapper itself, but `steps.x` lands on\n // the entry holding it, and handing that over would drop the reason on the\n // symbol and give the piece a bare `{}`.\n assertNoUnavailableValue(current);\n return current === undefined ? MISSING : current;\n}\n\nconst isEmpty = (value: unknown) => value === null || value === \"\";\n\nexport function evaluateExpression(\n expression: Expression,\n scope: ExpressionScope,\n): unknown {\n const last = expression.terms.length - 1;\n let value: unknown = null;\n for (const [index, term] of expression.terms.entries()) {\n if (term.kind === \"literal\") {\n value = term.value;\n } else {\n const found = lookupPath(scope, term.segments);\n if (found === MISSING) {\n if (term.optional) value = null;\n else if (index === last)\n throw new UnresolvedReferenceError(term.source);\n else continue;\n } else value = found;\n }\n if (!isEmpty(value)) return value;\n }\n return value;\n}\n\nfunction interpolate(value: unknown): string {\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value as string | number | boolean);\n}\n\n// A string that is one {{…}} once trimmed yields the raw value; any other\n// string with expressions is interpolated text.\nexport function resolveTemplate(text: string, scope: ExpressionScope): unknown {\n const segments = splitTemplate(text);\n if (!segments.some((segment) => segment.kind === \"expression\")) {\n return segments.map((segment) => segment.text).join(\"\");\n }\n const meaningful = segments.filter(\n (segment) => segment.kind === \"expression\" || segment.text.trim() !== \"\",\n );\n if (meaningful.length === 1) {\n return evaluateExpression(parseExpression(meaningful[0].text), scope);\n }\n return segments\n .map((segment) =>\n segment.kind === \"text\"\n ? segment.text\n : interpolate(evaluateExpression(parseExpression(segment.text), scope)),\n )\n .join(\"\");\n}\n\n/** Evaluates every string in a value, nested ones included. */\nexport function resolveExpressions(\n value: unknown,\n scope: ExpressionScope,\n): unknown {\n if (typeof value === \"string\") return resolveTemplate(value, scope);\n if (Array.isArray(value)) {\n return value.map((item) => resolveExpressions(item, scope));\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n resolveExpressions(entry, scope),\n ]),\n );\n }\n return value;\n}\n\n// Truthiness of a resolved condition; the strings \"false\" and \"0\" are falsy.\nexport function evaluateCondition(\n condition: string,\n scope: ExpressionScope,\n): boolean {\n const resolved = resolveTemplate(condition, scope);\n if (resolved === \"false\" || resolved === \"0\") return false;\n return Boolean(resolved);\n}\n","// Branch operators, after Activepieces' BranchOperator: one explicit operator\n// over typed operands. A wrongly typed operand fails the step, never coerces.\n\nexport type BranchOperandType =\n | \"text\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"list\"\n | \"any\";\n\nexport interface BranchOperatorSpec {\n label: string;\n // What `left` must hold; `right` is read as the same type, text for lists.\n left: BranchOperandType;\n // Whether `right` is read at all.\n binary: boolean;\n // Whether `caseSensitive` applies.\n text: boolean;\n test: (left: unknown, right: unknown, caseSensitive: boolean) => boolean;\n}\n\nexport class BranchConfigError extends Error {\n constructor(message: string) {\n super(`Branch: ${message}`);\n this.name = \"BranchConfigError\";\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return \"nothing\";\n const text = JSON.stringify(value);\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\nfunction asText(value: unknown, side: string, caseSensitive: boolean): string {\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n ) {\n throw new BranchConfigError(`${side} must be text, got ${describe(value)}`);\n }\n const text = String(value);\n return caseSensitive ? text : text.toLowerCase();\n}\n\nconst DECIMAL = /^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?$/;\n\nfunction asNumber(value: unknown, side: string): number {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && DECIMAL.test(value.trim())) {\n return Number(value.trim());\n }\n throw new BranchConfigError(\n `${side} must be a number, got ${describe(value)}`,\n );\n}\n\nfunction asBoolean(value: unknown, side: string): boolean {\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw new BranchConfigError(\n `${side} must be true or false, got ${describe(value)}`,\n );\n}\n\nfunction asDate(value: unknown, side: string): number {\n const time =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\" && value.trim() !== \"\"\n ? Date.parse(value)\n : Number.NaN;\n if (!Number.isFinite(time)) {\n throw new BranchConfigError(\n `${side} must be a date, got ${describe(value)}`,\n );\n }\n return time;\n}\n\nfunction asList(value: unknown, side: string): unknown[] {\n if (Array.isArray(value)) return value;\n throw new BranchConfigError(`${side} must be a list, got ${describe(value)}`);\n}\n\nconst blank = (value: unknown) =>\n value === undefined || value === null || value === \"\";\n\nfunction textOp(\n label: string,\n test: (left: string, right: string) => boolean,\n): BranchOperatorSpec {\n return {\n label,\n left: \"text\",\n binary: true,\n text: true,\n test: (left, right, caseSensitive) =>\n test(\n asText(left, \"left\", caseSensitive),\n asText(right, \"right\", caseSensitive),\n ),\n };\n}\n\nfunction numberOp(\n label: string,\n test: (left: number, right: number) => boolean,\n): BranchOperatorSpec {\n return {\n label,\n left: \"number\",\n binary: true,\n text: false,\n test: (left, right) =>\n test(asNumber(left, \"left\"), asNumber(right, \"right\")),\n };\n}\n\nfunction dateOp(\n label: string,\n test: (left: number, right: number) => boolean,\n): BranchOperatorSpec {\n return {\n label,\n left: \"date\",\n binary: true,\n text: false,\n test: (left, right) => test(asDate(left, \"left\"), asDate(right, \"right\")),\n };\n}\n\nfunction unary(\n label: string,\n left: BranchOperandType,\n test: (left: unknown) => boolean,\n): BranchOperatorSpec {\n return { label, left, binary: false, text: false, test };\n}\n\nfunction listHas(\n left: unknown,\n right: unknown,\n caseSensitive: boolean,\n): boolean {\n const wanted = asText(right, \"right\", caseSensitive);\n return asList(left, \"left\").some((item) => {\n if (typeof item === \"object\" && item !== null) return false;\n const text = String(item);\n return (caseSensitive ? text : text.toLowerCase()) === wanted;\n });\n}\n\n// In the order the editor lists them.\nexport const BRANCH_OPERATORS = {\n TEXT_EXACTLY_MATCHES: textOp(\"Text is exactly\", (a, b) => a === b),\n TEXT_DOES_NOT_EXACTLY_MATCH: textOp(\"Text is not exactly\", (a, b) => a !== b),\n TEXT_CONTAINS: textOp(\"Text contains\", (a, b) => a.includes(b)),\n TEXT_DOES_NOT_CONTAIN: textOp(\n \"Text does not contain\",\n (a, b) => !a.includes(b),\n ),\n TEXT_STARTS_WITH: textOp(\"Text starts with\", (a, b) => a.startsWith(b)),\n TEXT_DOES_NOT_START_WITH: textOp(\n \"Text does not start with\",\n (a, b) => !a.startsWith(b),\n ),\n TEXT_ENDS_WITH: textOp(\"Text ends with\", (a, b) => a.endsWith(b)),\n TEXT_DOES_NOT_END_WITH: textOp(\n \"Text does not end with\",\n (a, b) => !a.endsWith(b),\n ),\n NUMBER_IS_EQUAL_TO: numberOp(\"Number equals\", (a, b) => a === b),\n NUMBER_IS_GREATER_THAN: numberOp(\"Number is greater than\", (a, b) => a > b),\n NUMBER_IS_LESS_THAN: numberOp(\"Number is less than\", (a, b) => a < b),\n DATE_IS_EQUAL: dateOp(\"Date is\", (a, b) => a === b),\n DATE_IS_BEFORE: dateOp(\"Date is before\", (a, b) => a < b),\n DATE_IS_AFTER: dateOp(\"Date is after\", (a, b) => a > b),\n BOOLEAN_IS_TRUE: unary(\"Is true\", \"boolean\", (v) => asBoolean(v, \"left\")),\n BOOLEAN_IS_FALSE: unary(\"Is false\", \"boolean\", (v) => !asBoolean(v, \"left\")),\n LIST_CONTAINS: {\n label: \"List contains\",\n left: \"list\",\n binary: true,\n text: true,\n test: listHas,\n },\n LIST_DOES_NOT_CONTAIN: {\n label: \"List does not contain\",\n left: \"list\",\n binary: true,\n text: true,\n test: (left, right, caseSensitive) => !listHas(left, right, caseSensitive),\n },\n LIST_IS_EMPTY: unary(\n \"List is empty\",\n \"list\",\n (v) => asList(v, \"left\").length === 0,\n ),\n LIST_IS_NOT_EMPTY: unary(\n \"List is not empty\",\n \"list\",\n (v) => asList(v, \"left\").length > 0,\n ),\n EXISTS: unary(\"Exists\", \"any\", (v) => !blank(v)),\n DOES_NOT_EXIST: unary(\"Does not exist\", \"any\", blank),\n} satisfies Record<string, BranchOperatorSpec>;\n\nexport type BranchOperator = keyof typeof BRANCH_OPERATORS;\n\n// Operators whose operand may name nothing: missing is what they test for.\nexport const EXISTENCE_OPERATORS: ReadonlySet<string> = new Set<BranchOperator>(\n [\"EXISTS\", \"DOES_NOT_EXIST\"],\n);\n\nconst OPERATORS: Record<string, BranchOperatorSpec> = BRANCH_OPERATORS;\n\nexport const DEFAULT_BRANCH_OPERATOR: BranchOperator = \"TEXT_EXACTLY_MATCHES\";\n\nexport interface BranchOutcome {\n operator: BranchOperator;\n left: unknown;\n right?: unknown;\n result: boolean;\n}\n\n// Config: { operator, left, right?, caseSensitive? }, expressions resolved.\nexport function evaluateBranch(config: unknown): BranchOutcome {\n if (config === null || typeof config !== \"object\" || Array.isArray(config)) {\n throw new BranchConfigError(\"the config must be an object\");\n }\n const { operator, left, right, caseSensitive } = config as Record<\n string,\n unknown\n >;\n if (operator === undefined || operator === null || operator === \"\") {\n throw new BranchConfigError(\"an operator is required\");\n }\n if (typeof operator !== \"string\" || !Object.hasOwn(OPERATORS, operator)) {\n throw new BranchConfigError(`unknown operator ${describe(operator)}`);\n }\n if (caseSensitive !== undefined && typeof caseSensitive !== \"boolean\") {\n throw new BranchConfigError(\"caseSensitive must be true or false\");\n }\n const spec = OPERATORS[operator];\n const result = spec.test(left, right, caseSensitive === true);\n return {\n operator: operator as BranchOperator,\n left,\n ...(spec.binary ? { right } : {}),\n result,\n };\n}\n","// A step's config with its expressions resolved, as the step receives it.\nimport { CORE_PIECE_NAME } from \"@powerhousedao/pieces-framework/workflow\";\nimport { EXISTENCE_OPERATORS } from \"../core/branch-operators.js\";\nimport {\n assertNoUnavailableValue,\n resolveExpressions,\n UnresolvedReferenceError,\n type ExpressionScope,\n} from \"./expressions.js\";\nimport type { WorkflowStepDef } from \"./types.js\";\n\ntype StepInputSource = Pick<\n WorkflowStepDef,\n \"pieceName\" | \"actionName\" | \"config\"\n>;\n\n/**\n * A step's resolved input, and the last gate before it crosses to the piece.\n *\n * The unavailable wrapper carries its reason on a symbol, so anything that\n * serializes it loses the reason — the worker boundary included. Checking the\n * whole resolved input here, at any depth, is what guarantees that no route\n * through resolution can hand a piece the wrapper as data: the path checks\n * inside `lookupPath` catch the ways an expression reaches one, and this\n * catches whatever they do not.\n */\nexport function resolveStepInput(\n step: StepInputSource,\n scope: ExpressionScope,\n): unknown {\n const input = resolveStepInputRaw(step, scope);\n assertNoUnavailableValue(input);\n return input;\n}\n\n// An existence test asks whether its operand names anything, so a reference\n// that resolves to nothing is its answer rather than an error.\nfunction resolveStepInputRaw(\n step: StepInputSource,\n scope: ExpressionScope,\n): unknown {\n const { config } = step;\n if (\n step.pieceName !== CORE_PIECE_NAME ||\n step.actionName !== \"branch\" ||\n config === null ||\n typeof config !== \"object\" ||\n Array.isArray(config) ||\n !Object.hasOwn(config, \"left\")\n ) {\n return resolveExpressions(config, scope);\n }\n const record = config as Record<string, unknown>;\n const operator = resolveExpressions(record.operator, scope);\n if (typeof operator !== \"string\" || !EXISTENCE_OPERATORS.has(operator)) {\n return resolveExpressions(config, scope);\n }\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [\n key,\n key === \"left\"\n ? resolveOrMissing(value, scope)\n : resolveExpressions(value, scope),\n ]),\n );\n}\n\nfunction resolveOrMissing(value: unknown, scope: ExpressionScope): unknown {\n try {\n return resolveExpressions(value, scope);\n } catch (error) {\n if (error instanceof UnresolvedReferenceError) return undefined;\n throw error;\n }\n}\n","// Resolves connection references into the auth value a piece reads from\n// ctx.auth, shaped per Activepieces auth kind (powerhouse/connection state).\n\nimport type { SecretProvider } from \"./secrets.js\";\nimport type { WorkflowDefinition } from \"./types.js\";\nimport {\n AppConnectionType,\n type AppConnectionValue,\n type BasicAuthConnectionValue,\n type OAuth2ConnectionValueWithApp,\n} from \"@powerhousedao/pieces-framework\";\n\n// The powerhouse/connection document model's own enum: the framework's\n// AppConnectionType, minus its hosted OAuth2 variants, with NO_AUTH as NONE.\nexport type ConnectionAuthType =\n | `${AppConnectionType.SECRET_TEXT}`\n | `${AppConnectionType.BASIC_AUTH}`\n | `${AppConnectionType.CUSTOM_AUTH}`\n | `${AppConnectionType.OAUTH2}`\n | `${AppConnectionType.OIDC}`\n | \"NONE\";\n\n// Mirrors the powerhouse/connection document state the resolver consumes.\nexport interface ConnectionSource {\n authType: ConnectionAuthType;\n config?: Record<string, unknown>;\n secretRefs?: { name: string; ref: string }[];\n}\n\n// Which step is asking. A resolver needs it to check the request against the\n// run's binding rather than trust the id it was handed.\n\n// piecePackage is the piece the caller resolved the block to.\nexport interface ConnectionRequest {\n piecePackage?: string;\n stepId?: string;\n stepKey?: string;\n}\n\n// The auth a piece reads, plus the concrete secret strings behind it. The\n// second half is what value-based journal redaction matches on.\nexport interface ResolvedConnection {\n auth: unknown;\n secretValues: string[];\n}\n\nexport interface EngineConnectionResolver {\n resolve(connectionId: string, request?: ConnectionRequest): Promise<unknown>;\n // Optional: hosts that predate redaction keep working without it. It takes\n // the same request, so authorization is not skipped to get the secrets.\n resolveWithSecrets?(\n connectionId: string,\n request?: ConnectionRequest,\n ): Promise<ResolvedConnection>;\n}\n\nexport class ConnectionNotFoundError extends Error {\n constructor(connectionId: string) {\n super(`No connection registered for id \"${connectionId}\"`);\n this.name = \"ConnectionNotFoundError\";\n }\n}\n\n// A step reached for a connection its workflow definition never declared.\n// Raised before any lookup, so it cannot say whether the id exists.\nexport class ConnectionNotBoundError extends Error {\n constructor(connectionId: string) {\n super(`Connection \"${connectionId}\" is not bound to this workflow`);\n this.name = \"ConnectionNotBoundError\";\n }\n}\n\nexport class UnsupportedAuthTypeError extends Error {\n constructor(authType: string) {\n super(`Auth type \"${authType}\" is not supported yet`);\n this.name = \"UnsupportedAuthTypeError\";\n }\n}\n\nasync function resolveSecrets(\n source: ConnectionSource,\n secrets: SecretProvider,\n): Promise<Record<string, string>> {\n const entries = await Promise.all(\n (source.secretRefs ?? []).map(\n async ({ name, ref }) => [name, await secrets.get(ref)] as const,\n ),\n );\n return Object.fromEntries(entries);\n}\n\n// Values are AppConnectionValue-shaped: pieces read auth.secret_text,\n// auth.username/password or auth.props.* depending on their auth kind.\nexport async function shapeAuthValue(\n source: ConnectionSource,\n secrets: SecretProvider,\n): Promise<unknown> {\n return (await shapeConnection(source, secrets)).auth;\n}\n\n// Only the values behind `secretRefs` are reported as secret: config fields\n// (a base URL, a username) are not, and redacting them would cost debuggability.\nexport async function shapeConnection(\n source: ConnectionSource,\n secrets: SecretProvider,\n): Promise<ResolvedConnection> {\n const resolved = await resolveSecrets(source, secrets);\n if (source.authType === \"OAUTH2\") return shapeOAuth2(source, resolved);\n return {\n auth: shapeAuth(source, resolved),\n secretValues: Object.values(resolved),\n };\n}\n\n// OAUTH2 keeps client_id in config and client_secret plus the host-written\n// token set (JSON) in secretRefs; the rest are the method's own props.\nfunction shapeOAuth2(\n source: ConnectionSource,\n resolved: Record<string, string>,\n): ResolvedConnection {\n const { client_secret: clientSecret, token, ...secretProps } = resolved;\n const { client_id: clientId, ...configProps } = source.config ?? {};\n if (!token) {\n throw new Error(\n \"This OAuth2 connection is not signed in; connect it first\",\n );\n }\n let tokens: Record<string, unknown>;\n try {\n tokens = JSON.parse(token) as Record<string, unknown>;\n } catch {\n throw new Error(\"Stored OAuth2 token is malformed; reconnect\");\n }\n const text = (value: unknown, fallback = \"\") =>\n typeof value === \"string\" ? value : fallback;\n const auth: OAuth2ConnectionValueWithApp = {\n type: AppConnectionType.OAUTH2,\n client_id: text(clientId),\n client_secret: text(clientSecret),\n redirect_url: text(tokens.redirect_url),\n access_token: text(tokens.access_token),\n refresh_token: text(tokens.refresh_token),\n token_type: text(tokens.token_type, \"Bearer\"),\n claimed_at: Number(tokens.claimed_at ?? 0),\n scope: text(tokens.scope),\n token_url: text(tokens.token_url),\n ...(typeof tokens.expires_in === \"number\"\n ? { expires_in: tokens.expires_in }\n : {}),\n data: (tokens.data ?? {}) as Record<string, unknown>,\n props: { ...configProps, ...secretProps },\n };\n // The token blob itself is never what a piece prints; its parts are.\n const secretValues = [\n clientSecret,\n auth.access_token,\n auth.refresh_token,\n ...Object.values(secretProps),\n ...tokenLikeValues(auth.data),\n ].filter((value): value is string => Boolean(value));\n return { auth, secretValues: [...new Set(secretValues)] };\n}\n\n// Keys naming a credential: id_token, authed_user.access_token, clientSecret.\n// Not every string: a scope or a team name would be blanked all over a log.\nconst TOKEN_KEY = /(token|secret)$/i;\n\nfunction tokenLikeValues(value: unknown, key = \"\"): string[] {\n if (typeof value === \"string\") return TOKEN_KEY.test(key) ? [value] : [];\n if (Array.isArray(value)) {\n return value.flatMap((item) => tokenLikeValues(item, key));\n }\n if (value !== null && typeof value === \"object\") {\n return Object.entries(value).flatMap(([name, item]) =>\n tokenLikeValues(item, name),\n );\n }\n return [];\n}\n\n// NONE is the persisted value; the framework's NO_AUTH case carries no value a\n// piece reads, so ctx.auth stays undefined rather than becoming that shape.\nfunction shapeAuth(\n source: ConnectionSource,\n resolved: Record<string, string>,\n): AppConnectionValue | undefined {\n switch (source.authType) {\n case \"NONE\":\n return undefined;\n case \"SECRET_TEXT\": {\n const values = Object.values(resolved);\n if (values.length !== 1) {\n throw new Error(\n `SECRET_TEXT connection must have exactly one secret ref, got ${values.length}`,\n );\n }\n return { type: AppConnectionType.SECRET_TEXT, secret_text: values[0] };\n }\n case \"BASIC_AUTH\": {\n const props = { ...source.config, ...resolved };\n return {\n type: AppConnectionType.BASIC_AUTH,\n username: props.username,\n password: props.password,\n } as BasicAuthConnectionValue;\n }\n case \"CUSTOM_AUTH\": {\n return {\n type: AppConnectionType.CUSTOM_AUTH,\n props: { ...source.config, ...resolved },\n };\n }\n default:\n throw new UnsupportedAuthTypeError(source.authType);\n }\n}\n\nexport class StaticConnectionResolver implements EngineConnectionResolver {\n private readonly connections: Map<string, ConnectionSource>;\n\n constructor(\n connections: Record<string, ConnectionSource>,\n private readonly secrets: SecretProvider,\n ) {\n this.connections = new Map(Object.entries(connections));\n }\n\n resolve(connectionId: string): Promise<unknown> {\n return this.resolveWithSecrets(connectionId).then(\n (resolved) => resolved.auth,\n );\n }\n\n resolveWithSecrets(connectionId: string): Promise<ResolvedConnection> {\n const source = this.connections.get(connectionId);\n if (!source) {\n return Promise.reject(new ConnectionNotFoundError(connectionId));\n }\n return shapeConnection(source, this.secrets);\n }\n}\n\n// Every connection a definition declares: the trigger's and each step's.\n\n// A templated id is left out — connectionId is never expression-resolved, so\n// it names no connection and a step cannot pick credentials at run time.\nexport function declaredConnectionIds(\n definition: WorkflowDefinition,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n const declare = (connectionId: string | null | undefined) => {\n if (connectionId && !connectionId.includes(\"{{\"))\n declared.add(connectionId);\n };\n declare(definition.trigger?.connectionId);\n for (const step of definition.steps) declare(step.connectionId);\n return declared;\n}\n\n// Every REACTOR connection a definition binds, kept apart from the auth\n// connections so neither resolves as the other.\nexport function declaredReactorConnectionIds(\n definition: WorkflowDefinition,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n const declare = (connectionId: string | null | undefined) => {\n if (connectionId && !connectionId.includes(\"{{\"))\n declared.add(connectionId);\n };\n declare(definition.trigger?.reactorConnectionId);\n for (const step of definition.steps) declare(step.reactorConnectionId);\n return declared;\n}\n\n// The binding in force for the caller, or undefined when there is none. Read\n// per call because one executor serves every concurrent run.\nexport type ConnectionBindingLookup = () => ReadonlySet<string> | undefined;\n\n// Server-side connection binding (doc 08 §10): a step resolves only what the\n// definition its run pinned declared.\n\n// Without a binding nothing resolves, so a path that fails to establish one\n// fails closed.\nexport class BoundConnectionResolver implements EngineConnectionResolver {\n // Present only when the inner resolver has it, because its absence is what\n // tells a caller to fall back to guessing the secrets from the auth value.\n readonly resolveWithSecrets?: (\n connectionId: string,\n request?: ConnectionRequest,\n ) => Promise<ResolvedConnection>;\n\n constructor(\n private readonly inner: EngineConnectionResolver,\n private readonly binding: ConnectionBindingLookup,\n private readonly onRefused?: (\n connectionId: string,\n request?: ConnectionRequest,\n ) => void,\n ) {\n const withSecrets = inner.resolveWithSecrets?.bind(inner);\n if (!withSecrets) return;\n this.resolveWithSecrets = (connectionId, request) =>\n this.bound(connectionId, request)\n ? withSecrets(connectionId, request)\n : Promise.reject(new ConnectionNotBoundError(connectionId));\n }\n\n resolve(connectionId: string, request?: ConnectionRequest): Promise<unknown> {\n if (!this.bound(connectionId, request)) {\n return Promise.reject(new ConnectionNotBoundError(connectionId));\n }\n return this.inner.resolve(connectionId, request);\n }\n\n // Both paths ask the same question, so neither is a way around it.\n private bound(connectionId: string, request?: ConnectionRequest): boolean {\n if (this.binding()?.has(connectionId)) return true;\n this.onRefused?.(connectionId, request);\n return false;\n }\n}\n","// Content-addressed copies of downloaded attachments. A ref names its bytes,\n// so a cached file never goes stale; steps get a clone, never the cache file.\nimport { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport {\n copyFile,\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n utimes,\n writeFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport interface CachedAttachmentMeta {\n fileName?: string;\n contentType?: string;\n size: number;\n}\n\nexport interface AttachmentCacheOptions {\n dir: string;\n // Total bytes kept; the least recently used entries go first.\n maxBytes: number;\n}\n\nconst META = \".json\";\n\nexport class AttachmentCache {\n constructor(private readonly options: AttachmentCacheOptions) {}\n\n private entry(ref: string): string {\n // attachment://v1:<sha256> -> v1-<sha256>; anything else is not cacheable.\n const match = /^attachment:\\/\\/(v\\d+):([a-f0-9]{64})$/i.exec(ref);\n if (!match) throw new Error(`Not a content-addressed reference: ${ref}`);\n return path.join(this.options.dir, `${match[1]}-${match[2].toLowerCase()}`);\n }\n\n static cacheable(ref: string): boolean {\n return /^attachment:\\/\\/v\\d+:[a-f0-9]{64}$/i.test(ref);\n }\n\n // Copies a cached ref to destPath, or returns undefined on a miss.\n async get(\n ref: string,\n destPath: string,\n ): Promise<CachedAttachmentMeta | undefined> {\n const file = this.entry(ref);\n let meta: CachedAttachmentMeta;\n try {\n meta = JSON.parse(\n await readFile(file + META, \"utf8\"),\n ) as CachedAttachmentMeta;\n // A file whose size no longer matches was tampered with or torn.\n if ((await stat(file)).size !== meta.size) {\n await this.remove(file);\n return undefined;\n }\n } catch {\n return undefined;\n }\n // A clone where the filesystem has one: a piece writing to its copy never\n // reaches the cache.\n await copyFile(file, destPath, constants.COPYFILE_FICLONE);\n const now = new Date();\n await utimes(file, now, now).catch(() => undefined);\n return meta;\n }\n\n // Adopts a file just downloaded to srcPath, leaving srcPath in place.\n async put(\n ref: string,\n srcPath: string,\n meta: Omit<CachedAttachmentMeta, \"size\">,\n ): Promise<void> {\n if (this.options.maxBytes <= 0) return;\n const file = this.entry(ref);\n const size = (await stat(srcPath)).size;\n if (size > this.options.maxBytes) return;\n await mkdir(this.options.dir, { recursive: true });\n const tmp = `${file}.${randomUUID()}.tmp`;\n try {\n await copyFile(srcPath, tmp, constants.COPYFILE_FICLONE);\n await writeFile(file + META, JSON.stringify({ ...meta, size }));\n // Rename last: a reader never sees a file without its metadata.\n await rename(tmp, file);\n } catch (error) {\n await rm(tmp, { force: true });\n throw error;\n }\n await this.evict();\n }\n\n private async remove(file: string): Promise<void> {\n await rm(file, { force: true });\n await rm(file + META, { force: true });\n }\n\n private async evict(): Promise<void> {\n const names = await readdir(this.options.dir).catch(() => [] as string[]);\n const entries = await Promise.all(\n names\n .filter((name) => !name.endsWith(META) && !name.endsWith(\".tmp\"))\n .map(async (name) => {\n const file = path.join(this.options.dir, name);\n const info = await stat(file).catch(() => undefined);\n return info\n ? { file, size: info.size, used: info.mtimeMs }\n : undefined;\n }),\n );\n const live = entries\n .filter((e) => e !== undefined)\n .sort((a, b) => b.used - a.used);\n let total = 0;\n for (const entry of live) {\n total += entry.size;\n if (total > this.options.maxBytes) await this.remove(entry.file);\n }\n }\n}\n","// What the core piece declares beyond Activepieces' metadata. The descriptor\n// builder copies these; the in-process executor routes by `portOf`.\n\nexport interface PropHints {\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport function withHints<P extends object>(property: P, hints: PropHints): P {\n return { ...property, ...hints };\n}\n\nexport const shownWhen = (prop: string, oneOf: unknown[]): PropHints => ({\n showWhen: { prop, oneOf },\n});\n\nexport interface PortedAction {\n ports: readonly string[];\n // The port a successful result leaves on.\n portOf: (output: unknown) => string;\n}\n\nexport function withPorts<A extends object>(\n action: A,\n ported: PortedAction,\n): A & PortedAction {\n return Object.assign(action, ported);\n}\n\nexport function isPorted(action: unknown): action is PortedAction {\n const candidate = action as Partial<PortedAction> | null;\n return (\n typeof candidate?.portOf === \"function\" && Array.isArray(candidate.ports)\n );\n}\n\n// A form the editor draws instead of the trigger's props, e.g. \"schedule\".\nexport function withDisplay<T extends object>(\n trigger: T,\n display: string,\n): T & { display: string } {\n return Object.assign(trigger, { display });\n}\n","import { createAction, Property } from \"@powerhousedao/pieces-framework\";\nimport {\n BRANCH_PORTS,\n NEXT_PORT,\n PIECE_ACTION_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n BRANCH_OPERATORS,\n DEFAULT_BRANCH_OPERATOR,\n evaluateBranch,\n type BranchOutcome,\n} from \"./branch-operators.js\";\nimport { shownWhen, withHints, withPorts } from \"./hints.js\";\n\nconst operators = Object.entries(BRANCH_OPERATORS);\nconst BINARY_OPERATORS = operators\n .filter(([, spec]) => spec.binary)\n .map(([name]) => name);\nconst TEXT_OPERATORS = operators\n .filter(([, spec]) => spec.text)\n .map(([name]) => name);\n\nexport const branchAction = withPorts(\n createAction({\n name: \"branch\",\n displayName: \"Branch\",\n description:\n \"Takes the true port when the operator holds for its operands, else the \" +\n \"false port. An operand of the wrong type (a number operator on text, a \" +\n \"list operator on something that is not a list) fails the step.\",\n requireAuth: false,\n props: {\n left: Property.ShortText({\n displayName: \"Value\",\n description: \"What to test, usually an expression.\",\n required: true,\n placeholder: \"{{steps.fetch.output.status}}\",\n }),\n operator: Property.StaticDropdown({\n displayName: \"Condition\",\n description: \"How the value is tested.\",\n required: true,\n defaultValue: DEFAULT_BRANCH_OPERATOR,\n options: {\n options: operators.map(([value, spec]) => ({\n value,\n label: spec.label,\n })),\n },\n }),\n right: withHints(\n Property.ShortText({\n displayName: \"Compared with\",\n description: \"The value the condition compares to.\",\n required: true,\n }),\n shownWhen(\"operator\", BINARY_OPERATORS),\n ),\n caseSensitive: withHints(\n Property.Checkbox({\n displayName: \"Case sensitive\",\n description: \"Match letter case exactly.\",\n required: false,\n }),\n shownWhen(\"operator\", TEXT_OPERATORS),\n ),\n },\n run: (ctx) => Promise.resolve(evaluateBranch(ctx.propsValue)),\n }),\n {\n ports: BRANCH_PORTS,\n portOf: (output) => ((output as BranchOutcome).result ? \"true\" : \"false\"),\n },\n);\n\nfunction assertionText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null) return \"\";\n return JSON.stringify(value);\n}\n\nfunction normalizedList(entries: unknown): string[] {\n const list =\n typeof entries === \"string\"\n ? [entries]\n : Array.isArray(entries)\n ? entries\n : [];\n return list\n .map((entry) => String(entry).trim().toLowerCase())\n .filter(Boolean);\n}\n\n// Model output is the motivating case: an empty completion, or a classifier\n// answering the wrong question, must not flow on to a step with a side effect.\nexport const assertAction = withPorts(\n createAction({\n name: \"assert\",\n displayName: \"Assert\",\n description:\n \"Fails the step when its value is blank or rejected, so a bad value stops \" +\n \"the run instead of reaching a step with a side effect.\",\n requireAuth: false,\n props: {\n value: Property.ShortText({\n displayName: \"Value\",\n description:\n \"e.g. {{steps.describe.output}} - the run fails when it is blank.\",\n required: true,\n }),\n rejectValues: Property.Array({\n displayName: \"Rejected values\",\n description:\n \"One per line; the run fails when the value matches any of them.\",\n required: false,\n }),\n allowValues: Property.Array({\n displayName: \"Allowed values\",\n description:\n \"One per line; when set, anything else fails. Safer than a reject list for model output.\",\n required: false,\n }),\n allowEmpty: Property.Checkbox({\n displayName: \"Allow empty\",\n description: \"Accept a blank value instead of failing.\",\n required: false,\n }),\n message: Property.ShortText({\n displayName: \"Failure message\",\n description: \"Replaces the default error.\",\n required: false,\n }),\n },\n run: (ctx) => {\n const { value, rejectValues, allowValues, allowEmpty, message } =\n ctx.propsValue as Record<string, unknown>;\n const trimmed = assertionText(value).trim();\n const fail = (reason: string) =>\n Promise.reject(\n new Error(\n typeof message === \"string\" && message\n ? message\n : `Assert: ${reason}`,\n ),\n );\n if (!trimmed && allowEmpty !== true) return fail(\"value is empty\");\n if (normalizedList(rejectValues).includes(trimmed.toLowerCase())) {\n return fail(`value is a rejected value (\"${trimmed}\")`);\n }\n // An allow-list is the safer gate for model output: anything unforeseen\n // fails here rather than reaching a step that writes.\n const allowed = normalizedList(allowValues);\n if (allowed.length > 0 && !allowed.includes(trimmed.toLowerCase())) {\n return fail(\n `value \"${trimmed}\" is not one of the allowed values (${allowed.join(\", \")})`,\n );\n }\n return Promise.resolve({ value });\n },\n }),\n { ports: PIECE_ACTION_PORTS, portOf: () => NEXT_PORT },\n);\n","// The core triggers. The host feeds them, the way the reactor piece's document\n// triggers are fed: schedule.ts, webhook.ts and the manual fire mutation.\nimport {\n createTrigger,\n Property,\n TriggerStrategy,\n} from \"@powerhousedao/pieces-framework\";\nimport {\n SCHEDULE_MODES,\n SCHEDULE_UNIT_MS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport { shownWhen, withDisplay, withHints } from \"./hints.js\";\n\n// A hook that runs would mean the host stopped feeding this trigger.\nfunction hostFed(name: string): () => Promise<never> {\n return () =>\n Promise.reject(\n new Error(`The \"${name}\" trigger is fired by the host, not by its hooks`),\n );\n}\n\nconst hooks = (name: string) => ({\n onEnable: hostFed(name),\n onDisable: hostFed(name),\n run: hostFed(name),\n});\n\nconst options = (entries: [value: string, label: string][]) => ({\n options: entries.map(([value, label]) => ({ value, label })),\n});\n\nexport const scheduleTrigger = withDisplay(\n createTrigger({\n name: \"schedule\",\n displayName: \"Schedule\",\n description:\n \"Fires on a five-field cron expression, or every so many minutes, hours or days.\",\n type: TriggerStrategy.POLLING,\n requireAuth: false,\n props: {\n mode: Property.StaticDropdown({\n displayName: \"Runs\",\n description: \"cron or interval.\",\n required: true,\n defaultValue: \"cron\",\n options: options([\n [SCHEDULE_MODES[0], \"On a cron schedule\"],\n [SCHEDULE_MODES[1], \"At a fixed interval\"],\n ]),\n }),\n cron: withHints(\n Property.ShortText({\n displayName: \"Cron expression\",\n description:\n \"Five fields, e.g. 0 9 * * 1-5 runs at 09:00 on weekdays.\",\n required: true,\n defaultValue: \"0 9 * * 1-5\",\n }),\n shownWhen(\"mode\", [\"cron\"]),\n ),\n every: withHints(\n Property.Number({\n displayName: \"Every\",\n description: \"A whole number of units, at least 1.\",\n required: true,\n defaultValue: 15,\n }),\n shownWhen(\"mode\", [\"interval\"]),\n ),\n unit: withHints(\n Property.StaticDropdown({\n displayName: \"Unit\",\n description: \"minutes, hours or days.\",\n required: true,\n defaultValue: \"minutes\",\n options: {\n options: Object.keys(SCHEDULE_UNIT_MS).map((unit) => ({\n value: unit,\n label: unit.charAt(0).toUpperCase() + unit.slice(1),\n })),\n },\n }),\n shownWhen(\"mode\", [\"interval\"]),\n ),\n timezone: Property.ShortText({\n displayName: \"Timezone\",\n description: \"An IANA name such as Europe/Lisbon. Defaults to UTC.\",\n required: false,\n defaultValue: \"UTC\",\n }),\n },\n sampleData: {\n scheduledFor: \"2026-09-28T09:00:00.000Z\",\n firedAt: \"2026-09-28T09:00:00.120Z\",\n timezone: \"UTC\",\n cron: \"0 9 * * 1-5\",\n },\n ...hooks(\"schedule\"),\n }),\n \"schedule\",\n);\n\n// Every scheme that verifies a signature, and so needs a secret.\nconst SIGNED_SCHEMES = [\"token\", \"hmac\", \"hmac-prefixed\", \"hmac-timestamped\"];\n\n// Schemes that compute a digest, and so take a hash and an encoding.\nconst HMAC_SCHEMES = [\"hmac\", \"hmac-prefixed\", \"hmac-timestamped\"];\n\n// A managed secret's ref, drawn as a secret picker rather than a text field.\nconst SECRET_REF_TYPE = \"PH_SECRET_REF\";\n\nexport const webhookTrigger = createTrigger({\n name: \"webhook\",\n displayName: \"Webhook\",\n description:\n \"Fires on an HTTP delivery to the workflow's endpoint. Ask for the URL \" +\n \"with the webhookEndpoint query rather than constructing it.\",\n type: TriggerStrategy.WEBHOOK,\n requireAuth: false,\n props: {\n methods: Property.StaticDropdown({\n displayName: \"Method\",\n description: \"The HTTP method a delivery must use.\",\n required: true,\n defaultValue: \"POST\",\n options: options([\n [\"POST\", \"POST\"],\n [\"ANY\", \"Any\"],\n [\"GET\", \"GET\"],\n [\"PUT\", \"PUT\"],\n [\"PATCH\", \"PATCH\"],\n [\"DELETE\", \"DELETE\"],\n ]),\n }),\n // Named by wire format, not by sender: one brand name would mislead.\n scheme: Property.StaticDropdown({\n displayName: \"Verification\",\n description: \"How a delivery proves its sender.\",\n required: true,\n defaultValue: \"none\",\n options: options([\n [\"none\", \"None — the URL's token only\"],\n [\"token\", \"Shared token in a header\"],\n [\"hmac\", \"HMAC digest\"],\n [\"hmac-prefixed\", \"HMAC digest with a label (sha256=…)\"],\n [\"hmac-timestamped\", \"HMAC digest, timestamped (t=…,v1=…)\"],\n ]),\n }),\n // Hidden while unverified: a secret there would never be checked.\n secretRef: withHints(\n {\n ...Property.ShortText({\n displayName: \"Secret\",\n description:\n \"The shared secret: the value the header must equal, or the key the sender signs with\",\n required: true,\n }),\n type: SECRET_REF_TYPE as never,\n },\n shownWhen(\"scheme\", SIGNED_SCHEMES),\n ),\n header: withHints(\n Property.ShortText({\n displayName: \"Header\",\n description:\n \"Where the token or signature is read from. Defaults to the header the chosen scheme conventionally uses; set it only if the sender differs\",\n required: false,\n advanced: true,\n }),\n shownWhen(\"scheme\", SIGNED_SCHEMES),\n ),\n toleranceSeconds: withHints(\n Property.Number({\n displayName: \"Replay window (seconds)\",\n description:\n \"Rejects a delivery signed longer ago than this, so a captured request expires. Default 300\",\n required: false,\n advanced: true,\n }),\n shownWhen(\"scheme\", [\"hmac-timestamped\"]),\n ),\n algorithm: withHints(\n Property.StaticDropdown({\n displayName: \"Hash\",\n description: \"How the digest was computed.\",\n required: false,\n advanced: true,\n options: options([\n [\"sha256\", \"SHA-256 (default)\"],\n [\"sha1\", \"SHA-1\"],\n [\"sha512\", \"SHA-512\"],\n ]),\n }),\n shownWhen(\"scheme\", HMAC_SCHEMES),\n ),\n encoding: withHints(\n Property.StaticDropdown({\n displayName: \"Digest encoding\",\n description: \"How the digest is written.\",\n required: false,\n advanced: true,\n options: options([\n [\"hex\", \"Hexadecimal (default)\"],\n [\"base64\", \"Base64\"],\n ]),\n }),\n shownWhen(\"scheme\", HMAC_SCHEMES),\n ),\n prefix: withHints(\n Property.ShortText({\n displayName: \"Signature label\",\n description:\n \"The text before the digest. Left empty it is the hash name and an equals sign, e.g. sha256=. Tick No label when the sender sends the digest alone\",\n required: false,\n advanced: true,\n }),\n { emptyChoice: \"No label\", ...shownWhen(\"scheme\", [\"hmac-prefixed\"]) },\n ),\n dedupeField: Property.ShortText({\n displayName: \"Event id field\",\n description:\n \"Where the sender puts its own event id, so a redelivery is accepted without a second run. A bare name reads a query param or a top-level body field; prefix with header: or body: to read a header or a nested path (header:x-delivery-id, body:data.object.id)\",\n required: false,\n advanced: true,\n }),\n dedupeTtlSeconds: Property.Number({\n displayName: \"Dedupe window (seconds)\",\n description: \"How long an event id is remembered. Default 300\",\n required: false,\n advanced: true,\n }),\n challengeField: Property.ShortText({\n displayName: \"Challenge field\",\n description:\n \"Echo this field back instead of running, for senders that verify the endpoint before registering it. Same header:/body: prefixes as the event id field\",\n required: false,\n advanced: true,\n }),\n responseMode: Property.StaticDropdown({\n displayName: \"Response\",\n description: \"Waiting holds the sender's socket open for the whole run\",\n required: false,\n advanced: true,\n defaultValue: \"async\",\n options: options([\n [\"async\", \"Answer immediately (202)\"],\n [\"sync\", \"Wait for the run (200)\"],\n ]),\n }),\n responseStatus: Property.Number({\n displayName: \"Success status\",\n description: \"Status returned on acceptance. Default 202 async, 200 sync\",\n required: false,\n advanced: true,\n }),\n },\n sampleData: {\n method: \"POST\",\n path: \"/\",\n headers: { \"content-type\": \"application/json\" },\n queryParams: {},\n body: { event: \"ping\" },\n },\n ...hooks(\"webhook\"),\n});\n\nexport const manualTrigger = createTrigger({\n name: \"manual\",\n displayName: \"Manual\",\n description:\n \"Fires only when something asks it to, with the fire mutation. The trigger \" +\n \"to use for a workflow driven by a test or a script.\",\n type: TriggerStrategy.MANUAL,\n requireAuth: false,\n props: {},\n sampleData: null,\n ...hooks(\"manual\"),\n});\n","","// The core piece ships with the runtime, so it carries the runtime's version.\nimport pkg from \"../../../package.json\" with { type: \"json\" };\n\nexport const CORE_PIECE_VERSION: string = pkg.version;\n","// The built-in core piece: branching, assertions, and the triggers that belong\n// to no service. The runtime registers it itself and always runs this copy.\nimport { createPiece, PieceCategory } from \"@powerhousedao/pieces-framework\";\nimport { CORE_PIECE_NAME } from \"@powerhousedao/pieces-framework/workflow\";\nimport { assertAction, branchAction } from \"./actions.js\";\nimport { manualTrigger, scheduleTrigger, webhookTrigger } from \"./triggers.js\";\nimport { CORE_PIECE_VERSION } from \"./version.js\";\n\nexport { CORE_PIECE_NAME, CORE_PIECE_VERSION };\nexport * from \"./branch-operators.js\";\nexport { isPorted, type PortedAction, type PropHints } from \"./hints.js\";\n\nexport const corePiece = createPiece({\n displayName: \"Core\",\n description:\n \"The engine's own blocks: branching, assertions, and the triggers that \" +\n \"belong to no service.\",\n logoUrl: \"\",\n authors: [\"powerhouse\"],\n auth: undefined,\n categories: [PieceCategory.CORE],\n actions: [branchAction, assertAction],\n triggers: [scheduleTrigger, webhookTrigger, manualTrigger],\n});\n","// Pieces the runtime ships and registers itself. They are this package's own\n// code, so they are described and run in process rather than in the worker.\nimport type { BlockIdentity } from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport type { LocalPiece } from \"./activepieces/resolver.js\";\nimport {\n buildDescriptor,\n type PieceDescriptor,\n} from \"./activepieces/descriptor.js\";\nimport { getActions, type ApPiece } from \"./activepieces/types.js\";\nimport {\n CORE_PIECE_NAME,\n CORE_PIECE_VERSION,\n corePiece,\n isPorted,\n} from \"./core/index.js\";\n\nexport interface BuiltinPiece {\n name: string;\n version: string;\n piece: ApPiece;\n}\n\nconst BUILTIN_PIECES: readonly BuiltinPiece[] = [\n {\n name: CORE_PIECE_NAME,\n version: CORE_PIECE_VERSION,\n piece: corePiece as unknown as ApPiece,\n },\n];\n\nexport function builtinPiece(name: string): BuiltinPiece | undefined {\n return BUILTIN_PIECES.find((entry) => entry.name === name);\n}\n\nexport function isBuiltinPiece(name: string): boolean {\n return builtinPiece(name) !== undefined;\n}\n\n// As the resolver sees it: installed, with nothing on disk to load.\nexport function builtinLocalPieces(): LocalPiece[] {\n return BUILTIN_PIECES.map(({ name, version }) => ({ name, version }));\n}\n\nconst descriptors = new Map<string, PieceDescriptor>();\n\nexport function describeBuiltinPiece(builtin: BuiltinPiece): PieceDescriptor {\n let descriptor = descriptors.get(builtin.name);\n if (!descriptor) {\n descriptor = buildDescriptor(\n builtin.piece,\n { packageName: builtin.name, version: builtin.version },\n { routed: true, hostFed: true },\n );\n descriptors.set(builtin.name, descriptor);\n }\n return descriptor;\n}\n\n// What a block's edges may leave on: a built-in block's own list, else the\n// ports every piece action or trigger declares.\nexport function blockPorts(\n block: BlockIdentity,\n): readonly string[] | undefined {\n const builtin = builtinPiece(block.pieceName);\n if (builtin) {\n const descriptor = describeBuiltinPiece(builtin);\n const entries: { name: string; ports: readonly string[] }[] =\n block.kind === \"trigger\" ? descriptor.triggers : descriptor.actions;\n return entries.find((entry) => entry.name === block.name)?.ports;\n }\n return block.kind === \"trigger\" ? TRIGGER_PORTS : PIECE_ACTION_PORTS;\n}\n\nexport class UnknownBuiltinActionError extends Error {\n constructor(piece: string, action: string) {\n super(`${piece} has no action \"${action}\"`);\n this.name = \"UnknownBuiltinActionError\";\n }\n}\n\n// Only propsValue is served: a built-in action reaches nothing else.\nexport async function runBuiltinAction(\n builtin: BuiltinPiece,\n actionName: string,\n propsValue: Record<string, unknown>,\n): Promise<{ output: unknown; port?: string }> {\n const action = getActions(builtin.piece)[actionName] as unknown;\n if (!action || typeof (action as { run?: unknown }).run !== \"function\") {\n throw new UnknownBuiltinActionError(builtin.name, actionName);\n }\n const output = await (\n action as { run: (ctx: unknown) => Promise<unknown> }\n ).run({ propsValue });\n return {\n output,\n ...(isPorted(action) ? { port: action.portOf(output) } : {}),\n };\n}\n","// What a block resolved to: the piece version that runs and where it came\n// from. A version mismatch never fails; only `missing` does.\nimport type {\n BlockIdentity,\n BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\n\nexport type PieceOrigin = \"local\" | \"registry\" | \"activepieces\" | \"npm\";\n\nexport type BlockMatch =\n | \"exact\"\n | \"compatible\"\n | \"fallback\"\n | \"installed\"\n | \"missing\";\n\nexport interface BlockResolution {\n requested: BlockRef;\n // No source: a caller outside a reactor, which tries every download source.\n resolved?: { version: string; source?: PieceOrigin };\n match: BlockMatch;\n // Human text for the badge; absent when the pin ran as written.\n note?: string;\n // Newest version any source offers, for \"update available\".\n latestVersion?: string;\n // Set when nothing resolved and a source could not be asked.\n unreachable?: string;\n}\n\n// What a step's journal row keeps of its resolution.\nexport interface StepPieceRecord {\n version: string;\n source?: PieceOrigin;\n match: BlockMatch;\n note?: string;\n}\n\nexport function pieceRecord(\n resolution: BlockResolution | undefined,\n): StepPieceRecord | undefined {\n if (!resolution?.resolved) return undefined;\n return {\n version: resolution.resolved.version,\n ...(resolution.resolved.source\n ? { source: resolution.resolved.source }\n : {}),\n match: resolution.match,\n ...(resolution.note ? { note: resolution.note } : {}),\n };\n}\n\n// How a block reads in a message: `@acme/piece-http@1.2.0 action \"send\"`.\nexport function blockLabel(block: BlockIdentity | BlockRef): string {\n const version = \"pieceVersion\" in block ? `@${block.pieceVersion}` : \"\";\n return `${block.pieceName}${version} ${block.kind} \"${block.name}\"`;\n}\n\nexport class UnknownBlockError extends Error {\n constructor(\n block: BlockIdentity | BlockRef,\n detail = `No executor registered for ${blockLabel(block)}`,\n ) {\n super(detail);\n this.name = \"UnknownBlockError\";\n }\n}\n\nexport function unpinnedNote(block: BlockRef): string {\n return `${block.pieceName} ${block.kind} \"${block.name}\" pins \"${block.pieceVersion}\", which is not an exact semver version`;\n}\n\n// The message a missing resolution fails with.\nexport function missingError(resolution: BlockResolution): Error {\n return new UnknownBlockError(resolution.requested, resolution.note);\n}\n\nconst RESOLUTION = Symbol.for(\"reactor-workflow.block-resolution\");\n\n// A failed step still journals what it resolved to.\nexport function withResolution<T>(\n error: T,\n resolution: BlockResolution | undefined,\n): T {\n if (resolution && error !== null && typeof error === \"object\") {\n (error as Record<symbol, unknown>)[RESOLUTION] = resolution;\n }\n return error;\n}\n\nexport function resolutionOf(error: unknown): BlockResolution | undefined {\n if (error === null || typeof error !== \"object\") return undefined;\n return (error as Record<symbol, BlockResolution | undefined>)[RESOLUTION];\n}\n","import {\n blockKey,\n isExactVersion,\n type BlockKind,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport { childLogger } from \"document-model\";\nimport { randomUUID } from \"node:crypto\";\nimport { lstat, mkdir, realpath, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n bundleResolver,\n pieceModuleRef,\n type PieceResolver,\n} from \"../activepieces/resolver.js\";\nimport type { ActionContextIdentity } from \"../activepieces/context/action.js\";\nimport { hostCallTimeoutForStep } from \"../activepieces/context/limits.js\";\nimport {\n rewriteFileRefs,\n type StagedFile,\n} from \"../activepieces/context/files.js\";\nimport {\n FileTooLargeError,\n maxFileBytes,\n} from \"../activepieces/context/limits.js\";\nimport { AttachmentCache } from \"./attachment-cache.js\";\nimport { PieceWorker, type IPieceWorker } from \"../activepieces/worker/host.js\";\nimport type { ReactorTap } from \"../activepieces/worker/reactor-rpc.js\";\nimport { DEFAULT_EGRESS_POLICY } from \"../activepieces/worker/egress.js\";\nimport {\n LOG_WRITE,\n OUTPUT_UPDATE,\n STORE_DELETE,\n STORE_GET,\n STORE_PUT,\n type EgressPolicy,\n type HostCallHandlers,\n type HostNotifyHandlers,\n type PieceLogEntry,\n type StagedInput,\n} from \"../activepieces/worker/protocol.js\";\nimport type { StoreScopeName } from \"../activepieces/context/store-scope.js\";\nimport {\n collectSecretValues,\n redactError,\n redactMessage,\n rememberSecrets,\n} from \"../activepieces/worker/redact.js\";\nimport type {\n ConnectionRequest,\n EngineConnectionResolver,\n ResolvedConnection,\n} from \"./connections.js\";\nimport type { BlockExecution, BlockExecutor, BlockResult } from \"./types.js\";\nimport type { WorkflowTelemetry } from \"../../telemetry.js\";\nimport { builtinPiece, isBuiltinPiece, runBuiltinAction } from \"../builtin.js\";\nimport {\n blockLabel,\n missingError,\n UnknownBlockError,\n unpinnedNote,\n withResolution,\n type BlockResolution,\n type PieceOrigin,\n} from \"./resolution.js\";\n\nexport { UnknownBlockError };\n\nexport class TriggerBlockAsStepError extends Error {\n constructor(block: BlockRef) {\n super(\n `${blockLabel(block)} is a trigger and cannot run as a workflow step`,\n );\n this.name = \"TriggerBlockAsStepError\";\n }\n}\n\n// The host's attachment store, as the engine needs it: materialize a\n// reference to a path the worker can read, and ingest a path the worker wrote.\n// Both directions go through the filesystem, so bytes never enter IPC.\nexport interface AttachmentPort {\n read(\n ref: string,\n destPath: string,\n signal?: AbortSignal,\n ): Promise<{ fileName?: string; contentType?: string }>;\n // Whether the running workflow may read the ref, without fetching it: a\n // cached copy is only handed over after the same check a download makes.\n authorize?(ref: string): Promise<void>;\n write(\n file: {\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n },\n signal?: AbortSignal,\n ): Promise<string>;\n}\n\nconst ATTACHMENT_REF = /^attachment:\\/\\//i;\n\n// Collects every attachment reference appearing as a string in a step config.\n// Deliberately type-agnostic: the worker decides which of them to hydrate\n// (only FILE props go through toApFile), so staging a reference no one reads\n// costs one file, while missing one would fail the step.\nfunction collectRefs(value: unknown, found: Set<string>): void {\n if (typeof value === \"string\") {\n if (ATTACHMENT_REF.test(value)) found.add(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectRefs(entry, found);\n return;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const entry of Object.values(value)) collectRefs(entry, found);\n }\n}\n\n// The durable `ctx.store`, as the engine needs it: one call per operation, so\n// a piece that checkpoints mid-loop keeps what it wrote if the step then dies.\n\n// Which scope a step's keys belong to is the host's business; the executor is\n// shared across runs and must not decide it.\nexport interface PieceStorePort {\n get(key: string, scope: StoreScopeName): Promise<unknown>;\n put(key: string, value: unknown, scope: StoreScopeName): Promise<void>;\n delete(key: string, scope: StoreScopeName): Promise<void>;\n}\n\n// One key operation as it arrives from the worker.\ninterface StoreCallPayload {\n key?: unknown;\n value?: unknown;\n scope?: unknown;\n}\n\n// An unrecognised scope is treated as FLOW, the narrower partition: a bad\n// name must never widen what a step can reach.\nfunction storeScopeOf(payload: unknown): StoreScopeName {\n const scope = (payload as StoreCallPayload | undefined)?.scope;\n return scope === \"PROJECT\" ? \"PROJECT\" : \"FLOW\";\n}\n\nfunction storeKeyOf(payload: unknown): string {\n const key = (payload as StoreCallPayload | undefined)?.key;\n if (typeof key !== \"string\" || key === \"\") {\n throw new Error(\"Store call carried no key\");\n }\n return key;\n}\n\n// The handlers served to a running step or trigger hook. A rejection becomes\n// the error the piece sees, which is what an over-limit write should do.\nexport function storeHandlers(port: PieceStorePort): HostCallHandlers {\n return {\n [STORE_GET]: (payload) =>\n port.get(storeKeyOf(payload), storeScopeOf(payload)),\n [STORE_PUT]: async (payload) => {\n await port.put(\n storeKeyOf(payload),\n (payload as StoreCallPayload).value,\n storeScopeOf(payload),\n );\n return null;\n },\n [STORE_DELETE]: async (payload) => {\n await port.delete(storeKeyOf(payload), storeScopeOf(payload));\n return null;\n },\n };\n}\n\nconst logger = childLogger([\"workflow\", \"piece-staging\"]);\n\nexport interface ActivepiecesBlockExecutorOptions {\n cacheDir: string;\n // Which piece version, from which source, runs a block. Without one a\n // block runs its pin, fetched from any download source.\n resolveBlock?: (block: BlockRef) => Promise<BlockResolution>;\n connections?: EngineConnectionResolver;\n // The worker piece steps go to. A function is asked once per step, so a\n // host handing each run its own child answers with that run's.\n worker?: IPieceWorker | (() => IPieceWorker | undefined);\n defaultTimeoutMs?: number;\n // Both are needed for ctx.files to work: a directory the host and the forked\n // worker share, and somewhere to put what the piece wrote. Without them a\n // piece calling ctx.files falls back to inline data URIs.\n stagingRoot?: string;\n attachments?: AttachmentPort;\n // Keeps downloaded attachments by content so later steps and runs skip the\n // download. Needs `attachments.authorize`.\n attachmentCache?: AttachmentCache;\n // Without it `ctx.store` falls back to the worker's heap, which a step\n // timeout discards.\n pieceStore?: PieceStorePort;\n // Where a block's piece comes from. Defaults to fetching the pinned\n // version into `cacheDir`, which is what a published piece needs.\n resolver?: PieceResolver;\n // ctx.reactor over the reactor RPC, for an action that declares requireReactor;\n // undefined when it declares none. Asked per step.\n reactorAccess?: (\n request: StepReactorRequest,\n ) => Promise<ReactorTap | undefined>;\n // Where a step's piece may connect to. Left unset it is the default policy,\n // which refuses private address space; `null` runs the piece unrestricted.\n egress?: EgressPolicy | null;\n // Taps on a running step. Each is opt-in because it costs the worker an IPC\n // message per event, and neither is asked for unless someone reads it.\n onPieceLog?: (entry: PieceLogEntry, execution: BlockExecution) => void;\n onPartialOutput?: (output: unknown, execution: BlockExecution) => void;\n // The run, workflow and project a step belongs to, asked per step: the\n // executor is shared across runs. The step name is the step's key.\n identity?: () => Omit<ActionContextIdentity, \"stepName\"> | undefined;\n // Whether this step runs as a single-step test, asked per step likewise.\n stepTest?: () => boolean;\n telemetry?: WorkflowTelemetry;\n}\n\nexport interface StepReactorRequest {\n block: ParsedBlockType;\n reactorConnectionId?: string | null;\n}\n\n// The notify handlers served to one step. Unlike a store call, nothing here\n// answers the piece: these are reports, and the step never waits on them.\nfunction stepTaps(\n options: ActivepiecesBlockExecutorOptions,\n execution: BlockExecution,\n values: string[],\n): HostNotifyHandlers | undefined {\n const { onPieceLog, onPartialOutput } = options;\n if (!onPieceLog && !onPartialOutput) return undefined;\n const handlers: HostNotifyHandlers = {};\n if (onPieceLog) {\n // A piece logging its own outgoing request is a common idiom, so this is\n // one of the likeliest places for a credential to reach the host log.\n handlers[LOG_WRITE] = (payload) => {\n const entry = payload as PieceLogEntry;\n // Returned, not discarded: a sink that rejects is the host's to catch.\n return onPieceLog(\n { ...entry, message: redactMessage(entry.message, { values }) },\n execution,\n );\n };\n }\n if (onPartialOutput) {\n handlers[OUTPUT_UPDATE] = (payload) => onPartialOutput(payload, execution);\n }\n return handlers;\n}\n\n// Mutated in place rather than rewrapped: callers classify on the error's\n// class, and a new one would lose that.\n\n// `stack` embeds the message as it was at construction, so a caller logging\n// the error object rather than `.message` would otherwise still print it.\nfunction redactThrown(error: unknown, values: string[]): unknown {\n if (error instanceof Error) {\n error.message = redactMessage(error.message, { values });\n if (error.stack) error.stack = redactMessage(error.stack, { values });\n return rememberSecrets(error, values);\n }\n return rememberSecrets(redactError(error, { values }), values);\n}\n\n// Shipped by the workflow package, which versions it with the host.\nconst HOST_SHIPPED_PIECE = \"@powerhousedao/piece-reactor\";\n\n// The host's own code, so it always runs the installed copy.\nexport function isHostBound(packageName: string): boolean {\n return packageName === HOST_SHIPPED_PIECE || isBuiltinPiece(packageName);\n}\n\nexport type { BlockKind };\n\n// A block's piece with the version and source it runs at.\nexport interface ParsedBlockType {\n packageName: string;\n version: string;\n source?: PieceOrigin;\n kind: BlockKind;\n // Action or trigger name within the piece.\n name: string;\n}\n\n// The piece a resolution runs; undefined for a missing one.\nexport function resolvedBlock(\n resolution: BlockResolution,\n): ParsedBlockType | undefined {\n const { requested, resolved } = resolution;\n if (!resolved || resolution.match === \"missing\") return undefined;\n return {\n packageName: requested.pieceName,\n version: resolved.version,\n ...(resolved.source ? { source: resolved.source } : {}),\n kind: requested.kind,\n name: requested.name,\n };\n}\n\n// Without a host policy a block runs exactly what it pins.\nexport function pinnedResolution(block: BlockRef): BlockResolution {\n if (!isExactVersion(block.pieceVersion)) {\n return { requested: block, match: \"missing\", note: unpinnedNote(block) };\n }\n return {\n requested: block,\n resolved: { version: block.pieceVersion },\n match: \"exact\",\n };\n}\n\n// Executes piece actions: a built-in piece in process, any other through the\n// piece worker.\nexport class ActivepiecesBlockExecutor implements BlockExecutor {\n // Only set when nothing was supplied: the fallback this executor owns and\n // must dispose. A supplied worker belongs to whoever supplied it.\n private own: PieceWorker | undefined;\n\n private readonly resolver: PieceResolver;\n\n constructor(private readonly options: ActivepiecesBlockExecutorOptions) {\n this.resolver =\n options.resolver ?? bundleResolver({ cacheDir: options.cacheDir });\n }\n\n private worker(): IPieceWorker {\n const supplied = this.options.worker;\n if (typeof supplied === \"function\") {\n const worker = supplied();\n if (worker) return worker;\n } else if (supplied) {\n return supplied;\n }\n return (this.own ??= new PieceWorker({\n telemetry: this.options.telemetry,\n }));\n }\n\n async execute(execution: BlockExecution): Promise<BlockResult> {\n const resolution = this.options.resolveBlock\n ? await this.options.resolveBlock(execution.block)\n : pinnedResolution(execution.block);\n const parsed = resolvedBlock(resolution);\n if (!parsed) throw missingError(resolution);\n if (parsed.kind !== \"action\") {\n throw new TriggerBlockAsStepError(execution.block);\n }\n try {\n const builtin = builtinPiece(parsed.packageName);\n const result = builtin\n ? await runBuiltinAction(\n builtin,\n parsed.name,\n execution.config as Record<string, unknown>,\n )\n : await this.run(execution, parsed);\n return { ...result, resolution };\n } catch (error) {\n throw withResolution(error, resolution);\n }\n }\n\n private async run(\n execution: BlockExecution,\n parsed: ParsedBlockType,\n ): Promise<BlockResult> {\n // One staging directory per execution, removed in the finally below. A\n // host crash can still leave one behind, which is why it lives under a\n // root the host can sweep at startup.\n const stagingDir = this.options.stagingRoot\n ? path.join(this.options.stagingRoot, randomUUID())\n : undefined;\n\n // Bundle fetch and connection resolution belong inside the catch: a secret\n // provider or a resolver can fail with the credential in its own message.\n const runSecrets = execution.redactValues ?? [];\n let redactValues: string[] = [...runSecrets];\n try {\n const ref = {\n name: parsed.packageName,\n version: parsed.version,\n ...(parsed.source ? { source: parsed.source } : {}),\n };\n const telemetry = this.options.telemetry;\n const piece = await (telemetry\n ? telemetry.phase(\"piece.resolve\", {}, () => this.resolver.resolve(ref))\n : this.resolver.resolve(ref));\n const connection = await this.resolveConnection(execution.connectionId, {\n piecePackage: parsed.packageName,\n stepId: execution.step.id,\n stepKey: execution.step.key,\n });\n const auth = connection?.auth;\n redactValues = [...runSecrets, ...(connection?.secretValues ?? [])];\n\n const timeoutMs = execution.step.timeoutSeconds\n ? execution.step.timeoutSeconds * 1000\n : this.options.defaultTimeoutMs;\n // Staging and ingest count against the step's timeout, not only the\n // piece's own run.\n const deadline = timeoutMs ? Date.now() + timeoutMs : undefined;\n const signal = deadline ? AbortSignal.timeout(timeoutMs!) : undefined;\n const stagedInputs = await this.stageInputs(\n execution.config,\n stagingDir,\n signal,\n );\n const remainingMs = deadline\n ? Math.max(1, deadline - Date.now())\n : undefined;\n const pieceStore = this.options.pieceStore;\n const notifications = stepTaps(this.options, execution, redactValues);\n const egress =\n this.options.egress === undefined\n ? DEFAULT_EGRESS_POLICY\n : this.options.egress;\n const reactorTap = await this.options.reactorAccess?.({\n block: parsed,\n reactorConnectionId: execution.reactorConnectionId,\n });\n const result = await this.worker().runAction(\n {\n ...pieceModuleRef(piece),\n actionName: parsed.name,\n propsValue: execution.config as Record<string, unknown>,\n auth,\n identity: {\n ...this.options.identity?.(),\n stepName: execution.step.key,\n },\n ...(redactValues.length > 0 ? { redactValues } : {}),\n ...(this.options.stepTest?.() ? { stepTest: true } : {}),\n ...(stagingDir ? { stagingDir } : {}),\n ...(stagedInputs ? { stagedInputs } : {}),\n ...(pieceStore ? { durableStore: true } : {}),\n ...(this.options.onPieceLog ? { captureLogs: true } : {}),\n ...(this.options.onPartialOutput ? { liveOutput: true } : {}),\n ...(egress ? { egress } : {}),\n },\n {\n ...(remainingMs ? { timeoutMs: remainingMs } : {}),\n // Never shorter than the step's own timeout: a step given two\n // minutes must not have its host calls cut off after ten seconds.\n hostCallTimeoutMs: hostCallTimeoutForStep(timeoutMs),\n ...(pieceStore ? { hostCalls: storeHandlers(pieceStore) } : {}),\n ...(notifications ? { notifications } : {}),\n ...(reactorTap ? { reactor: reactorTap } : {}),\n },\n );\n return {\n output: await this.ingestFiles(\n result.output,\n result.files,\n stagingDir,\n signal,\n ),\n redactValues,\n };\n } catch (error) {\n // The child already stripped what it threw; this covers what the host\n // itself raises (bundle fetch, connection resolution, file ingest).\n throw redactThrown(error, redactValues);\n } finally {\n if (stagingDir) await rm(stagingDir, { recursive: true, force: true });\n }\n }\n\n private async resolveConnection(\n connectionId: string | null | undefined,\n request: ConnectionRequest,\n ): Promise<ResolvedConnection | undefined> {\n const connections = this.options.connections;\n if (!connectionId || !connections) return undefined;\n // The request travels with both, so taking the secret-bearing path never\n // means skipping the check on who is asking.\n if (connections.resolveWithSecrets) {\n return connections.resolveWithSecrets(connectionId, request);\n }\n const auth = await connections.resolve(connectionId, request);\n return { auth, secretValues: [...collectSecretValues(auth)] };\n }\n\n private async stageInputs(\n config: unknown,\n stagingDir: string | undefined,\n signal: AbortSignal | undefined,\n ): Promise<StagedInput[] | undefined> {\n const port = this.options.attachments;\n if (!stagingDir || !port) return undefined;\n const refs = new Set<string>();\n collectRefs(config, refs);\n if (refs.size === 0) return undefined;\n await mkdir(stagingDir, { recursive: true });\n const staged: StagedInput[] = [];\n let index = 0;\n for (const ref of refs) {\n const destPath = path.join(stagingDir, `in-${index++}`);\n try {\n const meta = await this.readAttachment(port, ref, destPath, signal);\n staged.push({ ref, path: destPath, ...meta });\n } catch (error) {\n if (signal?.aborted) throw error;\n staged.push({\n ref,\n path: \"\",\n error: error instanceof Error ? error.message : String(error),\n });\n // Staging is opportunistic: refs are collected from the whole config\n // without knowing which props are FILE, because the prop schema lives\n // in the worker. So a ref this step was never going to open must not\n // fail it -- a dispatch carrying one as data is the ordinary case. A\n // FILE prop that did need it still fails, in the worker, naming the\n // reference it could not resolve.\n logger.debug(\n \"Left @ref unstaged: @error\",\n ref,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n return staged;\n }\n\n // The cache answers only after the port's own read check.\n private async readAttachment(\n port: AttachmentPort,\n ref: string,\n destPath: string,\n signal: AbortSignal | undefined,\n ): Promise<{ fileName?: string; contentType?: string }> {\n const cache = this.options.attachmentCache;\n if (!cache || !port.authorize || !AttachmentCache.cacheable(ref)) {\n return port.read(ref, destPath, signal);\n }\n await port.authorize(ref);\n const hit = await cache.get(ref, destPath).catch(() => undefined);\n if (hit) {\n return {\n ...(hit.fileName !== undefined ? { fileName: hit.fileName } : {}),\n ...(hit.contentType !== undefined\n ? { contentType: hit.contentType }\n : {}),\n };\n }\n const meta = await port.read(ref, destPath, signal);\n await cache.put(ref, destPath, meta).catch((error: unknown) => {\n logger.debug(\n \"Could not cache @ref: @error\",\n ref,\n error instanceof Error ? error.message : String(error),\n );\n });\n return meta;\n }\n\n // A file the worker reports must be one it wrote into this step's staging\n // directory: the host reads the path, and piece code runs in the worker.\n private async checkStagedFile(\n file: StagedFile,\n stagingDir: string | undefined,\n ): Promise<number> {\n if (!stagingDir) {\n throw new Error(\n `Refusing to ingest \"${file.fileName}\": no staging directory`,\n );\n }\n const root = await realpath(stagingDir);\n const resolved = path.resolve(file.path);\n const info = await lstat(resolved).catch(() => undefined);\n // A hard link (nlink > 1) could point at any file the host user owns.\n if (\n !info?.isFile() ||\n info.nlink !== 1 ||\n path.dirname(await realpath(resolved)) !== root ||\n path.dirname(resolved) !== path.resolve(stagingDir)\n ) {\n throw new Error(\n `Refusing to ingest \"${file.fileName}\": it is not a file the step wrote`,\n );\n }\n const limit = maxFileBytes();\n if (info.size > limit) throw new FileTooLargeError(info.size, limit);\n return info.size;\n }\n\n // A provisional apfile:// token only becomes a real reference once the step\n // has returned, so a piece that writes a file and then reads it back by URL\n // within the same run would not work. No action needs that today; the fix is\n // a bidirectional worker channel, which is its own design.\n private async ingestFiles(\n output: unknown,\n files: StagedFile[] | undefined,\n stagingDir: string | undefined,\n signal: AbortSignal | undefined,\n ): Promise<unknown> {\n if (!files || files.length === 0) return output;\n const port = this.options.attachments;\n if (!port) {\n throw new Error(\n `The action wrote ${files.length} file(s) through ctx.files, but no attachment store is configured for this reactor`,\n );\n }\n const refs = new Map<string, string>();\n for (const file of files) {\n const size = await this.checkStagedFile(file, stagingDir);\n refs.set(\n file.token,\n await port.write(\n {\n path: path.resolve(file.path),\n fileName: file.fileName,\n size,\n contentType: file.contentType,\n },\n signal,\n ),\n );\n }\n return rewriteFileRefs(output, refs);\n }\n\n dispose(): void {\n this.own?.dispose();\n this.own = undefined;\n }\n}\n\n// Routes explicit handlers first, then the piece executor. Handlers, keyed\n// by blockKey, let a host serve blocks of its own in its process.\nexport class CompositeBlockExecutor implements BlockExecutor {\n constructor(\n private readonly pieces: BlockExecutor,\n private readonly handlers: Record<string, BlockExecutor> = {},\n ) {}\n\n execute(execution: BlockExecution): Promise<BlockResult> {\n const handler = this.handlers[blockKey(execution.block)] as\n | BlockExecutor\n | undefined;\n if (handler) return handler.execute(execution);\n return this.pieces.execute(execution);\n }\n}\n","// Per-step retry, as the coordinator runs it.\n//\n// The workflow document has carried a step `retry` block and a workflow\n// `defaultRetry` since its first version and nothing read either one, so an\n// author who set `maxAttempts: 3` got exactly one attempt and no warning\n// (W3.3, backlog item 4). This is the policy, resolved; `coordinator.ts`\n// applies it.\n//\n// It lives in the piece layer rather than beside the rest of the policy\n// because the coordinator is here and nothing under `src/pieces` may import\n// `src/reactor`.\n\nexport type BackoffKind = \"FIXED\" | \"EXPONENTIAL\";\n\n/** A retry policy with every field resolved; `maxAttempts` is already clamped. */\nexport interface EffectiveRetryPolicy {\n maxAttempts: number;\n backoff: BackoffKind;\n initialDelaySeconds: number;\n maxDelaySeconds: number;\n /** Empty means every error is retryable; see {@link isRetryableError}. */\n retryOn: readonly string[];\n}\n\n/**\n * A step's attempt ceiling.\n *\n * Clamped rather than trusted: `maxAttempts` is author input with no bound in\n * the schema, and each attempt re-runs a side effect and holds the run's\n * worker slot. Ten is well past any useful retry and far short of a workflow\n * that cannot be stopped.\n */\nexport const MAX_STEP_ATTEMPTS = 10;\n\n/** The ceiling on one backoff wait, whatever `maxDelaySeconds` says: the wait\n * holds the run's worker slot, and the run deadline bounds the rest. */\nexport const MAX_RETRY_DELAY_MS = 5 * 60_000;\n\nfunction positive(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0\n ? value\n : null;\n}\n\n/** Resolves an author-written retry block; null when it asks for one attempt,\n * which is the same thing as no retry policy and saves every reader a branch. */\nexport function effectiveRetryPolicy(\n retry: unknown,\n): EffectiveRetryPolicy | null {\n if (typeof retry !== \"object\" || retry === null) return null;\n const record = retry as Record<string, unknown>;\n const asked = positive(record.maxAttempts) ?? 1;\n const maxAttempts = Math.min(Math.trunc(asked), MAX_STEP_ATTEMPTS);\n if (maxAttempts <= 1) return null;\n const initial = positive(record.initialDelaySeconds) ?? 0;\n const max = positive(record.maxDelaySeconds) ?? initial;\n return {\n maxAttempts,\n backoff: record.backoff === \"EXPONENTIAL\" ? \"EXPONENTIAL\" : \"FIXED\",\n initialDelaySeconds: initial,\n maxDelaySeconds: Math.max(initial, max),\n retryOn: Array.isArray(record.retryOn)\n ? record.retryOn.filter(\n (entry): entry is string => typeof entry === \"string\",\n )\n : [],\n };\n}\n\n/** How long to wait before `attempt` (1-based: attempt 2 is the first retry).\n * EXPONENTIAL doubles from the initial delay, capped both by the author's\n * `maxDelaySeconds` and by {@link MAX_RETRY_DELAY_MS}. */\nexport function retryDelayMs(\n retry: EffectiveRetryPolicy,\n attempt: number,\n): number {\n const initial = retry.initialDelaySeconds * 1000;\n const raw =\n retry.backoff === \"EXPONENTIAL\"\n ? initial * 2 ** Math.max(0, attempt - 2)\n : initial;\n return Math.max(\n 0,\n Math.min(raw, retry.maxDelaySeconds * 1000, MAX_RETRY_DELAY_MS),\n );\n}\n\n/**\n * Whether `retryOn` admits this error.\n *\n * The schema calls its entries \"error classes\", which in a workflow is a loose\n * notion: a piece throws whatever it likes, and what reaches here may be an\n * `Error` subclass of the engine's, an HTTP failure formatted by the piece\n * framework, or a string. So an entry matches the error's CLASS NAME exactly,\n * or appears anywhere in its message — case-insensitively in both cases. That\n * makes `[\"HostCallTimeoutError\"]` and `[\"429\"]` both work, which is what an\n * author writing one of these actually means.\n *\n * An EMPTY list admits everything. The schema's own reading (\"everything else\n * fails terminally on attempt 1\") would make the shipped default — an empty\n * `retryOn` — turn every `maxAttempts` into a lie, so empty is read as\n * \"unrestricted\" and a non-empty list as the filter it is.\n */\nexport function isRetryableError(\n retry: EffectiveRetryPolicy,\n error: unknown,\n): boolean {\n if (retry.retryOn.length === 0) return true;\n const name = (error instanceof Error ? error.name : \"\").toLowerCase();\n const message = (\n error instanceof Error ? error.message : String(error)\n ).toLowerCase();\n return retry.retryOn.some((entry) => {\n const needle = entry.trim().toLowerCase();\n if (needle === \"\") return false;\n return needle === name || message.includes(needle);\n });\n}\n","// A DYNAMIC prop's children are resolved at design time and stored beside the\n// step as `propertySettings[].schema`; the run checks the value against them.\nimport type { PropertySettingDef } from \"./types.js\";\n\n// Non-retryable: the config has to change before the step can succeed.\nexport class DynamicPropertiesError extends Error {\n constructor(\n message: string,\n readonly prop: string,\n readonly missing: string[],\n ) {\n super(message);\n this.name = \"DynamicPropertiesError\";\n }\n}\n\ninterface ChildProp {\n name: string;\n label: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n// Accepts the piece's own props map or the editor's descriptor list.\nfunction requiredChildren(schema: unknown): ChildProp[] {\n const entries: [string, unknown][] = Array.isArray(schema)\n ? schema\n .filter(isRecord)\n .filter((entry) => typeof entry.name === \"string\")\n .map((entry) => [entry.name as string, entry])\n : isRecord(schema)\n ? Object.entries(schema)\n : [];\n return entries\n .filter(([, prop]) => isRecord(prop) && prop.required === true)\n .map(([name, prop]) => {\n const displayName = (prop as Record<string, unknown>).displayName;\n return {\n name,\n label:\n typeof displayName === \"string\" && displayName !== \"\"\n ? `${displayName} (${name})`\n : name,\n };\n });\n}\n\nfunction isBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n\n/** Throws a DynamicPropertiesError naming the first prop whose value does not\n * satisfy its resolved children. Settings without a schema are ignored. */\nexport function checkDynamicProperties(\n config: unknown,\n settings: readonly PropertySettingDef[] | null | undefined,\n): void {\n if (!settings || settings.length === 0) return;\n const values = isRecord(config) ? config : {};\n for (const setting of settings) {\n if (setting.schema === undefined || setting.schema === null) continue;\n const raw = values[setting.prop];\n if (!isBlank(raw) && !isRecord(raw)) {\n throw new DynamicPropertiesError(\n `Property \"${setting.prop}\" must be an object of fields, received ${Array.isArray(raw) ? \"array\" : typeof raw}`,\n setting.prop,\n [],\n );\n }\n const value = isRecord(raw) ? raw : {};\n const missing = requiredChildren(setting.schema).filter((child) =>\n isBlank(value[child.name]),\n );\n if (missing.length > 0) {\n throw new DynamicPropertiesError(\n `Property \"${setting.prop}\" is missing required fields: ${missing.map((child) => child.label).join(\", \")}`,\n setting.prop,\n missing.map((child) => child.name),\n );\n }\n }\n}\n","import { createHash } from \"node:crypto\";\nimport type { WorkflowStepDef } from \"./types.js\";\n\n// JSON with object keys sorted at every depth, so key order never changes a hash.\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(sortKeys(value) ?? null);\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (value === null || typeof value !== \"object\") return value;\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .filter((key) => record[key] !== undefined)\n .map((key) => [key, sortKeys(record[key])]),\n );\n}\n\nexport function hashOf(...parts: string[]): string {\n const hash = createHash(\"sha256\");\n for (const part of parts) hash.update(part).update(\"\\u0000\");\n return hash.digest(\"hex\").slice(0, 16);\n}\n\n// What a step runs from: its block, config, connection and dynamic-prop\n// schemas. Field modes are editor-only.\nexport function stepConfigHash(step: WorkflowStepDef): string {\n const schemas = (step.propertySettings ?? [])\n .filter(\n (setting) => setting.schema !== null && setting.schema !== undefined,\n )\n .map((setting) => ({ prop: setting.prop, schema: setting.schema }));\n return hashOf(\n step.pieceName,\n step.pieceVersion,\n step.actionName,\n canonicalJson({\n config: step.config ?? {},\n connectionId: step.connectionId ?? null,\n propertySettings: schemas,\n // Only when set, so a step without one keeps its hash.\n ...(step.reactorConnectionId\n ? { reactorConnectionId: step.reactorConnectionId }\n : {}),\n }),\n );\n}\n","import {\n containsRedactedMarker,\n redact,\n redactMessage,\n secretsFor,\n} from \"../activepieces/worker/redact.js\";\nimport { PieceWorkerError } from \"../activepieces/worker/host.js\";\nimport {\n evaluateCondition,\n unavailableValue,\n UnavailableValueError,\n type ExpressionScope,\n} from \"./expressions.js\";\nimport {\n effectiveRetryPolicy,\n isRetryableError,\n retryDelayMs,\n type EffectiveRetryPolicy,\n} from \"./retry.js\";\nimport { resolveStepInput } from \"./step-input.js\";\nimport { checkDynamicProperties } from \"./dynamic-props.js\";\nimport { isIndeterminateError } from \"../activepieces/indeterminate.js\";\nimport {\n referenceDocuments,\n undeclaredPortEdges,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport { stepConfigHash } from \"./canonical.js\";\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport { blockLabel, pieceRecord, resolutionOf } from \"./resolution.js\";\nimport {\n stepBlock,\n triggerBlock,\n type BlockExecutor,\n type StepExecutionRecord,\n type WorkflowDefinition,\n type WorkflowRunResult,\n type WorkflowStepDef,\n} from \"./types.js\";\n\n/** One step a prior run already completed, as a rerun replays it. */\nexport interface ReplayedStep {\n output?: unknown;\n port?: string | null;\n /**\n * The step SUCCEEDED, but the run journal truncated its output past the\n * payload cap, so there is nothing to replay.\n *\n * It still replays, rather than running again: the step had side effects and\n * re-running it would charge the card twice (backlog item 15). Its scope\n * entry carries an unavailable value instead of data, so a downstream step\n * that reads `steps.<key>.output…` fails the rerun by name.\n */\n outputTruncated?: boolean;\n /**\n * What the journal holds in place of that output — the truncation marker\n * itself — to be journaled again on this run's REPLAYED row.\n *\n * Opaque to the engine: it is never resolved, only written back. Without it\n * the REPLAYED row's output is NULL, and the NEXT rerun reads a NULL as an\n * ordinary replay with no output: the truncation fact is gone after one\n * generation, and a downstream step is handed nothing instead of being told\n * by name why there is nothing.\n */\n truncatedOutput?: unknown;\n}\n\nexport interface RunWorkflowOptions {\n definition: WorkflowDefinition;\n executor: BlockExecutor;\n // Exposed to expressions as {{trigger.payload...}}.\n triggerPayload?: unknown;\n // Journaled outputs from a prior run, keyed by step id; matching steps\n // replay (output injected, port re-taken) instead of executing.\n completedSteps?: Map<string, ReplayedStep>;\n // The workflow policy's `defaultRetry`, for steps with no `retry` of their\n // own. Absent enforces no retry, which is what a definition with no policy\n // (every legacy document) means.\n defaultRetry?: EffectiveRetryPolicy | null;\n // Epoch ms the run must be over by (`policy.runTimeoutSeconds`). Checked\n // before each step and while a retry waits; past it the run is CANCELLED.\n deadline?: number;\n // Test seam for the retry waits, so a suite does not sleep through them.\n sleep?: (ms: number) => Promise<void>;\n // Called as each step reaches a terminal state, so a run that dies\n // mid-flight leaves the steps it finished behind. Ordinal is execution\n // order; skips are excluded, being knowable only once the run completes.\n onStep?: (\n record: StepExecutionRecord,\n ordinal: number,\n ) => void | Promise<void>;\n // Resolved secret variables: kept out of every journaled record and error.\n redactValues?: string[];\n // Scope entries of steps outside the definition; a single-step test reads\n // its upstream steps' test outputs from here.\n priorSteps?: ExpressionScope[\"steps\"];\n // A block's declared output ports; an edge on any other is a warning.\n declaredPorts?: (block: BlockRef) => readonly string[] | undefined;\n}\n\n// Edges no run can take, because their source never emits that port.\nexport function deadPortWarnings(\n definition: WorkflowDefinition,\n declaredPorts: (block: BlockRef) => readonly string[] | undefined,\n): string[] {\n const blocks = new Map<string, { key: string; block: BlockRef }>(\n definition.steps.map((step) => [\n step.id,\n { key: step.key, block: stepBlock(step) },\n ]),\n );\n if (definition.trigger) {\n blocks.set(definition.trigger.id, {\n key: \"trigger\",\n block: triggerBlock(definition.trigger),\n });\n }\n return undeclaredPortEdges(definition.edges, (id) => {\n const source = blocks.get(id);\n return source ? declaredPorts(source.block) : undefined;\n }).map((edge) => {\n const source = blocks.get(edge.from)!;\n const target = blocks.get(edge.to)?.key ?? edge.to;\n return `Edge from \"${source.key}\" to \"${target}\" leaves on port \"${edge.port}\", which ${blockLabel(source.block)} never takes`;\n });\n}\n\nfunction withPiece(\n piece: StepExecutionRecord[\"piece\"],\n): Pick<StepExecutionRecord, \"piece\"> {\n return piece ? { piece } : {};\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\n// A piece's own error crosses the worker inside a PieceWorkerError.\nexport function errorNameOf(error: unknown): string | undefined {\n if (error instanceof PieceWorkerError) return error.serialized.name;\n return error instanceof Error ? error.name : undefined;\n}\n\n// A record is journal material, read back by the editor and kept in the\n// database, so it never carries the live value a downstream step reads.\nfunction journaled(value: unknown, values: string[] | undefined): unknown {\n return value === undefined ? undefined : redact(value, { values });\n}\n\n/** What a run that passed `policy.runTimeoutSeconds` ends CANCELLED with. */\n/** The error name a run its deadline cancelled is journaled with; it is what\n * marks the run as resumable, unlike a firing that was refused. */\nexport const RUN_DEADLINE_ERROR_NAME = \"RunDeadlineExceeded\";\n\nexport const RUN_DEADLINE_REASON =\n \"Run exceeded its runTimeoutSeconds and was cancelled\";\n\n// Sequential v1 of the RunCoordinator (doc 08 §7.3): walks the steps+edges\n// graph, resolving each step's config against prior outputs before executing.\nexport async function runWorkflow(\n options: RunWorkflowOptions,\n): Promise<WorkflowRunResult> {\n const { definition, executor } = options;\n const runSecrets = options.redactValues ?? [];\n const scope: ExpressionScope = {\n trigger: { payload: options.triggerPayload },\n steps: { ...options.priorSteps },\n variables: Object.fromEntries(\n (definition.variables ?? []).map((v) => [v.key, v.value ?? null]),\n ),\n };\n\n const records = new Map<string, StepExecutionRecord>();\n // edgeId -> taken; an edge is decided once its source ran or was skipped.\n const edgeDecisions = new Map<string, boolean>();\n let runFailed: string | undefined;\n // Set instead of runFailed when the run ran out of time: the workflow did\n // not fail, it was stopped, and the status says so.\n let runCancelled: string | undefined;\n let runFailedName: string | undefined;\n let executedCount = 0;\n const sleep =\n options.sleep ??\n ((ms: number) =>\n new Promise<void>((resolve) => {\n // A pending retry wait must not be what keeps the process alive.\n setTimeout(resolve, ms).unref();\n }));\n\n // Null while there is time left; the reason once there is not.\n const outOfTime = (): string | undefined => {\n if (options.deadline === undefined) return undefined;\n if (Date.now() < options.deadline) return undefined;\n return RUN_DEADLINE_REASON;\n };\n\n // A failing journal write must not cost us the step's completed work: the\n // run carries on, and finishRun's final sweep repairs the missing row.\n const journal = async (record: StepExecutionRecord) => {\n if (!options.onStep) return;\n const ordinal = executedCount++;\n try {\n await options.onStep(record, ordinal);\n } catch {\n // Durability is the bonus here; run correctness is not at stake.\n }\n };\n\n const decideOutgoing = (sourceId: string, port: string | undefined) => {\n for (const edge of definition.edges) {\n if (edge.from !== sourceId) continue;\n const portMatches = port !== undefined && edge.port === port;\n let taken = portMatches;\n if (taken && edge.condition) {\n try {\n taken = evaluateCondition(edge.condition, scope);\n } catch (error) {\n taken = false;\n runFailed ??= `Condition of edge \"${edge.id}\": ${errorMessage(error)}`;\n }\n }\n edgeDecisions.set(edge.id, taken);\n }\n };\n\n // Trigger edges fire on the trigger's implicit \"next\" port.\n if (definition.trigger) {\n decideOutgoing(definition.trigger.id, \"next\");\n }\n\n const inboundEdges = (step: WorkflowStepDef) =>\n definition.edges.filter((edge) => edge.to === step.id);\n\n const isEntryStep = (step: WorkflowStepDef) =>\n !definition.trigger && inboundEdges(step).length === 0;\n\n const skipStep = (step: WorkflowStepDef) => {\n records.set(step.id, {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"SKIPPED\",\n });\n decideOutgoing(step.id, undefined);\n };\n\n // The journal keeps a redacted copy, so a replay would hand the marker to\n // the next step. Refusing is loud; replaying it would be silently wrong.\n const refuseReplay = (step: WorkflowStepDef) => {\n const error =\n `Journaled output of step \"${step.key}\" was redacted and cannot be ` +\n \"replayed; fire the workflow again instead of rerunning it\";\n records.set(step.id, {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"FAILED\",\n error,\n });\n runFailed = error;\n };\n\n // An author-skipped step continues on \"next\" as if it output nothing.\n const passStep = async (step: WorkflowStepDef) => {\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"SKIPPED\",\n output: null,\n port: \"next\",\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output: null };\n decideOutgoing(step.id, \"next\");\n };\n\n const executeStep = async (step: WorkflowStepDef) => {\n if (step.skip === true) {\n await passStep(step);\n return;\n }\n const replay = options.completedSteps?.get(step.id);\n if (replay) {\n if (containsRedactedMarker(replay.output)) {\n refuseReplay(step);\n return;\n }\n const port = replay.port ?? \"next\";\n // Truncated: the step is completed, its output is not available. Both\n // halves have to be true at once, or the rerun either re-runs a side\n // effect or hands a marker on as data.\n const output = replay.outputTruncated\n ? unavailableValue(\n `Output of step \"${step.key}\" is unavailable: it succeeded in the ` +\n \"run being rerun, but the run journal truncated its output past \" +\n \"the payload cap. The step is not re-run, because it had side \" +\n \"effects. Fire the workflow again instead of rerunning it.\",\n )\n : replay.output;\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"REPLAYED\",\n // Not the wrapper: that is a run-scope device and carries its reason on\n // a symbol. The marker goes on `journaledOutput` instead, which is what\n // carries the truncation fact into the NEXT rerun — a NULL output\n // column reads as an ordinary replay with nothing to replay, and the\n // fact would be gone after one generation.\n output: replay.outputTruncated ? undefined : replay.output,\n ...(replay.outputTruncated && replay.truncatedOutput !== undefined\n ? { journaledOutput: replay.truncatedOutput }\n : {}),\n port,\n configHash: stepConfigHash(step),\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output };\n decideOutgoing(step.id, port);\n return;\n }\n\n // One resolved policy per step: its own `retry`, else the workflow's. A\n // step that DECLARES a block overrides, whatever the block resolves to —\n // `{maxAttempts: 1}` is an author saying \"not this one\", and inheriting\n // the workflow default over it would be the opposite of an override.\n const retry =\n step.retry === undefined || step.retry === null\n ? (options.defaultRetry ?? null)\n : effectiveRetryPolicy(step.retry);\n const maxAttempts = retry?.maxAttempts ?? 1;\n const startedAt = new Date().toISOString();\n let input: unknown;\n\n // Resolution is OUTSIDE the retry loop on purpose. It reads the scope and\n // nothing else, and no attempt of this step changes the scope, so every\n // attempt would resolve the very same value — while a resolution error is\n // deterministic by construction: a reference to a key that does not exist\n // names nothing on attempt five either. Inside the loop it burned the\n // whole retry budget, backoff waits and all, on an error that could not\n // come right, and held the run's worker slot while it did.\n try {\n input = resolveStepInput(step, scope);\n checkDynamicProperties(input, step.propertySettings);\n } catch (error) {\n await endStep(step, { error, input, startedAt, attempt: 1 });\n return;\n }\n\n for (let attempt = 1; ; attempt++) {\n const attempts = attempt > 1 ? { attempts: attempt } : {};\n try {\n const result = await executor.execute({\n block: stepBlock(step),\n config: input,\n connectionId: step.connectionId,\n reactorConnectionId: step.reactorConnectionId,\n step,\n ...(runSecrets.length > 0 ? { redactValues: runSecrets } : {}),\n });\n const port = result.port ?? \"next\";\n const values = [...runSecrets, ...(result.redactValues ?? [])];\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"SUCCEEDED\",\n input: journaled(input, values),\n // Documents go into the record as references; the scope keeps them whole.\n output: journaled(referenceDocuments(result.output), values),\n port,\n startedAt,\n endedAt: new Date().toISOString(),\n ...withPiece(pieceRecord(result.resolution)),\n configHash: stepConfigHash(step),\n ...attempts,\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output: result.output };\n decideOutgoing(step.id, port);\n return;\n } catch (error) {\n // A host call that timed out may have committed the write it asked\n // for, so neither the step's failure nor its success is knowable. It\n // is not retried either: a retry would be a second write.\n const indeterminate = isIndeterminateError(error);\n const retryable =\n retry !== null &&\n attempt < maxAttempts &&\n !indeterminate &&\n // A value that is gone stays gone, and an expression that names\n // nothing names nothing on the next attempt either.\n !(error instanceof UnavailableValueError) &&\n isRetryableError(retry, error);\n if (retryable) {\n const stopped = await waitForRetry(retryDelayMs(retry, attempt + 1));\n // The deadline fell during the wait (or was already past): the run\n // is over, so NO further attempt runs. The attempt that failed is\n // journaled as the record of work done, without taking an error\n // port — nothing downstream may run after the run has ended — and\n // the run reads CANCELLED, since the clock stopped it rather than\n // the workflow failing.\n if (stopped !== undefined) {\n await endStep(step, {\n error,\n input,\n startedAt,\n attempt,\n cancelled: stopped,\n });\n return;\n }\n continue;\n }\n await endStep(step, { error, input, startedAt, attempt });\n return;\n }\n }\n };\n\n /**\n * A retry wait, clipped to the run's deadline.\n *\n * Undefined when there is room for both the wait and another attempt.\n * Otherwise the reason the run is over: the wait is served out only as far\n * as the deadline, never past it, and the caller runs no further attempt.\n * Sleeping the full backoff and leaving the deadline to \"the next attempt's\n * own check\" meant that attempt ran its side effect after the run had\n * expired, and the run then ended FAILED rather than CANCELLED.\n */\n async function waitForRetry(waitMs: number): Promise<string | undefined> {\n const expired = outOfTime();\n if (expired !== undefined) return expired;\n if (options.deadline === undefined) {\n if (waitMs > 0) await sleep(waitMs);\n return undefined;\n }\n const remaining = options.deadline - Date.now();\n if (waitMs >= remaining) {\n if (remaining > 0) await sleep(remaining);\n return RUN_DEADLINE_REASON;\n }\n if (waitMs > 0) await sleep(waitMs);\n // The wait fitted, but a slow timer can still land on the deadline.\n return outOfTime();\n }\n\n /**\n * The terminal end of a step that threw: its record, its error port, and\n * what that means for the run.\n *\n * One place for it, because three paths reach it — a deterministic\n * resolution failure before the first attempt, an exhausted or refused\n * retry, and a retry the run's deadline cut short.\n */\n async function endStep(\n step: WorkflowStepDef,\n outcome: {\n error: unknown;\n input: unknown;\n startedAt: string;\n attempt: number;\n // Set when the clock is why there is no further attempt; the run is\n // CANCELLED rather than FAILED, and no error port is taken.\n cancelled?: string;\n },\n ): Promise<void> {\n const { error, input, startedAt, attempt } = outcome;\n // A failed step is exactly where an input gets inspected, so it is\n // redacted with the same secrets the successful path uses.\n const values = [...runSecrets, ...secretsFor(error)];\n const detail = redactMessage(errorMessage(error), { values });\n const indeterminate = isIndeterminateError(error);\n const errorName = errorNameOf(error);\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: indeterminate ? \"INDETERMINATE\" : \"FAILED\",\n input: journaled(input, values),\n error: detail,\n ...(errorName ? { errorName } : {}),\n startedAt,\n endedAt: new Date().toISOString(),\n ...withPiece(pieceRecord(resolutionOf(error))),\n configHash: stepConfigHash(step),\n ...(attempt > 1 ? { attempts: attempt } : {}),\n };\n records.set(step.id, record);\n await journal(record);\n if (indeterminate) {\n // No port, so nothing downstream runs and no error branch claims to\n // have handled something that may have succeeded.\n runFailed = `Step \"${step.key}\" is INDETERMINATE: ${detail}`;\n runFailedName = errorName;\n return;\n }\n if (outcome.cancelled !== undefined) {\n runCancelled = outcome.cancelled;\n return;\n }\n // The same redacted text the journal took: an error-port branch writing\n // the reason somewhere a person will read must not widen what a failure\n // discloses.\n scope.steps[step.key] = { error: detail };\n decideOutgoing(step.id, \"error\");\n const errorHandled = definition.edges.some(\n (edge) => edge.from === step.id && edgeDecisions.get(edge.id),\n );\n if (!errorHandled) {\n const failedAfter = attempt > 1 ? ` after ${attempt} attempts` : \"\";\n runFailed = `Step \"${step.key}\" failed${failedAfter}: ${detail}`;\n runFailedName = errorName;\n }\n }\n\n // Before a step that will execute, never during it: a step is the unit of\n // work and killing one mid-flight would leave a side effect with no record.\n // Not before a step that would only be skipped, so the outcome does not\n // depend on graph shape. `??=`, not `=`: a retry wait that ran out the\n // clock has already set this, and a timer that fired a hair early must not\n // clear it.\n const expiredBeforeStep = (): boolean => {\n runCancelled ??= outOfTime();\n return runCancelled !== undefined;\n };\n\n let progressed = true;\n while (progressed && !runFailed && !runCancelled) {\n progressed = false;\n for (const step of definition.steps) {\n if (records.has(step.id)) continue;\n const inbound = inboundEdges(step);\n if (isEntryStep(step)) {\n if (expiredBeforeStep()) break;\n await executeStep(step);\n progressed = true;\n // Independent roots are otherwise free to run their side effects\n // before the outer loop notices the run is already over.\n if (runFailed || runCancelled) break;\n continue;\n }\n if (inbound.length === 0) continue;\n const decided = inbound.every((edge) => edgeDecisions.has(edge.id));\n if (!decided) continue;\n const reachable = inbound.some((edge) => edgeDecisions.get(edge.id));\n if (reachable) {\n if (expiredBeforeStep()) break;\n await executeStep(step);\n } else {\n skipStep(step);\n }\n progressed = true;\n if (runFailed || runCancelled) break;\n }\n }\n\n // Steps never reached (dangling, cyclic, or after a terminal failure).\n for (const step of definition.steps) {\n if (!records.has(step.id)) skipStep(step);\n }\n\n // A FAILED record with a taken error edge is a handled failure; only\n // unhandled ones set runFailed above.\n const steps = definition.steps.map((step) => records.get(step.id)!);\n const warnings = options.declaredPorts\n ? deadPortWarnings(definition, options.declaredPorts)\n : [];\n const noted = warnings.length > 0 ? { warnings } : {};\n if (runFailed) {\n return {\n status: \"FAILED\",\n steps,\n error: runFailed,\n ...(runFailedName ? { errorName: runFailedName } : {}),\n ...noted,\n };\n }\n // The deadline is the last word: a run whose final step happened to finish\n // in time still reads CANCELLED if the loop stopped for the clock, and the\n // steps it did complete are journaled either way.\n if (runCancelled) {\n return {\n status: \"CANCELLED\",\n steps,\n error: runCancelled,\n errorName: RUN_DEADLINE_ERROR_NAME,\n ...noted,\n };\n }\n return { status: \"SUCCEEDED\", steps, ...noted };\n}\n","// The pieces this reactor holds locally, by piece name.\n\n// A holder, not a finder: resolving a package is the host's package manager's\n// job, and this runtime must not depend on reactor-api to have it done.\nimport { childLogger } from \"document-model\";\nimport {\n builtinLocalPieces,\n isBuiltinPiece,\n type LocalPiece,\n} from \"../pieces/index.js\";\n\nconst logger = childLogger([\"workflow\", \"piece-registry\"]);\n\nfunction pieceLocation(piece: LocalPiece): string {\n return piece.entryPath ?? piece.bundleDir ?? piece.entryUrl ?? \"?\";\n}\n\nexport class PieceRegistry {\n private byName = new Map<string, LocalPiece>();\n\n // Replaces the whole set: what the host reports is everything it holds, so\n // a piece missing from it is a piece the reactor no longer has.\n setPieces(pieces: readonly LocalPiece[]): void {\n const found = new Map<string, LocalPiece>();\n for (const piece of pieces) {\n // The first claim keeps the name; the host hands pieces in package-name order.\n const held = found.get(piece.name);\n if (!held) {\n found.set(piece.name, piece);\n continue;\n }\n logger.warn(\n \"Piece @name is shipped twice; keeping @kept, ignoring @ignored\",\n piece.name,\n `${held.version} (${pieceLocation(held)})`,\n `${piece.version} (${pieceLocation(piece)})`,\n );\n }\n this.byName = found;\n const names = [...found.keys()].join(\", \");\n // \"Holding\" meant one thing when every piece was code on this disk. A\n // package loaded from a registry contributes the declaration, not the code.\n const held = [...found.values()].filter(\n (piece) => piece.entryPath ?? piece.bundleDir,\n ).length;\n const served = found.size - held;\n // Names go through the logger's values: it substitutes `@`-prefixed\n // tokens, and a scoped package name printed inline comes out as null/pack.\n if (found.size > 0) {\n const what =\n served === 0\n ? `${held} package piece(s) on disk`\n : held === 0\n ? `${served} package piece(s), fetched when first run`\n : `${held} on disk and ${served} fetched when first run`;\n logger.info(`Holding ${what}: @names`, names);\n } else {\n logger.debug(\"Holding no package pieces\");\n }\n }\n\n lookup = (name: string): LocalPiece | undefined => this.byName.get(name);\n\n entries(): LocalPiece[] {\n return [...this.byName.values()];\n }\n\n // Name -> installed version.\n versions(): Record<string, string> {\n return Object.fromEntries(\n [...this.byName.values()].map((piece) => [piece.name, piece.version]),\n );\n }\n\n /** Test seam: a suite that filled the registry starts the next from nothing. */\n reset(): void {\n this.byName = new Map();\n }\n}\n\n// One registry for the runtime, the way the bundle cache is one directory.\nexport const packagePieces = new PieceRegistry();\n\n// What the runtime can run as installed: its built-in pieces, which always\n// answer for their names, then the host's.\nexport function installedPiece(name: string): LocalPiece | undefined {\n return (\n builtinLocalPieces().find((piece) => piece.name === name) ??\n packagePieces.lookup(name)\n );\n}\n\nexport function installedPieces(): LocalPiece[] {\n return [\n ...builtinLocalPieces(),\n ...packagePieces.entries().filter((piece) => !isBuiltinPiece(piece.name)),\n ];\n}\n","// Spans and metrics for runs, steps, workers and the reactor a step reaches.\n// The host passes its tracer and meter; absent, the global API's (no-op until registered).\nimport {\n context as otelContext,\n metrics,\n SpanStatusCode,\n trace,\n type Attributes,\n type BatchObservableCallback,\n type Context,\n type Counter,\n type Histogram,\n type Meter,\n type ObservableGauge,\n type Span,\n type Tracer,\n} from \"@opentelemetry/api\";\nimport type {\n WorkerPhaseTiming,\n WorkerTimings,\n} from \"./pieces/activepieces/worker/protocol.js\";\nimport {\n resolutionOf,\n type BlockResolution,\n} from \"./pieces/engine/resolution.js\";\nimport type { BlockExecutor } from \"./pieces/engine/types.js\";\n\nexport const TELEMETRY_SCOPE = \"@powerhousedao/reactor-workflow\";\n\nexport interface WorkflowTelemetryOptions {\n tracer?: Tracer;\n meter?: Meter;\n}\n\nexport interface WorkerPoolStats {\n size: number;\n active: number;\n idle: number;\n waiting: number;\n}\n\nexport class WorkflowTelemetry {\n readonly tracer: Tracer;\n private readonly meter: Meter;\n private readonly runs: Counter;\n private readonly runDuration: Histogram;\n private readonly stepDuration: Histogram;\n private readonly phaseDuration: Histogram;\n private dispatcherGauges?: Record<\n \"inFlight\" | \"waiting\" | \"loop\",\n ObservableGauge\n >;\n private poolGauges?: Record<\n \"size\" | \"active\" | \"idle\" | \"waiting\",\n ObservableGauge\n >;\n\n constructor(options: WorkflowTelemetryOptions = {}) {\n this.tracer = options.tracer ?? trace.getTracer(TELEMETRY_SCOPE);\n this.meter = options.meter ?? metrics.getMeter(TELEMETRY_SCOPE);\n this.runs = this.meter.createCounter(\"workflow.runs\", {\n description: \"Runs finished, by status and trigger kind\",\n unit: \"{run}\",\n });\n this.runDuration = this.meter.createHistogram(\"workflow.run.duration\", {\n description: \"Run duration from fire to the journal closing it\",\n unit: \"ms\",\n });\n this.stepDuration = this.meter.createHistogram(\"workflow.step.duration\", {\n description: \"Step duration, by piece and status\",\n unit: \"ms\",\n });\n this.phaseDuration = this.meter.createHistogram(\"workflow.phase.duration\", {\n description:\n \"Duration of one part of a run: load, journal writes, worker, reactor calls\",\n unit: \"ms\",\n });\n }\n\n // `name` is also the `phase` attribute on workflow.phase.duration.\n phase<T>(\n name: string,\n attributes: Attributes,\n fn: (span: Span) => Promise<T>,\n parent?: Context,\n ): Promise<T> {\n const started = performance.now();\n return this.span(`workflow.${name}`, attributes, fn, parent).finally(() =>\n this.recordPhase(name, performance.now() - started),\n );\n }\n\n // The child's own marks, as spans under its request. `forkedAt` starts the\n // boot span when this response is the child's first.\n workerTimings(\n request: Span,\n timings: WorkerTimings,\n forkedAt: number,\n ipc: { sent: number; received: number },\n ): void {\n const under = (span: Span) => trace.setSpan(otelContext.active(), span);\n const child = (\n name: string,\n start: number,\n end: number,\n parent: Span = request,\n attributes?: Attributes,\n ): Span => {\n const span = this.tracer.startSpan(\n `workflow.worker.${name}`,\n { startTime: start, ...(attributes ? { attributes } : {}) },\n under(parent),\n );\n span.end(end);\n this.recordPhase(`worker.${name}`, end - start);\n return span;\n };\n const ready = finite(timings.ready);\n if (ready !== undefined && forkedAt > 0) {\n child(\"boot\", forkedAt, Math.max(forkedAt, ready));\n }\n const received = finite(timings.received);\n const sent = finite(timings.sent);\n // A request queued behind boot only starts travelling once the child is up.\n const delivered = Math.max(ipc.sent, ready ?? 0);\n if (received !== undefined) {\n child(\"ipc.in\", delivered, Math.max(delivered, received));\n }\n // Parents first, so a nested phase finds the span it ran inside.\n const byName = new Map<string, Span>();\n const phases = Array.isArray(timings.phases) ? timings.phases : [];\n for (const phase of phases\n .filter(knownPhase)\n .sort((a, b) => a.start - b.start)) {\n const parent = phase.parent ? byName.get(phase.parent) : undefined;\n byName.set(\n phase.name,\n child(\n phase.name,\n phase.start,\n phase.end,\n parent,\n phaseAttributes(phase.attributes),\n ),\n );\n }\n if (sent !== undefined) {\n child(\"ipc.out\", sent, Math.max(sent, ipc.received));\n }\n request.setAttributes(workerMemory(timings.memory));\n }\n\n recordPhase(name: string, ms: number): void {\n this.phaseDuration.record(ms, { phase: name });\n }\n\n span<T>(\n name: string,\n attributes: Attributes,\n fn: (span: Span) => Promise<T>,\n parent: Context = otelContext.active(),\n ): Promise<T> {\n return this.tracer.startActiveSpan(\n name,\n { attributes },\n parent,\n async (span) => {\n try {\n return await fn(span);\n } catch (error) {\n failSpan(span, error);\n throw error;\n } finally {\n span.end();\n }\n },\n );\n }\n\n recordRun(ms: number, status: string, triggerKind: string): void {\n const attributes = {\n \"run.status\": status,\n \"trigger.kind\": metricTriggerKind(triggerKind),\n };\n this.runs.add(1, attributes);\n this.runDuration.record(ms, attributes);\n }\n\n recordStep(ms: number, pieceName: string, status: string): void {\n this.stepDuration.record(ms, {\n \"piece.name\": pieceName,\n \"step.status\": status,\n });\n }\n\n // Gauges read on each collection. Returns the unobserve a disposed pool calls,\n // so a replaced runtime's pool stops reporting and can be collected.\n observeWorkerPool(stats: () => WorkerPoolStats): () => void {\n this.poolGauges ??= this.createPoolGauges();\n const { size, active, idle, waiting } = this.poolGauges;\n const observables = [size, active, idle, waiting];\n const callback: BatchObservableCallback = (result) => {\n const current = stats();\n result.observe(size, current.size);\n result.observe(active, current.active);\n result.observe(idle, current.idle);\n result.observe(waiting, current.waiting);\n };\n this.meter.addBatchObservableCallback(callback, observables);\n return () =>\n this.meter.removeBatchObservableCallback(callback, observables);\n }\n\n // Runs admitted and waiting across workflows, and the loop that admits them.\n observeDispatcher(\n stats: () => { inFlight: number; waiting: number; utilization: number },\n ): () => void {\n // Created once: a replaced runtime re-observes the same instruments.\n this.dispatcherGauges ??= {\n inFlight: this.meter.createObservableGauge(\"workflow.runs.in_flight\", {\n description: \"Runs admitted and not yet finished\",\n unit: \"{run}\",\n }),\n waiting: this.meter.createObservableGauge(\"workflow.runs.waiting\", {\n description: \"Runs waiting for admission across workflows\",\n unit: \"{run}\",\n }),\n loop: this.meter.createObservableGauge(\n \"workflow.host.event_loop.utilization\",\n {\n description: \"Main thread busy share over the last second\",\n unit: \"1\",\n },\n ),\n };\n const { inFlight, waiting, loop } = this.dispatcherGauges;\n const observables = [inFlight, waiting, loop];\n const callback: BatchObservableCallback = (result) => {\n const current = stats();\n result.observe(inFlight, current.inFlight);\n result.observe(waiting, current.waiting);\n result.observe(loop, current.utilization);\n };\n this.meter.addBatchObservableCallback(callback, observables);\n return () =>\n this.meter.removeBatchObservableCallback(callback, observables);\n }\n\n private createPoolGauges() {\n const gauge = (name: string, description: string) =>\n this.meter.createObservableGauge(name, { description, unit: \"{worker}\" });\n return {\n size: gauge(\"workflow.worker.pool.size\", \"Most run children\"),\n active: gauge(\n \"workflow.worker.pool.active\",\n \"Children serving a request\",\n ),\n idle: gauge(\"workflow.worker.pool.idle\", \"Warm children waiting\"),\n waiting: gauge(\n \"workflow.worker.pool.waiting\",\n \"Requests waiting for a child\",\n ),\n };\n }\n}\n\n// The child is piece code: only the phases it is built to report, well-formed,\n// become spans and metric labels.\nconst WORKER_PHASES = new Set([\n \"piece.load\",\n \"reactor.open\",\n \"models\",\n \"action\",\n]);\nconst WORKER_ATTRIBUTES: Record<string, \"boolean\" | \"string\"> = {\n \"piece.cached\": \"boolean\",\n \"document.type\": \"string\",\n};\nconst MAX_ATTRIBUTE_LENGTH = 256;\n\nfunction finite(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value)\n ? value\n : undefined;\n}\n\nfunction knownPhase(phase: unknown): phase is WorkerPhaseTiming {\n if (typeof phase !== \"object\" || phase === null) return false;\n const { name, start, end, parent } = phase as Partial<WorkerPhaseTiming>;\n return (\n typeof name === \"string\" &&\n WORKER_PHASES.has(name) &&\n (parent === undefined || WORKER_PHASES.has(parent)) &&\n finite(start) !== undefined &&\n finite(end) !== undefined &&\n end! >= start!\n );\n}\n\nfunction phaseAttributes(attributes: unknown): Attributes | undefined {\n if (typeof attributes !== \"object\" || attributes === null) return undefined;\n const kept: Attributes = {};\n for (const [key, type] of Object.entries(WORKER_ATTRIBUTES)) {\n const value = (attributes as Record<string, unknown>)[key];\n if (typeof value !== type) continue;\n kept[key] =\n typeof value === \"string\"\n ? value.slice(0, MAX_ATTRIBUTE_LENGTH)\n : (value as boolean);\n }\n return Object.keys(kept).length > 0 ? kept : undefined;\n}\n\nconst MB = 2 ** 20;\n\n// The child's memory as it answered, in MB, on the request span.\nfunction workerMemory(memory: unknown): Attributes {\n if (typeof memory !== \"object\" || memory === null) return {};\n const attributes: Attributes = {};\n for (const [key, name] of [\n [\"rss\", \"worker.memory.rss_mb\"],\n [\"heapUsed\", \"worker.memory.heap_used_mb\"],\n [\"heapTotal\", \"worker.memory.heap_total_mb\"],\n [\"external\", \"worker.memory.external_mb\"],\n ] as const) {\n const bytes = finite((memory as Record<string, unknown>)[key]);\n if (bytes !== undefined) attributes[name] = bytes / MB;\n }\n return attributes;\n}\n\n// Piece trigger kinds embed author-typed names; metrics keep only \"piece\".\nfunction metricTriggerKind(triggerKind: string): string {\n return triggerKind.startsWith(\"piece:\") ? \"piece\" : triggerKind;\n}\n\n// A step's piece as a metric attribute: the name only once it resolved to a\n// real piece, since a workflow author can type any string into the document.\nfunction metricPieceName(\n step: { pieceName: string },\n resolution: BlockResolution | undefined,\n): string {\n return resolution?.resolved && resolution.match !== \"missing\"\n ? step.pieceName\n : \"unresolved\";\n}\n\n// One `workflow.step` span per executed block, and its duration by piece.\nexport function tracedSteps(\n executor: BlockExecutor,\n telemetry: WorkflowTelemetry,\n): BlockExecutor {\n return {\n execute(execution) {\n const { step } = execution;\n const started = performance.now();\n let status = \"FAILED\";\n let resolution: BlockResolution | undefined;\n return telemetry\n .span(\n \"workflow.step\",\n {\n \"step.id\": step.id,\n \"step.key\": step.key,\n \"piece.name\": step.pieceName,\n \"action.name\": step.actionName,\n },\n async (span) => {\n try {\n const result = await executor.execute(execution);\n resolution = result.resolution;\n status = \"SUCCEEDED\";\n const version = resolution?.resolved?.version;\n if (version) span.setAttribute(\"piece.version\", version);\n return result;\n } catch (error) {\n resolution = resolutionOf(error);\n throw error;\n }\n },\n )\n .finally(() => {\n telemetry.recordStep(\n performance.now() - started,\n metricPieceName(step, resolution),\n status,\n );\n });\n },\n };\n}\n\nexport function failSpan(span: Span, error: unknown): void {\n span.recordException(error instanceof Error ? error : String(error));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n}\n\n// Every promise-returning method of `target` runs in a span parented on `parent`.\nexport function tracedMethods<T extends object>(\n target: T,\n telemetry: WorkflowTelemetry,\n prefix: string,\n parent: Context,\n): T {\n return new Proxy(target, {\n get(object, property, receiver) {\n const value = Reflect.get(object, property, receiver) as unknown;\n if (typeof value !== \"function\" || typeof property !== \"string\") {\n return value;\n }\n const phase = `${prefix}.${property}`;\n return (...args: unknown[]) =>\n telemetry.tracer.startActiveSpan(\n `workflow.${phase}`,\n {},\n parent,\n (span) => {\n const started = performance.now();\n const end = (error?: unknown) => {\n if (error !== undefined) failSpan(span, error);\n span.end();\n telemetry.recordPhase(phase, performance.now() - started);\n };\n let result: unknown;\n try {\n result = (value as (...a: unknown[]) => unknown).apply(\n object,\n args,\n );\n } catch (error) {\n end(error);\n throw error;\n }\n // A synchronous method answers synchronously.\n if (!(result instanceof Promise)) {\n end();\n return result;\n }\n return result.then(\n (resolved: unknown) => {\n end();\n return resolved;\n },\n (error: unknown) => {\n end(error);\n throw error;\n },\n );\n },\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2KA,SAAgB,WAAW,OAA0C;CAGnE,QADE,OAAO,MAAM,YAAY,aAAa,MAAM,QAAQ,IAAI,MAAM,YAC9C,CAAC;AACrB;AAGA,SAAgB,YAAY,OAA2C;CAGrE,QADE,OAAO,MAAM,aAAa,aAAa,MAAM,SAAS,IAAI,MAAM,aAC/C,CAAC;AACtB;;;;ACrKA,MAAa,qBAAqB;AAalC,MAAM,sCAA2C,IAAI,IAAI,CACvD,sBACF,CAAC;AAED,SAAS,MAAM,OAAyB;CACtC,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,OAAQ,MAA6B;CAC3C,OAAO,OAAO,SAAS,YAAY,oBAAoB,IAAI,IAAI;AACjE;AAEA,SAAS,QAAQ,OAAyB;CACxC,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAQ,MAAkC,wBAAwB;AACpE;;;;;;;;;AAUA,SAAgB,qBAAqB,OAAyB;CAC5D,IAAI,QAAQ,KAAK,KAAK,MAAM,K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MAAuC,MAC/C,QACA,IACF;GACF,SAAS,OAAO;IACd,IAAI,KAAK;IACT,MAAM;GACR;GAEA,IAAI,EAAE,kBAAkB,UAAU;IAChC,IAAI;IACJ,OAAO;GACT;GACA,OAAO,OAAO,MACX,aAAsB;IACrB,IAAI;IACJ,OAAO;GACT,IACC,UAAmB;IAClB,IAAI,KAAK;IACT,MAAM;GACR,CACF;EACF,CACF;CACJ,EACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"telemetry-CBZzPM22.js","names":["logger","gunzip","gunzipCb","isRecord","pkg.version","CORE_PIECE_NAME","logger","otelContext"],"sources":["../src/pieces/activepieces/types.ts","../src/pieces/activepieces/indeterminate.ts","../src/pieces/activepieces/registry-source.ts","../src/pieces/activepieces/fetch.ts","../src/pieces/activepieces/unsupported.ts","../src/pieces/activepieces/descriptor.ts","../src/pieces/activepieces/resolver.ts","../src/pieces/activepieces/worker/json-safe.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/worker/host-call.ts","../src/pieces/activepieces/context/limits.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/trigger.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/redact.ts","../src/pieces/activepieces/worker/reactor-rpc.ts","../src/pieces/activepieces/worker/transport.ts","../src/pieces/activepieces/worker/timings.ts","../src/pieces/activepieces/worker/host.ts","../src/pieces/activepieces/worker/pool.ts","../src/pieces/engine/types.ts","../src/pieces/engine/secrets.ts","../src/pieces/engine/expressions.ts","../src/pieces/core/branch-operators.ts","../src/pieces/engine/step-input.ts","../src/pieces/engine/connections.ts","../src/pieces/engine/attachment-cache.ts","../src/pieces/core/hints.ts","../src/pieces/core/actions.ts","../src/pieces/core/triggers.ts","../package.json","../src/pieces/core/version.ts","../src/pieces/core/index.ts","../src/pieces/builtin.ts","../src/pieces/engine/resolution.ts","../src/pieces/engine/blocks.ts","../src/pieces/engine/retry.ts","../src/pieces/engine/dynamic-props.ts","../src/pieces/engine/canonical.ts","../src/pieces/engine/coordinator.ts","../src/reactor/piece-registry.ts","../src/telemetry.ts"],"sourcesContent":["// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<\n DropdownOption<unknown>,\n \"label\" | \"value\"\n> &\n Partial<Pick<DropdownOption<unknown>, \"description\" | \"icon\">>;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<\n BasePropertySchema,\n \"displayName\" | \"description\" | \"placeholder\" | \"advanced\"\n >\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // FILE: hand the piece a stream instead of the bytes.\n streaming?: boolean;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n // Layout and control hints, each read off only the types that declare it.\n width?: string;\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // The core piece's form hints; see PiecePropDescriptor.\n showWhen?: unknown;\n emptyChoice?: unknown;\n };\n\n// Widened from PropertyGroupDisplay: tabs | section | summary | builder | footer.\nexport interface ApPropertyGroup {\n key?: string;\n display?: string;\n label?: string;\n description?: string;\n icon?: string;\n props?: string[];\n}\n\nexport interface ApErrorHandlingOption {\n defaultValue?: boolean;\n hide?: boolean;\n}\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n propertyGroups?: ApPropertyGroup[];\n // READ | SEARCH | WRITE | DESTRUCTIVE, widened for the cross-bundle reason.\n classification?: string;\n errorHandlingOptions?: {\n retryOnFailure?: ApErrorHandlingOption;\n continueOnFailure?: ApErrorHandlingOption;\n };\n // Output ports, read only off a piece the host runs in process.\n ports?: unknown;\n // \"read\" | \"write\"; anything else reads as undeclared.\n requireReactor?: unknown;\n run: (ctx: unknown) => Promise<unknown>;\n // Called instead of run by a single-step test.\n test?: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: unknown;\n requireReactor?: unknown;\n props?: Record<string, ApProperty>;\n propertyGroups?: ApPropertyGroup[];\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n // Widened from WebhookRenewConfiguration: CRON | NONE.\n renewConfiguration?: { strategy?: string; cronExpression?: string };\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n deprecated?: boolean;\n // An array when the piece offers several auth methods.\n auth?: ApProperty | ApProperty[];\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","// \"Nobody knows whether that write landed\", as a property an error carries.\n//\n// A step whose host call wrote something and then did not get an answer in\n// time is neither a success nor a failure, and reporting it as FAILED is a\n// claim nobody can stand behind — which is what the 10s host-call cap was\n// doing to a reactor dispatch under load (backlog item 6).\n//\n// The marker is an ENUMERABLE OWN PROPERTY rather than a class, because the\n// error is usually thrown in the forked child and reaches the coordinator as a\n// `SerializedPieceError`: a name, a message, and the error's own enumerable\n// properties. The class does not survive; the property does.\n//\n// The reactor RPC keeps only an error's name and message, so a reactor job\n// still unfinished at the step deadline is recognised by its name.\nimport { ReactorJobPendingError } from \"@powerhousedao/pieces-framework\";\n\n/** The property name, so both sides spell it once. */\nexport const INDETERMINATE_FLAG = \"indeterminate\";\n\n/** Marks an error as indeterminate, in place. */\nexport function markIndeterminate<T extends Error>(error: T): T {\n Object.defineProperty(error, INDETERMINATE_FLAG, {\n value: true,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n return error;\n}\n\nconst INDETERMINATE_NAMES: ReadonlySet<string> = new Set([\n ReactorJobPendingError,\n]);\n\nfunction named(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n const name = (value as { name?: unknown }).name;\n return typeof name === \"string\" && INDETERMINATE_NAMES.has(name);\n}\n\nfunction flagged(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return false;\n return (value as Record<string, unknown>)[INDETERMINATE_FLAG] === true;\n}\n\n/**\n * Whether this error means \"the write may have landed\".\n *\n * Three places to look, in the order the error can reach us: the error itself\n * (thrown in the reactor process), the `properties` record of the\n * `SerializedPieceError` a `PieceWorkerError` carries (thrown in the child),\n * and the `cause` chain (a piece that wrapped it).\n */\nexport function isIndeterminateError(error: unknown): boolean {\n if (flagged(error) || named(error)) return true;\n const serialized = (\n error as { serialized?: { name?: unknown; properties?: unknown } }\n )?.serialized;\n if (flagged(serialized?.properties) || named(serialized)) return true;\n const cause = (error as { cause?: unknown })?.cause;\n return (\n cause !== undefined && cause !== error && (flagged(cause) || named(cause))\n );\n}\n","// A Powerhouse registry as a source of pieces: where this runtime reads piece\n// metadata and fetches piece code.\n\n// It serves the same three shapes cloud.activepieces.com and its CDN do — a\n// list, one piece's detail, a bundle tarball — at its own paths.\n\n// The registry is the one the host already installs packages from. A package\n// installed from it ships pieces that run in the worker with the same reach, so\n// a bundle fetched from it is no more trusted than one that arrived inside a\n// package; the trust boundary is the registry, and it is already drawn.\nimport { childLogger } from \"document-model\";\n\nconst logger = childLogger([\"workflow\", \"piece-registry\"]);\n\nexport interface PieceRegistrySource {\n /** Origin the piece endpoints hang off, without a trailing slash. */\n baseUrl: string;\n /** The catalog, in cloud.activepieces.com's list shape. */\n catalogUrl(suggestions?: boolean): string;\n /** One piece's detail, in the shape their piece endpoint answers with. */\n pieceUrl(name: string): string;\n /** The bundle; a folder per piece name keeps scoped names distinct. */\n tarballUrl(name: string, version: string): string;\n}\n\nfunction source(baseUrl: string): PieceRegistrySource {\n return {\n baseUrl,\n catalogUrl: (suggestions) =>\n suggestions\n ? `${baseUrl}/pieces?suggestionType=ACTION_AND_TRIGGER`\n : `${baseUrl}/pieces`,\n // Encoded whole, slash included: a scoped name is one path segment to the\n // registry's route, not two.\n pieceUrl: (name) => `${baseUrl}/pieces/${encodeURIComponent(name)}`,\n tarballUrl: (name, version) =>\n `${baseUrl}/-/pieces/bundled/${name}/${version}.tgz`,\n };\n}\n\n// Set by the host at composition from the registry it resolved for package\n// installs; absent on a host that installs no packages from one, and nothing\n// changes.\nlet configured: PieceRegistrySource | undefined;\n\nexport function setPieceRegistryUrl(url: string | undefined): void {\n const trimmed = url?.trim().replace(/\\/+$/, \"\") ?? \"\";\n if (trimmed === \"\") {\n configured = undefined;\n return;\n }\n if (configured?.baseUrl === trimmed) return;\n configured = source(trimmed);\n logger.info(`Pieces may be fetched from ${configured.baseUrl}`);\n}\n\n/** The registry at `baseUrl`, whichever one this host is configured with. */\nexport function pieceRegistrySourceAt(baseUrl: string): PieceRegistrySource {\n return source(baseUrl.replace(/\\/+$/, \"\"));\n}\n\nexport function pieceRegistrySource(): PieceRegistrySource | undefined {\n return configured;\n}\n","import { execFile } from \"node:child_process\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gunzip as gunzipCb } from \"node:zlib\";\nimport {\n pieceRegistrySource,\n pieceRegistrySourceAt,\n type PieceRegistrySource,\n} from \"./registry-source.js\";\n\nconst gunzip = promisify(gunzipCb);\n\n// Mirrors their pieceBundle.resolve(): CDN bundle when served, else the npm\n// tarball. Tarballs are immutable per (name, version), so the cache never expires.\nconst DEFAULT_CDN_PIECES_URL = \"https://cdn.activepieces.com/pieces/bundled\";\nconst DEFAULT_NPM_REGISTRY_URL = \"https://registry.npmjs.org\";\n\nlet cdnPiecesUrl = DEFAULT_CDN_PIECES_URL;\nlet npmRegistryUrl = DEFAULT_NPM_REGISTRY_URL;\n\n// Host and test seam: the public CDN and npm registry a piece is fetched from.\nexport function setPublicPieceSources(sources: {\n cdnUrl?: string;\n npmRegistryUrl?: string;\n}): void {\n const trim = (url: string) => url.trim().replace(/\\/+$/, \"\");\n cdnPiecesUrl = sources.cdnUrl ? trim(sources.cdnUrl) : DEFAULT_CDN_PIECES_URL;\n npmRegistryUrl = sources.npmRegistryUrl\n ? trim(sources.npmRegistryUrl)\n : DEFAULT_NPM_REGISTRY_URL;\n}\n\nexport function npmRegistryBaseUrl(): string {\n return npmRegistryUrl;\n}\n\nexport function cdnTarballUrl(name: string, version: string): string {\n return `${cdnPiecesUrl}/${name.replace(\"/\", \"-\")}-${version}.tgz`;\n}\n\nexport function npmTarballUrl(name: string, version: string): string {\n const unscoped = name.startsWith(\"@\") ? name.split(\"/\")[1] : name;\n return `${npmRegistryUrl}/${name}/-/${unscoped}-${version}.tgz`;\n}\n\n// name/version come from a workflow step's pieceName and pieceVersion,\n// unconstrained strings.\nconst NPM_NAME_RE = /^(@[a-z0-9][a-z0-9-_.]*\\/)?[a-z0-9][a-z0-9-_.]*$/;\nconst NPM_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/;\n\nfunction assertValidPackageCoordinate(name: string, version: string): void {\n if (!NPM_NAME_RE.test(name)) {\n throw new Error(`Invalid piece package name: ${name}`);\n }\n if (!NPM_VERSION_RE.test(version)) {\n throw new Error(`Invalid piece package version: ${version}`);\n }\n}\n\n// Belt-and-suspenders: the path we're about to rm/rename must land under cacheDir.\nfunction assertWithinCacheDir(dir: string, cacheDir: string): void {\n const root = path.resolve(cacheDir);\n const resolved = path.resolve(dir);\n if (resolved !== root && !resolved.startsWith(root + path.sep)) {\n throw new Error(`Resolved piece cache path escapes cacheDir: ${dir}`);\n }\n}\n\nfunction readString(header: Buffer, offset: number, length: number): string {\n const slice = header.subarray(offset, offset + length);\n const nul = slice.indexOf(0);\n return slice.subarray(0, nul === -1 ? length : nul).toString(\"utf8\");\n}\n\n// Published piece bundles run a few hundred KB extracted; the cap is well clear\n// of that and bounds what a hostile or corrupt tarball can inflate to.\nconst MAX_EXTRACTED_BYTES = 64 * 1024 * 1024;\n\n// Caps the compressed transfer itself, before gunzip ever runs — the decompressed\n// cap above does nothing for a huge (not necessarily bomb-like) response body.\nconst MAX_COMPRESSED_BYTES = 64 * 1024 * 1024;\n\n// Minimal ustar extraction: regular files only, \"package/\" root stripped.\nasync function extractTarball(tgz: Buffer, dest: string): Promise<void> {\n // Async gunzip: the sync one blocks the reactor's event loop for every\n // request, not just this one, and inflation is unbounded without maxOutputLength.\n const tar = await gunzip(tgz, { maxOutputLength: MAX_EXTRACTED_BYTES }).catch(\n (error: unknown) => {\n throw new Error(`Failed to decompress piece bundle: ${String(error)}`);\n },\n );\n let offset = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n if (header.every((byte) => byte === 0)) break;\n const name = readString(header, 0, 100);\n const prefix = readString(header, 345, 155);\n const size = parseInt(readString(header, 124, 12).trim() || \"0\", 8);\n const type = String.fromCharCode(header[156]);\n offset += 512;\n const isFile = type === \"0\" || type === \"\\0\" || type === \"\";\n if (isFile && size >= 0) {\n const full = prefix ? `${prefix}/${name}` : name;\n const rel = full.replace(/^[^/]+\\//, \"\");\n const target = path.resolve(dest, rel);\n // Guard against path traversal from a hostile tarball.\n if (rel && target.startsWith(path.resolve(dest) + path.sep)) {\n await mkdir(path.dirname(target), { recursive: true });\n await writeFile(target, tar.subarray(offset, offset + size));\n }\n }\n offset += Math.ceil(size / 512) * 512;\n }\n}\n\nexport interface FetchPieceBundleOptions {\n name: string;\n version: string;\n cacheDir: string;\n timeoutMs?: number;\n // Where a piece an installed reactor package ships is served, when the\n // package itself came from a registry rather than this disk.\n entryUrl?: string;\n // How long the install of a bundle's declared dependencies may run, for the\n // few that declare any. Bounds a hung registry rather than budgeting work.\n installTimeoutMs?: number;\n // The only tarball sources to try, in order; every one when unset.\n sources?: readonly BundleSource[];\n // Cache subdirectory, so copies from different sources never alias.\n cacheScope?: string;\n}\n\n/** Where a bundle came from, \"cache\" being a copy one of the others left. */\nexport type BundleSource = \"package\" | \"registry\" | \"cdn\" | \"npm\";\n\nexport interface FetchedBundle {\n dir: string;\n source: BundleSource | \"cache\";\n // What the bundle's own manifest declares. Empty for 739 of the 760\n // published pieces, which is the path that costs nothing.\n dependencies: Record<string, string>;\n // Whether those declarations were installed beside it, rather than the\n // bundle being loaded straight out of its extraction.\n installed: boolean;\n}\n\n// Bounds the transfer before gunzip: rejects an over-limit Content-Length up\n// front, else tracks a running total as the body streams in.\nasync function readBoundedBody(\n response: Response,\n url: string,\n): Promise<Buffer> {\n const declared = response.headers.get(\"content-length\");\n if (declared && Number(declared) > MAX_COMPRESSED_BYTES) {\n throw new Error(\n `${url} exceeds the ${MAX_COMPRESSED_BYTES}-byte compressed size cap (Content-Length: ${declared})`,\n );\n }\n if (!response.body) return Buffer.from(await response.arrayBuffer());\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > MAX_COMPRESSED_BYTES) {\n await reader.cancel();\n throw new Error(\n `${url} exceeds the ${MAX_COMPRESSED_BYTES}-byte compressed size cap`,\n );\n }\n chunks.push(value);\n }\n return Buffer.concat(chunks);\n}\n\n// A Powerhouse registry this deployment allowed comes first, so a piece it\n// serves is not shadowed by an Activepieces piece of the same name.\nfunction tarballSources(\n name: string,\n version: string,\n only?: readonly BundleSource[],\n registry = pieceRegistrySource(),\n): { source: BundleSource; url: string }[] {\n const all = allTarballSources(name, version, registry);\n return only ? all.filter(({ source }) => only.includes(source)) : all;\n}\n\nfunction allTarballSources(\n name: string,\n version: string,\n registry: PieceRegistrySource | undefined,\n): { source: BundleSource; url: string }[] {\n return [\n ...(registry\n ? [\n {\n source: \"registry\" as const,\n url: registry.tarballUrl(name, version),\n },\n ]\n : []),\n { source: \"cdn\" as const, url: cdnTarballUrl(name, version) },\n { source: \"npm\" as const, url: npmTarballUrl(name, version) },\n ];\n}\n\nasync function downloadTarball(\n name: string,\n version: string,\n timeoutMs: number,\n only?: readonly BundleSource[],\n registry?: PieceRegistrySource,\n): Promise<{ tgz: Buffer; source: BundleSource }> {\n const sources = tarballSources(name, version, only, registry);\n let lastError: unknown;\n for (const { source, url } of sources) {\n try {\n const response = await fetch(url, {\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!response.ok) {\n lastError = new Error(`${url} responded ${response.status}`);\n continue;\n }\n return { tgz: await readBoundedBody(response, url), source };\n } catch (error) {\n lastError = error;\n }\n }\n throw new Error(\n `Failed to fetch piece bundle ${name}@${version}: ${String(lastError)}`,\n );\n}\n\nasync function extractDownloadedTarball(\n name: string,\n version: string,\n timeoutMs: number,\n staging: string,\n only?: readonly BundleSource[],\n): Promise<BundleSource> {\n const { tgz, source } = await downloadTarball(name, version, timeoutMs, only);\n await extractTarball(tgz, staging);\n return source;\n}\n\n// A piece from an installed reactor package, served by the registry that\n// package came from: its manifest, then the one file the manifest names.\n\n// `ph build` leaves each piece a self-contained module with a package.json\n// beside it, so those two files are the whole bundle.\nasync function downloadPackagePiece(\n entryUrl: string,\n staging: string,\n timeoutMs: number,\n): Promise<BundleSource> {\n const base = entryUrl.slice(0, entryUrl.lastIndexOf(\"/\") + 1);\n const fetchInto = async (url: string, name: string): Promise<Buffer> => {\n const response = await fetch(url, {\n signal: AbortSignal.timeout(timeoutMs),\n });\n if (!response.ok) {\n throw new Error(`${url} responded ${response.status}`);\n }\n const body = await readBoundedBody(response, url);\n await writeFile(path.join(staging, name), body);\n return body;\n };\n await mkdir(staging, { recursive: true });\n const manifest = await fetchInto(`${base}package.json`, \"package.json\");\n const main = (JSON.parse(manifest.toString(\"utf8\")) as { main?: unknown })\n .main;\n const entry =\n typeof main === \"string\" && main !== \"\"\n ? main\n : entryUrl.slice(base.length);\n // One segment: the manifest of a built piece names a file beside itself, and\n // a path that climbs out of the staging directory is not that.\n if (entry.includes(\"/\") || entry.includes(\"\\\\\") || entry.startsWith(\".\")) {\n throw new Error(\n `Piece manifest at ${base} names an unusable main: ${entry}`,\n );\n }\n await fetchInto(`${base}${entry}`, entry);\n return \"package\";\n}\n\nfunction bundleDirFor(options: FetchPieceBundleOptions): string {\n const leaf = `${options.name.replace(\"/\", \"-\")}-${options.version}`;\n return options.cacheScope\n ? path.join(options.cacheDir, options.cacheScope, leaf)\n : path.join(options.cacheDir, leaf);\n}\n\n// Downloads and extracts a published piece bundle, returning the directory to\n// hand to loadPieceFromDir(). A cached extraction is reused, and re-checked.\nexport async function fetchPieceBundle(\n options: FetchPieceBundleOptions,\n): Promise<FetchedBundle> {\n const { name, version, cacheDir, timeoutMs = 30_000 } = options;\n assertValidPackageCoordinate(name, version);\n const dir = bundleDirFor(options);\n assertWithinCacheDir(dir, cacheDir);\n if (existsSync(path.join(dir, \"package.json\"))) {\n return {\n dir,\n source: \"cache\",\n dependencies: await readDependencies(dir),\n installed: false,\n };\n }\n\n const staging = `${dir}.tmp-${process.pid}`;\n await rm(staging, { recursive: true, force: true });\n // A piece a package ships is served as its built module, not as a tarball,\n // so it is fetched file by file rather than extracted.\n const source = options.entryUrl\n ? await downloadPackagePiece(options.entryUrl, staging, timeoutMs)\n : await extractDownloadedTarball(\n name,\n version,\n timeoutMs,\n staging,\n options.sources,\n );\n await rm(dir, { recursive: true, force: true });\n try {\n await rename(staging, dir);\n } catch (error) {\n // Concurrent fetcher won the rename; its extraction is identical.\n await rm(staging, { recursive: true, force: true });\n if (!existsSync(path.join(dir, \"package.json\"))) throw error;\n }\n return {\n dir,\n source,\n dependencies: await readDependencies(dir),\n installed: false,\n };\n}\n\n// Concurrent callers for the same bundle share one download+extract rather\n// than racing each other through it.\nconst inFlight = new Map<string, Promise<FetchedBundle>>();\n\n// The way in: a bundle arrives extracted, cached and loadable, and callers\n// that ask for the same one at the same time wait on a single fetch.\nexport async function ensurePieceBundle(\n options: FetchPieceBundleOptions,\n): Promise<FetchedBundle> {\n const key = bundleDirFor(options);\n const pending = inFlight.get(key);\n if (pending) return pending;\n // Dropped once settled, refusals included, so a later caller re-checks the\n // bundle rather than inheriting this call's answer forever.\n const started = resolveBundle(options).finally(() => inFlight.delete(key));\n inFlight.set(key, started);\n return started;\n}\n\n// 739 of the 760 published pieces declare nothing, and they take the path they\n// always took: extract, load, no package manager anywhere near it.\n\n// The rest have their declarations installed beside them, once per name and\n// version, and the refusal is what is left when that cannot be done.\nasync function resolveBundle(\n options: FetchPieceBundleOptions,\n): Promise<FetchedBundle> {\n const fetched = await fetchPieceBundle(options);\n if (Object.keys(fetched.dependencies).length === 0) return fetched;\n return installPieceBundle(options, fetched);\n}\n\n// Installs a bundle plus its declared deps into an isolated workspace, the way\n// their piece-installer does: the bundle as a file: dependency, then install.\nasync function installPieceBundle(\n options: FetchPieceBundleOptions,\n fetched: FetchedBundle,\n): Promise<FetchedBundle> {\n const { name, version, cacheDir } = options;\n const timeoutMs = options.installTimeoutMs ?? INSTALL_TIMEOUT_MS;\n const workspace = `${bundleDirFor(options)}.install`;\n assertWithinCacheDir(workspace, cacheDir);\n const dir = path.join(workspace, \"node_modules\", name);\n // Written last, so a torn install is never mistaken for a finished one.\n if (\n existsSync(path.join(workspace, INSTALL_READY_MARKER)) &&\n existsSync(path.join(dir, \"package.json\"))\n ) {\n return {\n dir,\n source: \"cache\",\n dependencies: fetched.dependencies,\n installed: true,\n };\n }\n try {\n await stageInstallWorkspace(workspace, options);\n // A package's piece installs from the registry the package came from,\n // which proxies npm; an npm piece keeps the host's own npm config.\n await runInstall(workspace, timeoutMs, packageRegistry(options)?.baseUrl);\n await writeFile(path.join(workspace, INSTALL_READY_MARKER), \"true\");\n } catch (error) {\n // Swept, so the next attempt starts clean: a half-written node_modules\n // loads worse than none at all, and more confusingly.\n await rm(workspace, { recursive: true, force: true }).catch(\n () => undefined,\n );\n throw notInstallable(name, version, fetched.dependencies, error);\n }\n return {\n dir,\n source: fetched.source,\n dependencies: fetched.dependencies,\n installed: true,\n };\n}\n\n// \"<registry>/-/cdn/<package>@<version>/<file>\" -> \"<registry>\".\nexport function registryOf(entryUrl: string): string | undefined {\n const at = entryUrl.indexOf(\"/-/cdn/\");\n return at > 0 ? entryUrl.slice(0, at) : undefined;\n}\n\n// A package's piece comes from, and installs through, the package's registry.\nfunction packageRegistry(\n options: FetchPieceBundleOptions,\n): PieceRegistrySource | undefined {\n if (!options.entryUrl) return undefined;\n const base = registryOf(options.entryUrl);\n return base ? pieceRegistrySourceAt(base) : pieceRegistrySource();\n}\n\n// The tarball, not the directory already extracted: npm symlinks a directory\n// dependency, and node resolves a symlinked module from its realpath.\n\n// That realpath is back in the cache, where the installed deps are not, so\n// the tgz is what makes npm unpack a real directory under node_modules.\nasync function stageInstallWorkspace(\n workspace: string,\n options: FetchPieceBundleOptions,\n): Promise<void> {\n const { tgz } = await downloadTarball(\n options.name,\n options.version,\n options.timeoutMs ?? 30_000,\n options.sources,\n packageRegistry(options),\n );\n await rm(workspace, { recursive: true, force: true });\n await mkdir(workspace, { recursive: true });\n await writeFile(path.join(workspace, \"bundle.tgz\"), tgz);\n await writeFile(\n path.join(workspace, \"package.json\"),\n JSON.stringify({\n name: \"piece-workspace\",\n version: \"1.0.0\",\n private: true,\n dependencies: { [options.name]: \"file:./bundle.tgz\" },\n }),\n );\n}\n\n// Enough to recognise what the bundle wants without turning the refusal into\n// a wall of text.\nconst MAX_LISTED_DEPENDENCIES = 5;\n\n// Written into the workspace once the install has finished, so a cache hit is\n// a finished install and never a torn one.\nconst INSTALL_READY_MARKER = \"ready\";\n\n// A published piece pulls a handful of packages at most; this is a bound on a\n// hung registry, not a budget. Configurable for a slow or distant mirror.\nconst INSTALL_TIMEOUT_MS =\n Number(process.env.PH_WORKFLOWS_PIECE_INSTALL_TIMEOUT_MS) || 120_000;\n\n// npm, and only npm. It is on every image that can run this reactor, which bun\n// is not, and one package manager is one thing to keep --ignore-scripts true of.\n\n// Activepieces use bun and it is much faster, but the install is cached per\n// name and version and off every hot path, so what it would buy is one-off.\nfunction installCommand(registry?: string): {\n file: string;\n args: string[];\n shell: boolean;\n} {\n // Windows installs npm as npm.cmd, which only a shell can spawn.\n const windows = process.platform === \"win32\";\n return {\n file: windows ? \"npm.cmd\" : \"npm\",\n // --ignore-scripts is not optional and has no switch to turn it off: it is\n // what makes installing a third party's package at runtime defensible.\n args: [\n \"install\",\n \"--ignore-scripts\",\n \"--no-audit\",\n \"--no-fund\",\n \"--omit=dev\",\n \"--loglevel=error\",\n ...(registry ? [`--registry=${registry}/`] : []),\n ],\n shell: windows,\n };\n}\n\nasync function runInstall(\n cwd: string,\n timeoutMs: number,\n registry?: string,\n): Promise<void> {\n const { file, args, shell } = installCommand(registry);\n await new Promise<void>((resolve, reject) => {\n execFile(\n file,\n args,\n // No bunfig to inherit: npm reads the host's config, and only the\n // registry above overrides it.\n { cwd, timeout: timeoutMs, shell, windowsHide: true },\n (error, _stdout, stderr) => {\n if (!error) return resolve();\n const killed = (error as { killed?: boolean }).killed === true;\n // npm's \"a complete log of this run\" line points at a file nobody\n // reading a reactor log can open; the cause above it is the message.\n const reported = stderr\n .split(\"\\n\")\n .filter((line) => !line.includes(\"A complete log of this run\"))\n .join(\"\\n\")\n .trim();\n reject(\n new Error(\n killed\n ? `timed out after ${timeoutMs}ms`\n : reported || error.message,\n ),\n );\n },\n );\n });\n}\n\n// What is left when a bundle names code it does not carry and that code could\n// not be fetched: the piece is unloadable, and this says what was tried.\nexport class PieceNotInstallableError extends Error {\n constructor(\n readonly packageName: string,\n readonly version: string,\n readonly dependencies: Record<string, string>,\n readonly cause: unknown,\n ) {\n const declared = Object.keys(dependencies);\n const listed = declared\n .slice(0, MAX_LISTED_DEPENDENCIES)\n .map((dep) => `${dep}@${dependencies[dep]}`);\n const rest = declared.length - listed.length;\n const count =\n declared.length === 1\n ? \"a dependency\"\n : `${declared.length} dependencies`;\n super(\n `Piece bundle ${packageName}@${version} carries ${count} it does not ` +\n `bundle (${listed.join(\", \")}${rest > 0 ? `, and ${rest} more` : \"\"}), ` +\n `and installing them here failed: ${reasonOf(cause)}. ` +\n `The install runs once per version, with lifecycle scripts disabled, so ` +\n `a dependency that builds or downloads on install cannot be prepared ` +\n `this way. Check that this reactor can reach an npm registry, or run a ` +\n `piece whose bundle inlines what it needs.`,\n );\n this.name = \"PieceNotInstallableError\";\n }\n}\n\nfunction reasonOf(cause: unknown): string {\n return cause instanceof Error ? cause.message : String(cause);\n}\n\nfunction notInstallable(\n name: string,\n version: string,\n dependencies: Record<string, string>,\n cause: unknown,\n): PieceNotInstallableError {\n return new PieceNotInstallableError(name, version, dependencies, cause);\n}\n\nasync function readDependencies(dir: string): Promise<Record<string, string>> {\n const raw = await readFile(path.join(dir, \"package.json\"), \"utf8\");\n const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> };\n return pkg.dependencies ?? {};\n}\n","import { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\nimport { Cron } from \"croner\";\n\n// Piece features this engine cannot run. Read off a loaded piece or off its\n// published listing alike, since both carry auth and triggers as data.\nconst ISSUES_URL = \"https://github.com/powerhouse-inc/powerhouse/issues/\";\n\nexport interface UnsupportedFeature {\n feature: string;\n issue: number;\n // \"<feature> is not supported yet (<issue url>)\", what a listing shows.\n reason: string;\n}\n\nfunction unsupported(feature: string, issue: number): UnsupportedFeature {\n return {\n feature,\n issue,\n reason: `${feature} is not supported yet (${ISSUES_URL}${issue})`,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// A piece's auth, from the bundle or the listing. With several methods the\n// piece runs if any one does; the connection picks which.\nexport function unsupportedAuth(auth: unknown): UnsupportedFeature | undefined {\n if (Array.isArray(auth)) {\n const reasons = auth.map(unsupportedMethod);\n return reasons.some((reason) => reason === undefined)\n ? undefined\n : reasons[0];\n }\n return unsupportedMethod(auth);\n}\n\n// The method a connection of `type` signs in with: the piece's only auth,\n// or the entry of that type among several (upstream's getAuthPropertyForValue).\nexport function authMethodFor(auth: unknown, type: unknown): unknown {\n if (!Array.isArray(auth)) return auth;\n return auth.find((entry) => isRecord(entry) && entry.type === type);\n}\n\nfunction unsupportedMethod(auth: unknown): UnsupportedFeature | undefined {\n if (!isRecord(auth)) return undefined;\n if (auth.type === \"OAUTH2\" && auth.grantType === \"client_credentials\") {\n return unsupported(\"OAuth2 client credentials\", 3091);\n }\n if (auth.type === \"OIDC\") return unsupported(\"OIDC auth\", 3091);\n if (auth.type === \"CUSTOM_AUTH\" && auth.refresh != null) {\n return unsupported(\"CustomAuth refresh\", 3091);\n }\n return undefined;\n}\n\n// A piece trigger; the core piece's triggers are fed by the host and never pass here.\nexport function unsupportedTrigger(trigger: {\n type?: unknown;\n renewConfiguration?: unknown;\n}): UnsupportedFeature | undefined {\n if (trigger.type === \"MANUAL\") {\n return unsupported(\"TriggerStrategy.MANUAL\", 3091);\n }\n const strategy = checkTriggerStrategy(trigger.type);\n if (\"issue\" in strategy) {\n const issue = trigger.type === \"APP_WEBHOOK\" ? 3081 : 3091;\n return {\n feature: `TriggerStrategy ${String(trigger.type)}`,\n issue,\n reason: `${strategy.issue} (${ISSUES_URL}${issue})`,\n };\n }\n const problem = renewProblem(trigger.renewConfiguration);\n if (problem) {\n return {\n feature: \"renewConfiguration\",\n issue: 3090,\n reason: `renewConfiguration ${problem} (${ISSUES_URL}3090)`,\n };\n }\n return undefined;\n}\n\n// A subscription the supervisor renews on a UTC cron by calling onRenew.\nexport interface TriggerRenew {\n strategy: \"CRON\";\n cronExpression: string;\n}\n\nfunction cronFires(cron: string): boolean {\n try {\n return (\n new Cron(cron, { timezone: \"UTC\", legacyMode: false }).nextRun() !== null\n );\n } catch {\n return false;\n }\n}\n\n// createTrigger fills in { strategy: \"NONE\" } for every trigger.\nfunction renewProblem(renew: unknown): string | undefined {\n if (renew === undefined || renew === null) return undefined;\n if (!isRecord(renew)) return \"is not an object\";\n if (renew.strategy === \"NONE\") return undefined;\n if (renew.strategy !== \"CRON\") {\n return `strategy ${String(renew.strategy)} is not supported`;\n }\n const cron = renew.cronExpression;\n if (typeof cron !== \"string\" || !cronFires(cron)) {\n return `cron ${JSON.stringify(cron)} is invalid`;\n }\n return undefined;\n}\n\n// The trigger's renewal, when it declares a valid CRON one.\nexport function triggerRenew(trigger: {\n renewConfiguration?: unknown;\n}): TriggerRenew | undefined {\n const renew = trigger.renewConfiguration;\n if (!isRecord(renew) || renew.strategy !== \"CRON\") return undefined;\n if (renewProblem(renew)) return undefined;\n return { strategy: \"CRON\", cronExpression: renew.cronExpression as string };\n}\n\nexport class UnsupportedPieceFeatureError extends Error {\n readonly feature: string;\n readonly issue: number;\n\n constructor(subject: string, unsupportedFeature: UnsupportedFeature) {\n super(`${subject}: ${unsupportedFeature.reason}`);\n this.name = \"UnsupportedPieceFeatureError\";\n this.feature = unsupportedFeature.feature;\n this.issue = unsupportedFeature.issue;\n }\n}\n","import type { RequireReactor } from \"@powerhousedao/pieces-framework\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApPropertyType,\n type ApDropdownOption,\n type ApPropertyGroup,\n type ApTrigger,\n type ApTriggerStrategy,\n} from \"./types.js\";\nimport {\n triggerRenew,\n unsupportedAuth,\n unsupportedTrigger,\n type TriggerRenew,\n type UnsupportedFeature,\n} from \"./unsupported.js\";\n\nexport interface PiecePropDescriptor {\n name: string;\n displayName: string;\n description?: string;\n placeholder?: string;\n type: ApPropertyType;\n required: boolean;\n defaultValue?: unknown;\n // STATIC_DROPDOWN choices, extracted so the editor needs no runtime call.\n staticOptions?: ApDropdownOption[];\n // True when the prop carries a design-time resolver (DROPDOWN options() / DYNAMIC props()).\n hasDynamicResolver: boolean;\n // Synthesised domain-provider id: activepieces:<pkg>#<action>.<prop> (doc 08 §6.3).\n // Only top-level props get one; nested resolvers are not addressable yet.\n dynamicResolverId?: string;\n // Sibling prop names whose values feed the resolver; the editor re-runs\n // it when any of them changes.\n refreshers?: string[];\n // Nested shape: an ARRAY item's fields, or the props a DYNAMIC resolver\n // produced (see describeProperties). OBJECT props are free-form and carry none.\n properties?: PiecePropDescriptor[];\n // Activepieces' layout hint: rendered in the collapsed advanced section.\n advanced?: boolean;\n // Layout and control hints (see describeHints); absent when not declared.\n width?: \"half\" | \"full\";\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // A STATIC_DROPDOWN's own state, beside its options.\n staticDisabled?: boolean;\n staticPlaceholder?: string;\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport interface PiecePropertyGroupDescriptor {\n key: string;\n display: string;\n label?: string;\n description?: string;\n icon?: string;\n props: string[];\n}\n\nexport interface PieceErrorHandlingDescriptor {\n retryOnFailure?: { defaultValue?: boolean; hide?: boolean };\n continueOnFailure?: { defaultValue?: boolean; hide?: boolean };\n}\n\nexport interface PieceActionDescriptor {\n name: string;\n displayName: string;\n description?: string;\n // UI metadata only — not a credential contract (spike finding).\n requireAuth: boolean;\n // The reactor access the step asks for; absent when it asks for none.\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n // Output ports the step can leave on; the editor draws only these.\n ports: readonly string[];\n // Carried verbatim: it is what the expression picker builds a later step's\n // field list from, and a package piece has no published listing to read.\n outputSchema?: unknown;\n // Orders the action picker, so a package piece that declares it must be\n // ordered by it too rather than counting as unset.\n audience?: string;\n propertyGroups?: PiecePropertyGroupDescriptor[];\n classification?: string;\n errorHandlingOptions?: PieceErrorHandlingDescriptor;\n}\n\nexport interface PieceTriggerDescriptor {\n name: string;\n displayName: string;\n description?: string;\n strategy: ApTriggerStrategy;\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: string;\n requireAuth: boolean;\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n ports: readonly string[];\n propertyGroups?: PiecePropertyGroupDescriptor[];\n outputSchema?: unknown;\n hasSampleData: boolean;\n // The sample itself, not just whether there is one: a trigger that declares\n // no outputSchema is read for its shape instead.\n sampleData?: unknown;\n // How the sender proves the endpoint exists before it will register it.\n // Absent when the trigger declares no handshake, or declares NONE.\n handshake?: { strategy: string; paramName?: string };\n // When the provider's subscription must be renewed; absent for NONE.\n renew?: TriggerRenew;\n // A trigger feature the engine cannot run; the piece's own is on the piece.\n unsupported?: UnsupportedFeature;\n}\n\nexport interface PieceAuthDescriptor {\n type: ApPropertyType;\n displayName?: string;\n description?: string;\n required?: boolean;\n // CUSTOM_AUTH's own fields. Without them a connection form has nothing to\n // ask for, which is what a piece read from a package rather than a published\n // listing would otherwise leave the editor with.\n props?: PiecePropDescriptor[];\n // OAUTH2 only: where and how the provider signs a user in.\n oauth2?: OAuth2MethodDescriptor;\n // Set when this engine can't sign in this way (OIDC, for one).\n unsupported?: UnsupportedFeature;\n}\n\nexport interface OAuth2MethodDescriptor {\n // May hold `{prop}` placeholders, filled from the connection's props.\n authUrl: string;\n tokenUrl: string;\n scope: string[];\n prompt?: \"none\" | \"consent\" | \"login\" | \"omit\";\n pkce?: boolean;\n pkceMethod?: \"plain\" | \"S256\";\n authorizationMethod?: \"HEADER\" | \"BODY\";\n grantType?: string;\n // Extra authorize-URL parameters, e.g. access_type=offline.\n extra?: Record<string, string>;\n}\n\nfunction describeOAuth2(\n raw: Record<string, unknown>,\n): OAuth2MethodDescriptor | undefined {\n if (typeof raw.authUrl !== \"string\" || typeof raw.tokenUrl !== \"string\") {\n return undefined;\n }\n const strings = (value: unknown) =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n const extra =\n raw.extra && typeof raw.extra === \"object\"\n ? Object.fromEntries(\n Object.entries(raw.extra).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n )\n : undefined;\n return {\n authUrl: raw.authUrl,\n tokenUrl: raw.tokenUrl,\n scope: strings(raw.scope),\n ...(typeof raw.prompt === \"string\"\n ? { prompt: raw.prompt as OAuth2MethodDescriptor[\"prompt\"] }\n : {}),\n ...(typeof raw.pkce === \"boolean\" ? { pkce: raw.pkce } : {}),\n ...(raw.pkceMethod === \"plain\" || raw.pkceMethod === \"S256\"\n ? { pkceMethod: raw.pkceMethod }\n : {}),\n ...(raw.authorizationMethod === \"HEADER\" ||\n raw.authorizationMethod === \"BODY\"\n ? { authorizationMethod: raw.authorizationMethod }\n : {}),\n ...(typeof raw.grantType === \"string\" ? { grantType: raw.grantType } : {}),\n ...(extra && Object.keys(extra).length > 0 ? { extra } : {}),\n };\n}\n\n// NONE is how the framework spells \"no handshake\", so it is not carried:\n// a caller checking the field would otherwise have to know that too.\nfunction describeHandshake(\n trigger: ApTrigger,\n): { strategy: string; paramName?: string } | undefined {\n const strategy = trigger.handshakeConfiguration?.strategy;\n if (!strategy || strategy === \"NONE\") return undefined;\n return { strategy, paramName: trigger.handshakeConfiguration?.paramName };\n}\n\nexport interface PieceSource {\n packageName: string;\n version: string;\n}\n\n// Serializable descriptor of an adapted piece; the engine never learns\n// Activepieces exists (doc 08 §6.2).\nexport interface PieceDescriptor {\n id: string;\n source: PieceSource;\n displayName: string;\n description?: string;\n logoUrl?: string;\n categories?: string[];\n deprecated?: boolean;\n // A list when the piece offers several sign-in methods.\n auth?: PieceAuthDescriptor | PieceAuthDescriptor[];\n minimumSupportedRelease?: string;\n maximumSupportedRelease?: string;\n actions: PieceActionDescriptor[];\n triggers: PieceTriggerDescriptor[];\n // Set when no block of the piece can run here, e.g. an OAuth2 piece.\n unsupported?: UnsupportedFeature;\n}\n\nfunction optional<K extends string, V>(\n key: K,\n value: V | undefined,\n): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\nexport function describeOption(option: ApDropdownOption): ApDropdownOption {\n return {\n label: option.label,\n value: option.value,\n ...(typeof option.description === \"string\" && option.description\n ? { description: option.description }\n : {}),\n ...(typeof option.icon === \"string\" && option.icon\n ? { icon: option.icon }\n : {}),\n };\n}\n\n// Copied only when well-formed: a foreign bundle may carry anything here.\nfunction describeHints(prop: ApProperty): Partial<PiecePropDescriptor> {\n const hints: Partial<PiecePropDescriptor> = {};\n if (prop.width === \"half\" || prop.width === \"full\") hints.width = prop.width;\n const strings = [\"icon\", \"variant\", \"display\", \"formatProperty\"] as const;\n for (const key of strings) {\n const value = prop[key];\n if (typeof value === \"string\" && value !== \"\") hints[key] = value;\n }\n const numbers = [\"min\", \"max\", \"step\"] as const;\n for (const key of numbers) {\n const value = prop[key];\n if (typeof value === \"number\" && Number.isFinite(value)) hints[key] = value;\n }\n if (Array.isArray(prop.reveals)) {\n const reveals = prop.reveals.filter(\n (name): name is string => typeof name === \"string\",\n );\n if (reveals.length > 0) hints.reveals = reveals;\n }\n if (prop.refreshOnSearch === true) hints.refreshOnSearch = true;\n const showWhen = prop.showWhen as { prop?: unknown; oneOf?: unknown } | null;\n if (typeof showWhen?.prop === \"string\" && Array.isArray(showWhen.oneOf)) {\n const oneOf: unknown[] = showWhen.oneOf;\n hints.showWhen = { prop: showWhen.prop, oneOf: [...oneOf] };\n }\n if (typeof prop.emptyChoice === \"string\" && prop.emptyChoice !== \"\") {\n hints.emptyChoice = prop.emptyChoice;\n }\n return hints;\n}\n\nfunction describeGroups(\n groups: ApPropertyGroup[] | undefined,\n): PiecePropertyGroupDescriptor[] | undefined {\n if (!Array.isArray(groups)) return undefined;\n const described = groups\n .filter(\n (group) =>\n typeof group.key === \"string\" &&\n typeof group.display === \"string\" &&\n Array.isArray(group.props),\n )\n .map((group) => ({\n key: group.key!,\n display: group.display!,\n ...(group.label ? { label: group.label } : {}),\n ...(group.description ? { description: group.description } : {}),\n ...(group.icon ? { icon: group.icon } : {}),\n props: group.props!.filter(\n (name): name is string => typeof name === \"string\",\n ),\n }));\n return described.length > 0 ? described : undefined;\n}\n\nfunction hasResolver(prop: ApProperty): boolean {\n return typeof prop.options === \"function\" || typeof prop.props === \"function\";\n}\n\nfunction toPropDescriptor(\n name: string,\n prop: ApProperty,\n resolverId?: string,\n): PiecePropDescriptor {\n const dynamic = hasResolver(prop);\n const descriptor: PiecePropDescriptor = {\n name,\n displayName: prop.displayName ?? name,\n type: prop.type ?? \"UNKNOWN\",\n required: prop.required ?? false,\n hasDynamicResolver: dynamic,\n };\n if (typeof prop.description === \"string\" && prop.description !== \"\") {\n descriptor.description = prop.description;\n }\n if (typeof prop.placeholder === \"string\" && prop.placeholder !== \"\") {\n descriptor.placeholder = prop.placeholder;\n }\n if (prop.defaultValue !== undefined) {\n descriptor.defaultValue = prop.defaultValue;\n }\n if (prop.advanced === true) descriptor.advanced = true;\n if (dynamic && resolverId) {\n descriptor.dynamicResolverId = resolverId;\n }\n if (dynamic && Array.isArray(prop.refreshers)) {\n descriptor.refreshers = prop.refreshers.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n }\n if (typeof prop.options === \"object\" && Array.isArray(prop.options.options)) {\n descriptor.staticOptions = prop.options.options.map(describeOption);\n if (prop.options.disabled === true) descriptor.staticDisabled = true;\n if (typeof prop.options.placeholder === \"string\") {\n descriptor.staticPlaceholder = prop.options.placeholder;\n }\n }\n Object.assign(descriptor, describeHints(prop));\n if (prop.properties && typeof prop.properties === \"object\") {\n const nested = describeProperties(prop.properties);\n if (nested.length > 0) descriptor.properties = nested;\n }\n return descriptor;\n}\n\n// Descriptor list for a props map: nested ARRAY items and what a DYNAMIC\n// resolver returns, so the editor never sees raw piece properties.\nexport function describeProperties(\n props: Record<string, ApProperty> | null | undefined,\n resolverIdFor?: (propName: string) => string,\n): PiecePropDescriptor[] {\n if (!props || typeof props !== \"object\") return [];\n return Object.entries(props)\n .filter((entry): entry is [string, ApProperty] =>\n isPropertyObject(entry[1]),\n )\n .map(([propName, prop]) =>\n toPropDescriptor(propName, prop, resolverIdFor?.(propName)),\n );\n}\n\n// Bundles are duck-typed; a props map may carry non-object junk.\nfunction isPropertyObject(value: unknown): value is ApProperty {\n return value !== null && typeof value === \"object\";\n}\n\nfunction withUnsupported(feature: UnsupportedFeature | undefined): {\n unsupported?: UnsupportedFeature;\n} {\n return feature ? { unsupported: feature } : {};\n}\n\n// Pure translation over a loaded piece; performs no I/O and never executes\n// piece code beyond the actions()/triggers() accessors.\nfunction describeAuthMethod(auth: unknown): PieceAuthDescriptor | undefined {\n if (!auth || typeof auth !== \"object\") return undefined;\n const method = auth as ApProperty;\n // CUSTOM_AUTH carries a record here; a DYNAMIC prop would carry a\n // resolver function, which is not an auth shape at all.\n const props =\n method.props && typeof method.props === \"object\"\n ? describeProperties(method.props)\n : [];\n const oauth2 =\n method.type === \"OAUTH2\"\n ? describeOAuth2(auth as Record<string, unknown>)\n : undefined;\n return {\n type: method.type ?? \"UNKNOWN\",\n displayName: method.displayName,\n description: method.description,\n required: method.required,\n ...(props.length > 0 ? { props } : {}),\n ...(oauth2 ? { oauth2 } : {}),\n ...withUnsupported(unsupportedAuth(method)),\n };\n}\n\nfunction declaredPorts(ports: unknown): readonly string[] | undefined {\n if (!Array.isArray(ports) || ports.length === 0) return undefined;\n return ports.every((port) => typeof port === \"string\")\n ? (ports as string[])\n : undefined;\n}\n\n// Only a well-formed declaration is carried: a foreign bundle may hold anything.\nfunction declaredReactor(value: unknown): RequireReactor | undefined {\n return value === \"read\" || value === \"write\" ? value : undefined;\n}\n\nexport interface BuildDescriptorOptions {\n // Read each action's own `ports`: only a piece whose results the host routes.\n routed?: boolean;\n // The host feeds the triggers itself, so no trigger strategy is refused.\n hostFed?: boolean;\n}\n\nexport function buildDescriptor(\n piece: ApPiece,\n source: PieceSource,\n options: BuildDescriptorOptions = {},\n): PieceDescriptor {\n const actions = Object.entries(getActions(piece)).map(\n ([actionName, action]): PieceActionDescriptor => ({\n name: action.name ?? actionName,\n displayName: action.displayName ?? actionName,\n description: action.description,\n requireAuth: action.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(action.requireReactor)),\n ports:\n (options.routed ? declaredPorts(action.ports) : undefined) ??\n PIECE_ACTION_PORTS,\n props: describeProperties(\n action.props,\n (propName) =>\n `activepieces:${source.packageName}#${actionName}.${propName}`,\n ),\n ...(action.outputSchema !== undefined\n ? { outputSchema: action.outputSchema }\n : {}),\n ...(action.audience !== undefined ? { audience: action.audience } : {}),\n ...optional(\"propertyGroups\", describeGroups(action.propertyGroups)),\n ...optional(\n \"classification\",\n typeof action.classification === \"string\"\n ? action.classification\n : undefined,\n ),\n ...optional(\"errorHandlingOptions\", action.errorHandlingOptions),\n }),\n );\n\n const triggers = Object.entries(getTriggers(piece)).map(\n ([triggerName, trigger]): PieceTriggerDescriptor => ({\n name: trigger.name ?? triggerName,\n displayName: trigger.displayName ?? triggerName,\n description: trigger.description,\n strategy: trigger.type ?? \"UNKNOWN\",\n testStrategy: trigger.testStrategy,\n ...(typeof trigger.display === \"string\" && trigger.display !== \"\"\n ? { display: trigger.display }\n : {}),\n requireAuth: trigger.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(trigger.requireReactor)),\n ports: TRIGGER_PORTS,\n props: describeProperties(\n trigger.props,\n (propName) =>\n `activepieces:${source.packageName}#${triggerName}.${propName}`,\n ),\n ...(trigger.outputSchema !== undefined\n ? { outputSchema: trigger.outputSchema }\n : {}),\n hasSampleData:\n trigger.sampleData !== undefined && trigger.sampleData !== null,\n ...(trigger.sampleData !== undefined && trigger.sampleData !== null\n ? { sampleData: trigger.sampleData }\n : {}),\n handshake: describeHandshake(trigger),\n ...optional(\"renew\", triggerRenew(trigger)),\n ...optional(\"propertyGroups\", describeGroups(trigger.propertyGroups)),\n ...(options.hostFed ? {} : withUnsupported(unsupportedTrigger(trigger))),\n }),\n );\n\n const descriptor: PieceDescriptor = {\n id: `activepieces:${source.packageName}`,\n source,\n displayName: piece.displayName,\n description: piece.description,\n logoUrl: piece.logoUrl,\n categories: piece.categories,\n ...(piece.deprecated === true ? { deprecated: true } : {}),\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n actions,\n triggers,\n ...withUnsupported(unsupportedAuth(piece.auth)),\n };\n // Several methods stay a list, in the piece's order; each says whether this\n // engine can run it.\n if (Array.isArray(piece.auth)) {\n const methods = piece.auth\n .map(describeAuthMethod)\n .filter((method) => method !== undefined);\n if (methods.length > 0) descriptor.auth = methods;\n } else {\n const method = describeAuthMethod(piece.auth);\n if (method) descriptor.auth = method;\n }\n return descriptor;\n}\n","// Where a piece's code comes from: the source a block resolution chose.\n\n// A published piece is a bundle fetched and cached on disk; a package piece\n// ships inside an installed reactor package, on disk or served by a registry.\nimport type { PieceOrigin } from \"../engine/resolution.js\";\nimport { ensurePieceBundle, type BundleSource } from \"./fetch.js\";\nimport type { PieceModuleRef } from \"./worker/protocol.js\";\n\nexport interface ResolvedPiece extends PieceModuleRef {\n name: string;\n version: string;\n // True when the piece is code the operator installed.\n local: boolean;\n}\n\n// One version of one piece, from one source. No source tries every download\n// source in turn, which is what a caller outside a reactor gets.\nexport interface PieceTarget {\n name: string;\n version: string;\n source?: PieceOrigin;\n}\n\nexport interface PieceResolver {\n resolve(target: PieceTarget): Promise<ResolvedPiece>;\n}\n\n// A piece found in an installed reactor package: a module file, or a directory\n// in npm-bundle shape when the package ships one already bundled.\nexport interface LocalPiece {\n name: string;\n version: string;\n entryPath?: string;\n bundleDir?: string;\n // Set instead of the two above when the package was loaded from a registry:\n // the piece is declared and served, but nothing of it is on this disk yet.\n entryUrl?: string;\n}\n\n// May answer asynchronously: a host whose registry loads on first use waits\n// here rather than racing every caller to have loaded it first.\nexport type LocalPieceLookup = (\n name: string,\n) => LocalPiece | undefined | Promise<LocalPiece | undefined>;\n\n// One entry of a reactor package's `pieces` export: which piece it ships and\n// where the built bundle sits, relative to the package root.\nexport type { PackagePiece } from \"@powerhousedao/pieces-framework\";\n\n// Download sources per resolved source. Activepieces bytes are the same on\n// their CDN and on npm, so both serve that source.\nconst DOWNLOADS: Record<Exclude<PieceOrigin, \"local\">, BundleSource[]> = {\n registry: [\"registry\"],\n activepieces: [\"cdn\", \"npm\"],\n npm: [\"npm\"],\n};\n\nexport class PieceNotInstalledError extends Error {\n constructor(name: string, version: string) {\n super(`Piece ${name}@${version} is not installed on this reactor`);\n this.name = \"PieceNotInstalledError\";\n }\n}\n\n// Fetches from the source the resolution chose, and from nowhere else.\nexport function sourcedResolver(options: {\n cacheDir: string;\n lookup?: LocalPieceLookup;\n timeoutMs?: number;\n}): PieceResolver {\n const fetch = (\n target: PieceTarget,\n extra: { entryUrl?: string; sources?: BundleSource[]; scope?: string },\n ) =>\n ensurePieceBundle({\n name: target.name,\n version: target.version,\n cacheDir: options.cacheDir,\n ...(extra.entryUrl ? { entryUrl: extra.entryUrl } : {}),\n ...(extra.sources ? { sources: extra.sources } : {}),\n ...(extra.scope ? { cacheScope: extra.scope } : {}),\n ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n });\n return {\n async resolve(target: PieceTarget): Promise<ResolvedPiece> {\n const { name, version, source } = target;\n if (source === \"local\") {\n const local = await options.lookup?.(name);\n if (!local || local.version !== version) {\n throw new PieceNotInstalledError(name, version);\n }\n if (local.entryPath || local.bundleDir) {\n return {\n name,\n version,\n ...(local.entryPath ? { entryPath: local.entryPath } : {}),\n ...(local.bundleDir ? { bundleDir: local.bundleDir } : {}),\n local: true,\n };\n }\n if (!local.entryUrl) throw new PieceNotInstalledError(name, version);\n // Declared by a package loaded from a registry: served at entryUrl.\n const bundle = await fetch(target, {\n entryUrl: local.entryUrl,\n scope: \"local\",\n });\n return { name, version, bundleDir: bundle.dir, local: true };\n }\n const bundle = await fetch(\n target,\n source ? { sources: DOWNLOADS[source], scope: source } : {},\n );\n return { name, version, bundleDir: bundle.dir, local: false };\n },\n };\n}\n\n// Every download source in turn: registry, CDN, npm.\nexport function bundleResolver(options: {\n cacheDir: string;\n timeoutMs?: number;\n}): PieceResolver {\n return sourcedResolver(options);\n}\n\n// What a request hands the worker, from whichever source answered.\nexport function pieceModuleRef(piece: ResolvedPiece): PieceModuleRef {\n return piece.entryPath\n ? { entryPath: piece.entryPath }\n : { bundleDir: piece.bundleDir };\n}\n","// Everything the child sends crosses a structured-clone boundary. A piece's\n// own objects routinely do not survive it, so they are flattened first.\nexport function jsonSafe(value: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(value)) as unknown;\n } catch {\n return String(value);\n }\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { PropsValidationErrors } from \"../context/normalize.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n // Why the host could not stage it; a FILE prop that needs it fails with this.\n error?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n // Epoch ms at which the host kills the worker for this request.\n deadline?: number;\n // Cap on each host call. Absent leaves the built-in default.\n hostCallTimeoutMs?: number;\n}\n\n// `ctx.reactor` for one request: its RPC messages carry `requestId`, and the\n// host serves them only while the request is in flight.\nexport interface ReactorRequestBinding {\n requestId: string;\n requireReactor: \"read\" | \"write\";\n}\n\nexport interface ReactorScopedRequest {\n // Stamped by PieceWorker when the caller serves the reactor.\n reactor?: ReactorRequestBinding;\n}\n\nexport const REACTOR_RPC = \"reactor-rpc\";\nexport const MODEL_MANIFEST = \"model-manifest\";\n// Host call: a type's entries, or every entry the host knows without one.\nexport const MODEL_ENTRIES = \"model-entries\";\n\n// One reactor RPC message (`@powerhousedao/reactor/rpc`), either direction.\nexport interface ReactorRpcEnvelope {\n type: typeof REACTOR_RPC;\n requestId: string;\n message: unknown;\n}\n\n// Importable document models (the reactor's ModelManifestEntry), host to child\n// on fork. A type loaded later is looked up through MODEL_ENTRIES.\nexport interface ModelEntriesPayload {\n documentType?: string;\n}\n\nexport interface ModelManifestMessage {\n type: typeof MODEL_MANIFEST;\n entries: unknown[];\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n // The delivery that woke a RESUME run, served as ctx.resumePayload. This\n // engine never suspends a run, so nothing sets it yet; absent, the context\n // member keeps throwing by name.\n resumePayload?: unknown;\n // Call the action's test method instead of run, as a single-step test does.\n stepTest?: boolean;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // ctx.project.id, the same one a run of the piece is handed.\n projectId?: string;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\" | \"onRenew\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece's auth declares no validate.\n declared: boolean;\n // validate's verdict; true when none is declared.\n valid: boolean;\n // Why validate failed, when it said so.\n detail?: string;\n // getConnectionIdentifier's label; it runs only once the check passes.\n accountLabel?: string;\n // Why getConnectionIdentifier threw. The check still passes.\n identifierError?: string;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n // Set when the piece or trigger uses a feature this engine does not run.\n unsupportedFeature?: string;\n // Set when the props failed validation, before piece code ran.\n invalidProps?: PropsValidationErrors;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n timings?: WorkerTimings;\n}\n\nexport interface ErrorResponse {\n id: number;\n type: \"error\";\n error: SerializedPieceError;\n tlsPoisoned: boolean;\n timings?: WorkerTimings;\n}\n\n// One part of serving a request, in epoch ms: piece.load, reactor.open,\n// models, action.\nexport interface WorkerPhaseTiming {\n name: string;\n start: number;\n end: number;\n // The phase this one ran inside, e.g. \"action\" for a model loaded mid-action.\n parent?: string;\n attributes?: Record<string, string | boolean>;\n}\n\n// Where a request's time went inside the child, in epoch ms.\nexport interface WorkerTimings {\n received: number;\n sent: number;\n phases: WorkerPhaseTiming[];\n // When the child's entry finished loading; on its first response only.\n ready?: number;\n // The child's process.memoryUsage() as it answered, in bytes.\n memory?: WorkerMemory;\n}\n\nexport interface WorkerMemory {\n rss: number;\n heapUsed: number;\n heapTotal: number;\n external: number;\n}\n\nexport type WorkerResponse = ResultResponse | ErrorResponse;\n\n// A request the child makes of its host while a step is running: the reverse\n// direction of everything above, and the only way a piece reaches durable state.\n\n// Ids are the child's own counter, a separate space from the host's, which is\n// why every handler dispatches on `type` before comparing an id.\nexport interface HostCallMessage {\n id: number;\n type: \"host-call\";\n method: string;\n payload: unknown;\n}\n\n// `error` carries the failure as data: a rejected promise cannot cross IPC,\n// so the reply always arrives and the child rethrows.\nexport interface HostCallResponse {\n id: number;\n type: \"host-result\";\n value?: unknown;\n error?: string;\n}\n\n// What the host will answer for the request in flight. Registered per request,\n// so a call arriving after the step returned finds nothing and is refused.\nexport type HostCallHandlers = Record<\n string,\n (payload: unknown) => Promise<unknown>\n>;\n\n// The one-way half of the channel: a report the host may act on, with no\n// answer to wait for. Their engine splits the same way (rpc vs rpc-notify).\n\n// A tap must never stall the step, so these carry no id and no reply. Node's\n// IPC preserves order, which is what drains them before the result lands.\nexport interface HostNotifyMessage {\n type: \"host-notify\";\n method: string;\n payload: unknown;\n}\n\n// Handlers registered per request, like HostCallHandlers. A throw here is\n// swallowed: a failed tap must not fail the step it was reporting on.\nexport type HostNotifyHandlers = Record<string, (payload: unknown) => void>;\n\n// One console call the piece made, already flattened to a string in the child.\nexport interface PieceLogEntry {\n level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n at: number;\n}\n\nexport const LOG_WRITE = \"log.write\";\nexport const OUTPUT_UPDATE = \"output.update\";\n\n// A store call carries `{ key, value?, scope }`. The scope is a name the host\n// partitions on, never a prefix the child bakes into the key.\nexport const STORE_GET = \"store.get\";\nexport const STORE_PUT = \"store.put\";\nexport const STORE_DELETE = \"store.delete\";\n","// The child's half of the call channel: how piece code reaches durable host\n// state mid-step, instead of handing everything back when the step returns.\n\n// Modelled on their engine RPC (createRpcClient): a method name, a payload, an\n// id, and failures returned as data rather than thrown across the boundary.\nimport { markIndeterminate } from \"../indeterminate.js\";\nimport { STORE_DELETE, STORE_PUT, type HostCallResponse } from \"./protocol.js\";\n\n// A host call is a local IPC round trip, so ten seconds is pathological in the\n// ordinary case. It was not in the field: a reactor dispatch under load, or a\n// store write behind a saturated PGlite, outran it and the step was reported\n// FAILED for a write that had in fact been committed (backlog item 6). The cap\n// is now the host's to set (PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS, and never\n// shorter than the step's own timeoutSeconds), and a mutating call that does\n// time out is INDETERMINATE rather than failed.\nexport const DEFAULT_HOST_CALL_TIMEOUT_MS = 10_000;\n\n/**\n * The host calls that may have committed something by the time they time out.\n *\n * A read that times out is just a read that did not answer. A write is not:\n * the host may have written and simply not got the answer back in time, so\n * reporting it as a failure is a claim nobody can stand behind. Reactor writes\n * go over the reactor RPC, not a host call; their unconfirmed outcome is\n * recognised by error name instead (`../indeterminate.ts`).\n */\nexport const MUTATING_HOST_CALLS: readonly string[] = [STORE_PUT, STORE_DELETE];\n\n// Set per request from the wire; requests are serialized per worker.\nlet fromWire: number | undefined;\n// The request's kill deadline, less a margin to report a timeout before it.\nlet stopAt: number | undefined;\n\nconst MIN_DEADLINE_MARGIN_MS = 250;\nconst MAX_DEADLINE_MARGIN_MS = 2_000;\n\nfunction deadlineMargin(budgetMs: number): number {\n return Math.min(\n Math.max(Math.floor(budgetMs / 10), MIN_DEADLINE_MARGIN_MS),\n MAX_DEADLINE_MARGIN_MS,\n );\n}\n\nexport function setHostCallTimeout(\n timeoutMs: number | undefined,\n deadline?: number,\n): void {\n fromWire = timeoutMs;\n stopAt =\n deadline === undefined\n ? undefined\n : deadline - deadlineMargin(deadline - Date.now());\n}\n\nexport function hostCallTimeoutMs(): number {\n return fromWire ?? DEFAULT_HOST_CALL_TIMEOUT_MS;\n}\n\ninterface Pending {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nconst pending = new Map<number, Pending>();\nlet nextId = 1;\nlet listening = false;\n\nexport class HostCallError extends Error {\n constructor(method: string, detail: string) {\n super(`Host call \"${method}\" failed: ${detail}`);\n this.name = \"HostCallError\";\n }\n}\n\n/** A read-ish host call that did not answer. An ordinary failure. */\nexport class HostCallTimeoutError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(`Host call \"${method}\" got no answer within ${timeoutMs}ms`);\n this.name = \"HostCallTimeoutError\";\n }\n}\n\n/**\n * A WRITING host call that did not answer: the write may have landed.\n *\n * Marked indeterminate (`../indeterminate.ts`), which is what survives the\n * worker boundary — this is thrown in the forked child, where the class does\n * not cross but the error's own enumerable properties do.\n */\nexport const INDETERMINATE_ERROR_NAME = \"HostCallIndeterminateError\";\n\nexport class HostCallIndeterminateError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(\n `Host call \"${method}\" got no answer within ${timeoutMs}ms; it writes, ` +\n \"so whether it was committed is unknown and the step is neither a \" +\n \"success nor a failure\",\n );\n this.name = INDETERMINATE_ERROR_NAME;\n markIndeterminate(this);\n }\n}\n\nfunction timeoutError(method: string, timeoutMs: number): Error {\n return MUTATING_HOST_CALLS.includes(method)\n ? new HostCallIndeterminateError(method, timeoutMs)\n : new HostCallTimeoutError(method, timeoutMs);\n}\n\nfunction isHostCallResponse(value: unknown): value is HostCallResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === \"host-result\"\n );\n}\n\n// Registered once, on the same channel the job messages arrive on. The job\n// dispatcher ignores `host-result` because it only knows its own request types.\nfunction ensureListening(): void {\n if (listening) return;\n listening = true;\n process.on(\"message\", (message: unknown) => {\n if (!isHostCallResponse(message)) return;\n const entry = pending.get(message.id);\n if (!entry) return;\n pending.delete(message.id);\n clearTimeout(entry.timer);\n if (message.error !== undefined) {\n entry.reject(new HostCallError(entry.method, message.error));\n return;\n }\n entry.resolve(message.value);\n });\n}\n\nexport function callHost<T = unknown>(\n method: string,\n payload: unknown,\n timeoutMs: number = hostCallTimeoutMs(),\n): Promise<T> {\n if (!process.send) {\n return Promise.reject(\n new HostCallError(method, \"the worker has no channel to its host\"),\n );\n }\n // Clipped to the step deadline: a call still waiting when the worker is\n // killed would surface as a retryable worker timeout, even for a write.\n const budgetMs =\n stopAt === undefined ? timeoutMs : Math.min(timeoutMs, stopAt - Date.now());\n if (budgetMs <= 0) {\n return Promise.reject(new HostCallTimeoutError(method, 0));\n }\n ensureListening();\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(timeoutError(method, budgetMs));\n }, budgetMs);\n pending.set(id, {\n method,\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n });\n process.send?.({ id, type: \"host-call\", method, payload });\n });\n}\n\n// Test seam: a worker replaced between suites must not inherit pending calls.\nexport function resetHostCalls(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n}\n\n// The one-way half: a report with no answer to wait for. It cannot fail from\n// the piece's side, so a missing channel is dropped rather than raised.\nexport function notifyHost(method: string, payload: unknown): void {\n try {\n process.send?.({ type: \"host-notify\", method, payload });\n } catch {\n // `process.send` stays defined after the channel closes and throws. A tap\n // that threw here would be a tap that changed the step.\n }\n}\n","// One file-size ceiling for both directions. Inbound hydration (a FILE prop\n// that arrives as a URL, a data URI or an attachment ref) and outbound\n// ctx.files.write share it, because a piece that can emit a file the next step\n// cannot ingest is worse than a piece that refuses both.\nimport { Transform, type TransformCallback } from \"node:stream\";\nimport { DEFAULT_HOST_CALL_TIMEOUT_MS } from \"../worker/host-call.js\";\n\nexport const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n// What the environment asks for, or undefined when it asks for nothing usable.\n// Read per call: a host may set it after this module is loaded.\nexport function configuredMaxFileBytes(): number | undefined {\n const raw = process.env.PH_WORKFLOWS_PIECE_MAX_FILE_BYTES;\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : undefined;\n}\n\n// The worker child is forked without an environment, so its limit arrives on\n// the wire instead. Requests are serialized per worker: one value at a time.\nlet fromWire: number | undefined;\n\nexport function setMaxFileBytes(limit: number | undefined): void {\n fromWire = limit;\n}\n\nexport function maxFileBytes(): number {\n return fromWire ?? configuredMaxFileBytes() ?? DEFAULT_MAX_FILE_BYTES;\n}\n\n/** How long a piece's call of its host may take before the step gives up on\n * it. Read per call, like the file ceiling, and travelling on the wire for the\n * same reason: the child is forked with no environment. */\nexport const HOST_CALL_TIMEOUT_ENV = \"PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS\";\n\n/**\n * The host-call cap for one step.\n *\n * The 10s default outran reality for a reactor dispatch under load and the\n * step was reported FAILED for a write that had been committed (backlog item\n * 6). So it is configurable, and it is never shorter than the step's OWN\n * timeout: a step the author gave two minutes should not have its host calls\n * cut off after ten seconds. The child still clips each call to end before\n * the step's kill deadline (`worker/host-call.ts`).\n */\nexport function hostCallTimeoutForStep(\n stepTimeoutMs: number | undefined,\n env: Record<string, string | undefined> = process.env,\n): number {\n const configured = Number(env[HOST_CALL_TIMEOUT_ENV]);\n const base =\n Number.isFinite(configured) && configured > 0\n ? Math.floor(configured)\n : DEFAULT_HOST_CALL_TIMEOUT_MS;\n return Math.max(base, stepTimeoutMs ?? 0);\n}\n\nexport class FileTooLargeError extends Error {\n readonly size: number;\n readonly limit: number;\n\n constructor(size: number, limit: number = maxFileBytes()) {\n super(\n `File of ${size} bytes exceeds the ${limit} byte limit ` +\n `(raise PH_WORKFLOWS_PIECE_MAX_FILE_BYTES to allow more)`,\n );\n this.name = \"FileTooLargeError\";\n this.size = size;\n this.limit = limit;\n }\n}\n\nexport function assertWithinLimit(size: number): void {\n const limit = maxFileBytes();\n if (size > limit) throw new FileTooLargeError(size, limit);\n}\n\n// Counts bytes as they pass and fails the stream past the cap, so an\n// undeclared or understated body never lands whole in memory or on disk.\nexport function byteCap(limit: number = maxFileBytes()): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk: Buffer, _encoding, done: TransformCallback) {\n seen += chunk.byteLength;\n if (seen > limit) done(new FileTooLargeError(seen, limit));\n else done(null, chunk);\n },\n });\n}\n","// Two FilesService implementations plus the staged-file contract that carries\n// bytes back to the host.\n//\n// `ctx.files.write()` is called *during* action.run(), inside the forked\n// worker, and the worker protocol has no worker-to-host request channel. So\n// this follows the pattern storeState already establishes — push in, return\n// whole — using the one thing a fork shares with its parent: the filesystem.\n// The worker writes bytes to a staging directory and returns a provisional\n// `apfile://<token>`; the host ingests each staged file after the step returns\n// and rewrites the tokens in the output before journalling it.\nimport { randomUUID } from \"node:crypto\";\nimport { createWriteStream } from \"node:fs\";\nimport { mkdir, rm, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport {\n assertWithinLimit,\n byteCap,\n FileTooLargeError,\n maxFileBytes,\n} from \"./limits.js\";\n\nexport { FileTooLargeError, maxFileBytes };\n\nexport const APFILE_SCHEME = \"apfile://\";\n\n// One file the piece wrote, as it crosses back on ResultResponse.files.\nexport interface StagedFile {\n // The provisional ref handed to the piece; the host rewrites it in place.\n token: string;\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n}\n\n// What a piece may hand ctx.files.write: upstream takes a Buffer or a Readable.\nexport type ApFileData = Buffer | Uint8Array | Readable;\n\n// The framework's FilesService for both actions and triggers, with fileName\n// optional.\nexport interface ApFilesService {\n write(file: { fileName?: string; data: ApFileData }): Promise<string>;\n}\n\n// A Readable drained into memory under the cap, for the inline fallback.\nasync function drain(data: Readable): Promise<Buffer> {\n const chunks: Buffer[] = [];\n for await (const chunk of data.pipe(byteCap())) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks);\n}\n\n// Default for both actions and triggers when the host injects nothing: inline\n// the bytes as a data URI so the payload stays self-contained. Bounded by the\n// shared cap, since a data URI lands in the run journal.\nexport class DataUriFilesService implements ApFilesService {\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const data =\n file.data instanceof Readable\n ? await drain(file.data)\n : Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n if (data.byteLength > maxFileBytes()) {\n throw new FileTooLargeError(data.byteLength);\n }\n return `data:application/octet-stream;base64,${data.toString(\"base64\")}`;\n }\n}\n\nconst EXTENSION_TYPES: Record<string, string> = {\n pdf: \"application/pdf\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n tif: \"image/tiff\",\n tiff: \"image/tiff\",\n txt: \"text/plain\",\n json: \"application/json\",\n csv: \"text/csv\",\n};\n\nfunction contentTypeFor(fileName: string): string | undefined {\n const extension = fileName.split(\".\").pop()?.toLowerCase();\n return extension ? EXTENSION_TYPES[extension] : undefined;\n}\n\n// Worker-side service: writes into `<stagingDir>/<uuid>` and remembers what it\n// wrote so the worker can report it on the response.\nexport class StagedFilesService implements ApFilesService {\n private readonly files: StagedFile[] = [];\n\n constructor(private readonly stagingDir: string) {}\n\n staged(): StagedFile[] {\n return [...this.files];\n }\n\n async write(file: { fileName?: string; data: ApFileData }): Promise<string> {\n const token = randomUUID();\n const fileName =\n file.fileName && file.fileName !== \"\" ? file.fileName : token;\n const target = path.join(this.stagingDir, token);\n let size: number;\n if (file.data instanceof Readable) {\n // Capped while it streams to disk: a piece cannot fill the disk with a\n // file the host would refuse anyway.\n await mkdir(this.stagingDir, { recursive: true });\n try {\n await pipeline(file.data, byteCap(), createWriteStream(target));\n } catch (error) {\n await rm(target, { force: true });\n throw error;\n }\n size = (await stat(target)).size;\n } else {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n // Checked before anything touches the disk, for the same reason.\n assertWithinLimit(data.byteLength);\n await mkdir(this.stagingDir, { recursive: true });\n await writeFile(target, data);\n size = data.byteLength;\n }\n this.files.push({\n token: `${APFILE_SCHEME}${token}`,\n path: target,\n fileName,\n size,\n contentType: contentTypeFor(fileName),\n });\n return `${APFILE_SCHEME}${token}`;\n }\n}\n\n// Replaces every provisional token in a step output with the real ref the host\n// got back from its attachment store. Walks the whole value: a piece may nest\n// the ref anywhere, and a plain string replace over the serialized JSON would\n// corrupt any base64 that happens to contain the token.\nexport function rewriteFileRefs(\n value: unknown,\n refs: Map<string, string>,\n): unknown {\n if (refs.size === 0) return value;\n if (typeof value === \"string\") return refs.get(value) ?? value;\n if (Array.isArray(value)) {\n return value.map((entry) => rewriteFileRefs(entry, refs));\n }\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = rewriteFileRefs(entry, refs);\n }\n return out;\n }\n return value;\n}\n","// Our TriggerHookContext → theirs (doc 06 §2.8): one builder covering the\n// strategy variants; identity/payload as data, capabilities injected or stubbed.\nimport { Cron } from \"croner\";\nimport { DEDUPE_KEY_PROPERTY, type ApTrigger } from \"../types.js\";\nimport {\n InMemoryKeyValueStore,\n type ActionContextIdentity,\n type KeyValueStore,\n} from \"./action.js\";\nimport type { ConnectionsProvider, FlowsProvider } from \"./props.js\";\nimport type { ReactorOption } from \"./reactor-option.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport type TriggerContextOptions = TriggerContextBaseOptions & ReactorOption;\n\ninterface TriggerContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\n\n// The affixed form is anchored on the literal \"signature\", with the prefix\n// matched by a lookbehind placed after it. A leading prefix pattern\n// ((?:[a-z0-9]+[-_])*signature) retries from every segment of a long\n// hyphen-separated run that never ends in \"signature\", which is quadratic:\n// whole seconds over a few hundred kilobytes of journaled text. The\n// lookbehind runs once per occurrence of the literal instead, and captures\n// the prefix so the marker still names the whole header.\nconst TEXT_FIELD = new RegExp(\n String.raw`(\\b(?:authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token)|signature(?<=\\b((?:[a-z0-9]+[-_])*)signature)(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\5`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\n\n// Anchored on \"://\" with the scheme checked by the lookbehind behind it: a\n// leading scheme pattern ([a-z][a-z0-9+.-]*) rescans a long unbroken\n// alphanumeric run from every offset, which is quadratic — tens of seconds\n// over a 256 KiB run. The scheme is not consumed, and not rewritten either\n// way; only the password half is replaced.\nconst URL_USERINFO =\n /:\\/\\/(?<=[a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, user: string) => `://${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n\n // signaturePrefix is the lookbehind's capture: the affixes before\n // \"signature\" sit outside the match, so they are stitched back onto the\n // name only for the marker — the text keeps them where they were.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n signaturePrefix: string | undefined,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(`${signaturePrefix ?? \"\"}${name}`)}${quote}`,\n );\n}\n\n// A document header's or reference's operation counts per scope. Scope names\n// such as \"auth\" are not credentials, and the counts are numbers.\nfunction isScopeRevision(\n parent: Record<string, unknown>,\n key: string,\n entry: unknown,\n): boolean {\n return (\n key === \"revision\" &&\n typeof parent.documentType === \"string\" &&\n typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n Object.values(entry).every(\n (count) => typeof count === \"number\" && Number.isFinite(count),\n )\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n const record = value as Record<string, unknown>;\n for (const [key, entry] of Object.entries(record)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : isScopeRevision(record, key, entry)\n ? { ...(entry as Record<string, number>) }\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\n\n// TRUNCATED_MARKER is matched whole, not as a substring: walk() only ever\n// writes it in place of an entire capped node, so prose that merely mentions\n// the word keeps replaying.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") {\n return value.includes(REDACTED_PREFIX) || value === TRUNCATED_MARKER;\n }\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n","// The reactor RPC on a piece child's IPC channel, bound to one request. It owns\n// only `reactor-rpc` envelopes carrying that request's id.\nimport {\n REACTOR_RPC,\n type ReactorRpcEnvelope,\n type ReactorRequestBinding,\n} from \"./protocol.js\";\nimport type { IPieceWorkerTransport } from \"./transport.js\";\n\n// Structurally `IRpcTransport` from `@powerhousedao/reactor/rpc`.\nexport interface ReactorRpcTransport {\n post(message: never): void;\n onMessage(listener: (message: never) => void): () => void;\n close(): void;\n}\n\n// Serves ctx.reactor for one request; `open` returns the stop run when it settles.\nexport interface ReactorTap {\n requireReactor: ReactorRequestBinding[\"requireReactor\"];\n open(\n transport: ReactorRpcTransport,\n request: { requestId: string; deadline: number },\n ): () => void;\n}\n\nexport function isReactorRpcEnvelope(\n value: unknown,\n requestId: string,\n): value is ReactorRpcEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n const envelope = value as Partial<ReactorRpcEnvelope>;\n return envelope.type === REACTOR_RPC && envelope.requestId === requestId;\n}\n\nfunction isRpcMessage(value: unknown): boolean {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { k?: unknown }).k === \"string\"\n );\n}\n\n// The host's end. The child runs piece code: another request's id, or a\n// message without a kind, is dropped.\nexport function createIpcTransport(\n worker: IPieceWorkerTransport,\n requestId: string,\n): ReactorRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: unknown) {\n if (closed || !worker.connected) return;\n worker.send({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener: (message: never) => void) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n if (!isRpcMessage(value.message)) return;\n listener(value.message as never);\n };\n worker.on(\"message\", handler);\n const detach = () => {\n worker.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n","// What PieceWorker needs from a connection to a worker, and nothing else.\n\n// Written against this rather than a ChildProcess so a later transport — a\n// pooled fork, a socket to another machine — slots in underneath unchanged.\nimport { fork, type ChildProcess } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n lstatSync,\n mkdirSync,\n} from \"node:fs\";\nimport { tmpdir, userInfo } from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport interface TransportExit {\n code: number | null;\n signal: NodeJS.Signals | null;\n}\n\nexport type TransportEventMap = {\n message: unknown;\n exit: TransportExit;\n};\n\nexport type TransportEvent = keyof TransportEventMap;\n\nexport type TransportListener<E extends TransportEvent> = (\n payload: TransportEventMap[E],\n) => void;\n\n// One worker's connection. An implementation must deliver `message` payloads\n// faithfully enough for the protocol above, and emit `exit` exactly once.\n\n// \"Faithfully enough\" means JSON-shaped, deliberately: the fork's structured\n// clone would carry a Date or a Map, but nothing may depend on that, because\n// no other carrier could honour it.\n\n// PieceWorker flattens what it sends and the child flattens what it answers,\n// so this is a contract a socket could meet too — a transport is not required\n// to preserve anything JSON would lose.\nexport interface IPieceWorkerTransport {\n send(message: unknown): void;\n on<E extends TransportEvent>(event: E, listener: TransportListener<E>): void;\n off<E extends TransportEvent>(event: E, listener: TransportListener<E>): void;\n // Ends the worker now; it takes any pending host calls with it.\n kill(): void;\n // False once the worker cannot receive: a send after this is dropped.\n readonly connected: boolean;\n}\n\n// Builds a fresh connection. Called on first use and again after a worker is\n// killed, so a factory must be able to produce more than one.\nexport type PieceWorkerTransportFactory = () => IPieceWorkerTransport;\n\nexport function defaultEntryPath(): string {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n while (!existsSync(path.join(dir, \"package.json\"))) {\n const parent = path.dirname(dir);\n if (parent === dir) throw new Error(\"Could not locate package root\");\n dir = parent;\n }\n const entry = path.join(dir, \"dist\", \"worker-entry.js\");\n if (!existsSync(entry)) {\n throw new Error(`Worker entry not built at ${entry} — run pnpm build`);\n }\n return entry;\n}\n\n// How long a profiling child gets to write its profile before SIGKILL.\nconst PROFILE_EXIT_MS = 2_000;\n\n// Each child writes a V8 CPU profile here; for benchmarks.\nfunction workerProfileDir(): string | undefined {\n return process.env.PH_WORKFLOWS_WORKER_CPU_PROF_DIR || undefined;\n}\n\nlet compileCache: string | null | undefined;\n\n// A planted cache is code the child runs, so the directory must be ours alone:\n// mkdirSync leaves an existing one, whoever owns it, as it found it.\nexport function privateDirectory(dir: string): boolean {\n const stat = lstatSync(dir);\n if (!stat.isDirectory()) return false;\n // No uids on Windows; there the directory sits in the user's own temp.\n if (typeof process.getuid !== \"function\") return true;\n return stat.uid === process.getuid() && (stat.mode & 0o077) === 0;\n}\n\n// Children run piece code as our uid and can write the cache, so by default it\n// is used only where they could already rewrite the entry it caches.\nexport function writable(file: string): boolean {\n try {\n accessSync(file, constants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n\n// V8 code cache every child shares, so a fork skips compiling what an earlier\n// one did. PH_WORKFLOWS_WORKER_COMPILE_CACHE names the directory; \"off\" disables.\nfunction workerCompileCache(entryPath: string): string | undefined {\n if (compileCache === undefined) {\n const configured = process.env.PH_WORKFLOWS_WORKER_COMPILE_CACHE;\n try {\n if (configured === \"off\") throw new Error(\"disabled\");\n if (!configured && !writable(entryPath)) throw new Error(\"read-only\");\n // userInfo throws in a container whose uid has no passwd entry.\n const base = configured\n ? undefined\n : path.join(tmpdir(), `ph-workflows-${userInfo().uid}`);\n const dir = configured || path.join(base!, \"compile-cache\");\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n // In a shared tmp the parent counts too: its owner could swap the cache out.\n const owned = privateDirectory(dir) && (!base || privateDirectory(base));\n compileCache = owned ? dir : null;\n } catch {\n // Unwritable or disabled: children compile from source.\n compileCache = null;\n }\n }\n return compileCache ?? undefined;\n}\n\n// A forked node child on this machine, over its IPC channel.\nexport interface ForkTransportOptions {\n // `--max-old-space-size` for the child.\n heapMb?: number;\n}\n\nexport function createForkTransport(\n entryPath: string,\n options: ForkTransportOptions = {},\n): IPieceWorkerTransport {\n const profileDir = workerProfileDir();\n const cacheDir = workerCompileCache(entryPath);\n const execArgv = profileDir\n ? [\"--cpu-prof\", `--cpu-prof-dir=${profileDir}`]\n : [];\n if (options.heapMb) {\n execArgv.push(`--max-old-space-size=${Math.trunc(options.heapMb)}`);\n }\n const child: ChildProcess = fork(entryPath, [], {\n // No host env: the child gets no secrets and no inherited TLS overrides.\n env: cacheDir ? { NODE_COMPILE_CACHE: cacheDir } : {},\n execArgv,\n // Structured clone rather than JSON, so a Buffer in a payload survives.\n serialization: \"advanced\",\n // Piece stdout/stderr are dropped for now; log capture arrives with journaling.\n stdio: [\"ignore\", \"ignore\", \"ignore\", \"ipc\"],\n });\n\n // Node reports exit as two positional arguments; the interface carries one\n // payload, so the adaptation lives here rather than in every listener.\n const exitListeners = new Map<\n TransportListener<\"exit\">,\n (code: number | null, signal: NodeJS.Signals | null) => void\n >();\n\n return {\n get connected() {\n return child.connected;\n },\n send(message) {\n child.send(message as never);\n },\n on(event, listener) {\n if (event === \"exit\") {\n const adapted = (code: number | null, signal: NodeJS.Signals | null) =>\n (listener as TransportListener<\"exit\">)({ code, signal });\n exitListeners.set(listener as TransportListener<\"exit\">, adapted);\n child.on(\"exit\", adapted);\n return;\n }\n child.on(\"message\", listener as (value: unknown) => void);\n },\n off(event, listener) {\n if (event === \"exit\") {\n const adapted = exitListeners.get(\n listener as TransportListener<\"exit\">,\n );\n if (adapted) {\n child.off(\"exit\", adapted);\n exitListeners.delete(listener as TransportListener<\"exit\">);\n }\n return;\n }\n child.off(\"message\", listener as (value: unknown) => void);\n },\n kill() {\n if (!profileDir) {\n child.kill(\"SIGKILL\");\n return;\n }\n // SIGTERM lets it write its CPU profile; a blocked loop never handles it.\n child.kill(\"SIGTERM\");\n const force = setTimeout(() => child.kill(\"SIGKILL\"), PROFILE_EXIT_MS);\n force.unref();\n child.once(\"exit\", () => clearTimeout(force));\n },\n };\n}\n","// Wall-clock marks a child takes while serving one request, sent back with its\n// response so the host can draw them as spans. The child carries no tracer.\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { WorkerPhaseTiming, WorkerTimings } from \"./protocol.js\";\n\nconst ANCHOR_MS = 1_000;\n// Date.now() rounds to the ms: a smaller drift is that, not a clock step, and\n// following it would step time backwards.\nconst STEP_MS = 5;\n\n// Epoch ms, sub-ms precise, comparable across processes. Re-anchored each second:\n// timeOrigin is fixed at start, so a clock step would skew host against child.\nexport function wallClock(): () => number {\n let anchoredAt = performance.now();\n let anchor = Date.now() - anchoredAt;\n return () => {\n const now = performance.now();\n if (now - anchoredAt >= ANCHOR_MS) {\n anchoredAt = now;\n const next = Date.now() - now;\n if (Math.abs(next - anchor) > STEP_MS) anchor = next;\n }\n return anchor + now;\n };\n}\n\nexport const epochNow = wallClock();\n\nlet readyAt: number | undefined;\nlet bootReported = false;\n\n// When the entry finished loading; reported once, with the first response.\nexport function markWorkerReady(): void {\n readyAt ??= epochNow();\n}\n\nexport interface RequestTimings {\n received: number;\n phases: WorkerPhaseTiming[];\n}\n\nconst current = new AsyncLocalStorage<RequestTimings>();\n// The phase `fn` runs inside, so a nested one (models in action) names its parent.\nconst currentPhase = new AsyncLocalStorage<string>();\n\nexport function startRequestTimings(): RequestTimings {\n return { received: epochNow(), phases: [] };\n}\n\nexport function withRequestTimings<T>(\n timings: RequestTimings,\n fn: () => Promise<T>,\n): Promise<T> {\n return current.run(timings, fn);\n}\n\n// Records `fn` as a phase of the request being served, if any.\nexport async function timed<T>(\n name: string,\n fn: () => Promise<T>,\n attributes?: Record<string, string | boolean>,\n): Promise<T> {\n const timings = current.getStore();\n if (!timings) return fn();\n const parent = currentPhase.getStore();\n const start = epochNow();\n try {\n return await currentPhase.run(name, fn);\n } finally {\n timings.phases.push({\n name,\n start,\n end: epochNow(),\n ...(parent ? { parent } : {}),\n ...(attributes ? { attributes } : {}),\n });\n }\n}\n\nexport function finishRequestTimings(timings: RequestTimings): WorkerTimings {\n const boot = !bootReported && readyAt !== undefined;\n bootReported = true;\n const { rss, heapUsed, heapTotal, external } = process.memoryUsage();\n return {\n received: timings.received,\n sent: epochNow(),\n phases: timings.phases,\n memory: { rss, heapUsed, heapTotal, external },\n ...(boot ? { ready: readyAt } : {}),\n };\n}\n","import {\n configuredMaxFileBytes,\n hostCallTimeoutForStep,\n} from \"../context/limits.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\nimport { jsonSafe } from \"./json-safe.js\";\nimport { randomUUID } from \"node:crypto\";\nimport { createIpcTransport, type ReactorTap } from \"./reactor-rpc.js\";\nimport type { WorkflowTelemetry } from \"../../../telemetry.js\";\nimport {\n createForkTransport,\n defaultEntryPath,\n type IPieceWorkerTransport,\n type PieceWorkerTransportFactory,\n type TransportExit,\n} from \"./transport.js\";\nimport {\n MODEL_ENTRIES,\n MODEL_MANIFEST,\n type CheckConnectionRequest,\n type DescribePieceRequest,\n type HostCallHandlers,\n type HostCallMessage,\n type HostCallResponse,\n type HostNotifyHandlers,\n type HostNotifyMessage,\n type ModelEntriesPayload,\n type ModelManifestMessage,\n type ReactorRequestBinding,\n type ReactorRpcEnvelope,\n type ResolveOptionsRequest,\n type RunActionRequest,\n type SerializedPieceError,\n type TriggerHookRequest,\n type WorkerMemory,\n type WorkerResponse,\n type WorkerTimings,\n} from \"./protocol.js\";\nimport { epochNow } from \"./timings.js\";\n\ntype WorkerRequestType =\n | \"run\"\n | \"resolve-options\"\n | \"trigger-hook\"\n | \"check-connection\"\n | \"describe\";\n\ntype WorkerRequest =\n | RunActionRequest\n | ResolveOptionsRequest\n | TriggerHookRequest\n | CheckConnectionRequest\n | DescribePieceRequest;\n\nexport class PieceWorkerError extends Error {\n readonly serialized: SerializedPieceError;\n\n constructor(serialized: SerializedPieceError) {\n super(`${serialized.name}: ${serialized.message}`);\n this.name = \"PieceWorkerError\";\n this.serialized = serialized;\n }\n}\n\nexport class PieceWorkerTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`Piece action timed out after ${timeoutMs}ms; worker was replaced`);\n this.name = \"PieceWorkerTimeoutError\";\n }\n}\n\nexport class PieceWorkerExitError extends Error {\n constructor(code: number | null, signal: string | null) {\n super(`Piece worker exited unexpectedly (code=${code}, signal=${signal})`);\n this.name = \"PieceWorkerExitError\";\n }\n}\n\nexport class PieceWorkerDisposedError extends Error {\n constructor() {\n super(\"This piece worker is disposed\");\n this.name = \"PieceWorkerDisposedError\";\n }\n}\n\nexport interface PieceWorkerResult {\n output: unknown;\n touched: string[];\n tlsPoisoned: boolean;\n // run only: files the piece wrote through ctx.files, staged on disk for the\n // host to ingest before the output is journalled.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n}\n\n// Handlers the host offers for the duration of one request: calls it answers,\n// and one-way reports it receives.\nexport interface RequestTaps {\n hostCalls?: HostCallHandlers;\n notifications?: HostNotifyHandlers;\n // ctx.reactor over the reactor RPC; ignored by check-connection and describe.\n reactor?: ReactorTap;\n}\n\n// Every request that can serve a piece takes the same shape: a deadline plus\n// the taps the host offers while it runs.\nexport interface RequestOptions extends RequestTaps {\n timeoutMs?: number;\n // Cap on each call the child makes of its host, for THIS request. Per\n // request rather than per worker because it follows the step's own timeout\n // (`hostCallTimeoutForStep`), and one worker serves many steps.\n hostCallTimeoutMs?: number;\n}\n\n/** @deprecated Named for the one request that had it; every request takes it\n * now. Kept because the old name is on main, in this package's public types. */\nexport type RunActionOptions = RequestOptions;\n\n// The child's marks, plus when the host sent the request and got the reply.\nexport type OnWorkerTimings = (\n timings: WorkerTimings,\n ipc: { sent: number; received: number },\n) => void;\n\ntype ChildMessage =\n | WorkerResponse\n | HostCallMessage\n | HostNotifyMessage\n | ReactorRpcEnvelope;\n\ninterface OpenReactor {\n binding: ReactorRequestBinding;\n stop: () => void;\n}\n\n// Importable document models for the child (the reactor's ModelManifestEntry).\nexport interface ModelManifestSource {\n // Sent on fork.\n entries(): unknown[];\n // The child's lookup on a miss; without a type, every entry the host knows.\n lookup?(documentType?: string): unknown[] | Promise<unknown[]>;\n}\n\n// A tap reports on the step; it never decides its outcome. Node delivers these\n// before the result, so no draining step is needed at teardown.\nfunction serveNotify(\n message: HostNotifyMessage,\n handlers: HostNotifyHandlers | undefined,\n): void {\n const handler = handlers?.[message.method];\n if (!handler) return;\n try {\n // Declared void, but TypeScript admits an async function here, and its\n // rejection would take the host down rather than the tap.\n void Promise.resolve(handler(message.payload)).catch(() => undefined);\n } catch {\n // A broken tap is not the step's problem.\n }\n}\n\nexport interface PieceWorkerOptions {\n // Absolute path to the compiled worker entry; defaults to dist/worker-entry.js.\n entryPath?: string;\n telemetry?: WorkflowTelemetry;\n defaultTimeoutMs?: number;\n // How to reach a worker. Defaults to a forked child on this machine; a\n // remote transport replaces it without touching the protocol above.\n transport?: PieceWorkerTransportFactory;\n // Cap on each call the child makes of its host; the child's default if unset.\n hostCallTimeoutMs?: number;\n // Sent to each child on fork, and looked up by type on a miss.\n models?: ModelManifestSource;\n // The child's V8 heap limit (`--max-old-space-size`); Node's default if unset.\n heapMb?: number;\n}\n\n// What a pool needs to decide whether a child can serve another request.\nexport interface PieceWorkerHealth {\n // A child is running; false before the first request and after it exits.\n alive: boolean;\n // From the child's last reply; absent until it has replied once.\n memory?: WorkerMemory;\n // A request switched TLS verification off, which the child may have cached.\n tlsPoisoned: boolean;\n}\n\n// The five requests a worker serves, plus teardown. Callers hold this rather\n// than PieceWorker itself, so a child that outlives every request and a child\n// that lives for one run are interchangeable to them.\nexport interface IPieceWorker {\n runAction(\n request: RunActionRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult>;\n resolveOptions(\n request: ResolveOptionsRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult>;\n checkConnection(\n request: CheckConnectionRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult>;\n describePiece(\n request: DescribePieceRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult>;\n runTriggerHook(\n request: TriggerHookRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult>;\n // Ends the worker. A caller that was handed one it does not own must not\n // call this; PieceWorkerPool disposes the workers it hands out.\n dispose(): void;\n // Absent on a worker a pool can't inspect; the pool then trusts it.\n health?(): PieceWorkerHealth;\n}\n\n// Executes piece actions in a child process. Side-effects (TLS env poisoning,\n// crashes) stay in the child; a timed-out or crashed worker is replaced.\nexport class PieceWorker implements IPieceWorker {\n private readonly connect: PieceWorkerTransportFactory;\n private readonly defaultTimeoutMs: number;\n private readonly hostCallTimeoutMs: number | undefined;\n private readonly models: ModelManifestSource | undefined;\n private readonly telemetry: WorkflowTelemetry | undefined;\n private worker: IPieceWorkerTransport | undefined;\n // When the current child was forked, in epoch ms.\n private forkedAt = 0;\n private queue: Promise<unknown> = Promise.resolve();\n private nextId = 1;\n private disposed = false;\n private memory: WorkerMemory | undefined;\n private tlsPoisoned = false;\n\n constructor(options: PieceWorkerOptions = {}) {\n const entryPath = options.entryPath;\n const { heapMb } = options;\n this.connect =\n options.transport ??\n (() => createForkTransport(entryPath ?? defaultEntryPath(), { heapMb }));\n this.defaultTimeoutMs = options.defaultTimeoutMs ?? 30_000;\n this.hostCallTimeoutMs = options.hostCallTimeoutMs;\n this.models = options.models;\n this.telemetry = options.telemetry;\n }\n\n // Requests are serialized per worker; concurrency comes from holding more\n // than one, which is what PieceWorkerPool does.\n runAction(\n request: RunActionRequest,\n options: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"run\", request, options.timeoutMs, options);\n }\n\n // Design-time DROPDOWN options() / DYNAMIC props() resolution. It takes the\n // same taps a run does: a package piece's resolver may read the reactor.\n resolveOptions(\n request: ResolveOptionsRequest,\n options: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"resolve-options\", request, options.timeoutMs, options);\n }\n\n // The piece's auth.validate and auth.getConnectionIdentifier over resolved\n // credentials; the output is a CheckConnectionOutcome.\n checkConnection(\n request: CheckConnectionRequest,\n options: { timeoutMs?: number } = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"check-connection\", request, options.timeoutMs);\n }\n\n // The piece's design-time descriptor; the output is a PieceDescriptor.\n describePiece(\n request: DescribePieceRequest,\n options: { timeoutMs?: number } = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"describe\", request, options.timeoutMs);\n }\n\n // One trigger lifecycle hook. It takes the same taps a run does, so a\n // `durableStore` hook reaches the host's store while it is still running.\n runTriggerHook(\n request: TriggerHookRequest,\n options: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n return this.enqueue(\"trigger-hook\", request, options.timeoutMs, options);\n }\n\n private enqueue(\n type: WorkerRequestType,\n request: WorkerRequest,\n timeoutMs?: number,\n taps: RequestOptions = {},\n ): Promise<PieceWorkerResult> {\n const run = this.queue.then(() => {\n const execute = (onTimings?: OnWorkerTimings) =>\n this.execute(\n type,\n request,\n timeoutMs ?? this.defaultTimeoutMs,\n taps,\n onTimings,\n );\n const telemetry = this.telemetry;\n if (!telemetry) return execute();\n // Named apart, not just attributed: the phase metric keys on the name,\n // and a cold request pays for the fork and the child's module loading.\n const cold = !this.worker;\n return telemetry.phase(\n `worker.${type}${cold ? \".cold\" : \"\"}`,\n { \"worker.cold\": cold },\n (span) =>\n execute((timings, ipc) =>\n telemetry.workerTimings(span, timings, this.forkedAt, ipc),\n ),\n );\n });\n this.queue = run.catch(() => undefined);\n return run;\n }\n\n // For good: a request still queued, or made later, forks nothing.\n dispose(): void {\n this.disposed = true;\n this.worker?.kill();\n this.worker = undefined;\n }\n\n health(): PieceWorkerHealth {\n return {\n alive: this.worker !== undefined,\n ...(this.memory ? { memory: this.memory } : {}),\n tlsPoisoned: this.tlsPoisoned,\n };\n }\n\n // A fresh child starts clean, so what the last one reported no longer holds.\n private forgetChild(): void {\n this.memory = undefined;\n this.tlsPoisoned = false;\n }\n\n // Read from piece-controlled output, so only well-formed numbers count.\n private noteReply(response: ChildMessage): void {\n if (\"tlsPoisoned\" in response && response.tlsPoisoned === true) {\n this.tlsPoisoned = true;\n }\n const memory = (response as { timings?: WorkerTimings }).timings?.memory;\n if (\n memory &&\n [memory.rss, memory.heapUsed, memory.heapTotal, memory.external].every(\n (value) => Number.isFinite(value),\n )\n ) {\n this.memory = memory;\n }\n }\n\n private spawn(): IPieceWorkerTransport {\n if (this.worker) return this.worker;\n this.forgetChild();\n this.forkedAt = epochNow();\n const worker = this.connect();\n this.sendModels(worker);\n const forget = () => {\n if (this.worker === worker) this.worker = undefined;\n worker.off(\"exit\", forget);\n };\n worker.on(\"exit\", forget);\n this.worker = worker;\n return worker;\n }\n\n private sendModels(worker: IPieceWorkerTransport): void {\n const entries = this.models?.entries() ?? [];\n if (entries.length === 0 || !worker.connected) return;\n const message: ModelManifestMessage = { type: MODEL_MANIFEST, entries };\n worker.send(jsonSafe(message));\n }\n\n private async modelEntries(payload: unknown): Promise<unknown[]> {\n const documentType = (payload as ModelEntriesPayload | undefined)\n ?.documentType;\n return (await this.models?.lookup?.(documentType)) ?? [];\n }\n\n // Starts serving ctx.reactor for one request; the returned stop closes it.\n private openReactor(\n worker: IPieceWorkerTransport,\n tap: ReactorTap,\n deadline: number,\n ): OpenReactor {\n const requestId = randomUUID();\n const transport = createIpcTransport(worker, requestId);\n let stopServing: () => void;\n try {\n stopServing = tap.open(transport, { requestId, deadline });\n } catch (error) {\n transport.close();\n throw error;\n }\n return {\n binding: { requestId, requireReactor: tap.requireReactor },\n stop: () => {\n transport.close();\n stopServing();\n },\n };\n }\n\n private execute(\n type: WorkerRequestType,\n request: WorkerRequest,\n timeoutMs: number,\n taps: RequestOptions,\n onTimings?: OnWorkerTimings,\n ): Promise<PieceWorkerResult> {\n if (this.disposed) return Promise.reject(new PieceWorkerDisposedError());\n const worker = this.spawn();\n const id = this.nextId++;\n // An explicit per-worker cap is the host's own decision and wins. With\n // none — which is how the pool builds them — each request carries the cap\n // derived from its step (`hostCallTimeoutForStep`), because one worker\n // serves many steps and the cap follows the step's own timeout.\n // A request with no cap of its own (a trigger hook, a design-time call)\n // takes the operator's, raised to its own timeout, as a step does.\n const hostCallTimeoutMs =\n this.hostCallTimeoutMs ??\n taps.hostCallTimeoutMs ??\n hostCallTimeoutForStep(timeoutMs);\n\n // When the request was handed to IPC, for the ipc.in span.\n let sentAt = 0;\n return new Promise<PieceWorkerResult>((resolve, reject) => {\n // The kill timer's own reading, so the child can give up in time to say why.\n const deadline = Date.now() + timeoutMs;\n let reactor: OpenReactor | undefined;\n if (taps.reactor && type !== \"check-connection\" && type !== \"describe\") {\n try {\n reactor = this.openReactor(worker, taps.reactor, deadline);\n } catch (error) {\n reject(error instanceof Error ? error : new Error(String(error)));\n return;\n }\n }\n const timer = setTimeout(() => {\n cleanup();\n worker.kill();\n this.worker = undefined;\n reject(new PieceWorkerTimeoutError(timeoutMs));\n }, timeoutMs);\n\n const onMessage = (value: unknown) => {\n const response = value as ChildMessage;\n // Ids come from two counters; dispatch on type before comparing them.\n if (\n response.type === \"host-call\" ||\n response.type === \"host-notify\" ||\n response.type === \"reactor-rpc\"\n ) {\n return;\n }\n if (response.id !== id) return;\n cleanup();\n const received = epochNow();\n this.noteReply(response);\n if (response.type === \"result\") {\n resolve({\n output: response.output,\n touched: response.touched,\n tlsPoisoned: response.tlsPoisoned,\n files: response.files,\n storeState: response.storeState,\n schedules: response.schedules,\n listeners: response.listeners,\n });\n } else {\n reject(new PieceWorkerError(response.error));\n }\n // After settling: the child is piece code and its timings may be junk.\n if (response.timings && onTimings) {\n try {\n onTimings(response.timings, { sent: sentAt, received });\n } catch {\n // Tracing must never fail the request it describes.\n }\n }\n };\n\n const onExit = ({ code, signal }: TransportExit) => {\n cleanup();\n reject(new PieceWorkerExitError(code, signal));\n };\n\n // Served outside the request queue: the queue is held by this very\n // request, so routing a call through it would deadlock the step.\n const onHostCall = (value: unknown) => {\n const message = value as ChildMessage;\n if (message.type === \"host-call\") {\n void this.serveHostCall(worker, message, taps.hostCalls);\n return;\n }\n if (message.type === \"host-notify\") {\n serveNotify(message, taps.notifications);\n }\n };\n\n const cleanup = () => {\n reactor?.stop();\n reactor = undefined;\n clearTimeout(timer);\n worker.off(\"message\", onMessage);\n worker.off(\"message\", onHostCall);\n worker.off(\"exit\", onExit);\n };\n\n worker.on(\"message\", onMessage);\n worker.on(\"message\", onHostCall);\n worker.on(\"exit\", onExit);\n // Flattened here rather than per caller: config, auth and connection\n // values are piece-authored, and the contract is JSON-shaped both ways.\n // The file ceiling is stamped on the same way the egress policy is passed\n // in: the child reads no environment of its own.\n sentAt = epochNow();\n worker.send(\n jsonSafe({\n id,\n type,\n request: {\n maxFileBytes: configuredMaxFileBytes(),\n deadline,\n ...(hostCallTimeoutMs ? { hostCallTimeoutMs } : {}),\n ...request,\n ...(reactor ? { reactor: reactor.binding } : {}),\n },\n }),\n );\n });\n }\n\n // Answers one call from the child. The handler set belongs to the request in\n // flight, so a call arriving after the step returned is refused, not served.\n private async serveHostCall(\n worker: IPieceWorkerTransport,\n message: HostCallMessage,\n handlers: HostCallHandlers | undefined,\n ): Promise<void> {\n let response: HostCallResponse;\n try {\n const handler =\n message.method === MODEL_ENTRIES\n ? (payload: unknown) => this.modelEntries(payload)\n : handlers?.[message.method];\n if (!handler) {\n throw new Error(`No host handler for \"${message.method}\"`);\n }\n response = {\n id: message.id,\n type: \"host-result\",\n value: await handler(message.payload),\n };\n } catch (error) {\n response = {\n id: message.id,\n type: \"host-result\",\n error: error instanceof Error ? error.message : String(error),\n };\n }\n // A worker killed on timeout takes its pending calls with it.\n if (worker.connected) worker.send(response);\n }\n}\n","// One warm pool of piece children, leased per request (ADR 0007).\n\n// A request takes an idle child that has its piece loaded, then any idle\n// child, then a new child, then a place in a FIFO queue.\n\n// Trigger hooks get children of their own, so a burst of runs can't delay\n// polls. A child that dies, grows or poisons TLS is retired.\nimport { readFileSync } from \"node:fs\";\nimport os from \"node:os\";\nimport {\n PieceWorker,\n PieceWorkerDisposedError,\n type IPieceWorker,\n type PieceWorkerHealth,\n type PieceWorkerOptions,\n type PieceWorkerResult,\n type RequestOptions,\n} from \"./host.js\";\nimport type {\n CheckConnectionRequest,\n DescribePieceRequest,\n ResolveOptionsRequest,\n RunActionRequest,\n TriggerHookRequest,\n} from \"./protocol.js\";\nimport type { WorkflowTelemetry } from \"../../../telemetry.js\";\n\n// Thrown when a request asks for a child the pool will not queue.\n\n// The pool queues without limit unless an operator caps it, so this only\n// appears where someone chose failing fast over waiting.\nexport class PieceWorkerPoolBusyError extends Error {\n constructor(size: number, waiting: number) {\n super(\n `All ${size} piece workers are busy and ${waiting} requests are already waiting`,\n );\n this.name = \"PieceWorkerPoolBusyError\";\n }\n}\n\nexport class PieceWorkerSessionClosedError extends Error {\n constructor() {\n super(\"This piece worker session is closed\");\n this.name = \"PieceWorkerSessionClosedError\";\n }\n}\n\n// Runs, trigger hooks, and the editor: each waits only behind its own lane.\nexport type PieceWorkerLane = \"run\" | \"trigger\" | \"design\";\n\nexport interface PieceWorkerPoolOptions extends PieceWorkerOptions {\n // Most children serving runs and design-time requests at once. Sized from\n // the container's cores and memory when unset.\n size?: number;\n // How many requests may wait for a child. 0 is unbounded: latency rather\n // than failure.\n maxQueueDepth?: number;\n // Children reserved for trigger hooks.\n triggerSlots?: number;\n // Children reserved for the editor's describe, options and connection checks.\n designSlots?: number;\n // Idle run children kept warm rather than retired.\n minWarm?: number;\n // Requests a child serves before it is retired, for leaks outside the heap.\n maxRequests?: number;\n // An idle child above the warm minimum exits after this long.\n idleMs?: number;\n // Children booting at once; more forks than this slow every boot.\n maxConcurrentForks?: number;\n // The reactor's own worker threads, which share the container's cores.\n reactorThreads?: number;\n // The container's memory, checked before each fork. Read from the cgroup by\n // default; a test substitutes its own.\n memory?: () => ContainerMemory | undefined;\n // Builds one worker. Defaults to a forked child; a test or a remote\n // deployment substitutes its own.\n createWorker?: (options: PieceWorkerOptions) => IPieceWorker;\n}\n\nexport interface ContainerMemory {\n limit: number;\n // Anonymous memory in use: what an out-of-memory kill counts.\n used: number;\n}\n\nexport interface PieceWorkerPoolStats {\n size: number;\n active: number;\n idle: number;\n waiting: number;\n}\n\nexport const DEFAULT_WORKER_HEAP_MB = 256;\n// Host-bound runs peak at 4-8 children; past this, a large host with no memory\n// limit could fork until it runs out.\nexport const DEFAULT_POOL_MAX = 32;\nconst DEFAULT_TRIGGER_SLOTS = 1;\nconst DEFAULT_DESIGN_SLOTS = 1;\nconst DEFAULT_MIN_WARM = 1;\nconst DEFAULT_MAX_REQUESTS = 1_000;\nconst DEFAULT_IDLE_MS = 60_000;\nconst DEFAULT_MAX_CONCURRENT_FORKS = 4;\n// A child is retired between requests past this share of its heap budget.\nconst HEAP_RETIREMENT = 0.8;\n// RSS over V8 heap total, measured on children with 1 to 14 pieces loaded.\nconst RSS_PER_HEAP = 1.6;\n// Forks stop while anonymous memory plus one child would pass this share.\nconst FORK_HEADROOM = 0.9;\n// About 0.3 cores per busy reactor executor thread.\nconst REACTOR_THREADS_PER_CORE = 3;\n// A fresh child's RSS, until a child has reported its own.\nconst FRESH_CHILD_BYTES = 80 * 1024 * 1024;\nconst MIB = 1024 * 1024;\n// A fork counts against the cap this long at most; boots measured 20-75ms.\nconst BOOT_WINDOW_MS = 1_000;\nconst LANES = [\"run\", \"trigger\", \"design\"] as const;\n\ninterface Child {\n readonly worker: IPieceWorker;\n readonly lane: PieceWorkerLane;\n // Bundles this child has loaded, so a request can find one already warm.\n readonly loaded: Set<string>;\n requests: number;\n busy: boolean;\n // Booting until its first reply or BOOT_WINDOW_MS, whichever comes first.\n forkedAt: number;\n replied: boolean;\n // Killed by a session closing mid-request; never handed out again.\n doomed: boolean;\n idleSince: number;\n session: PieceWorkerSession | undefined;\n}\n\ninterface Waiter {\n session: PieceWorkerSession;\n key: string | undefined;\n resolve: (child: Child) => void;\n reject: (error: unknown) => void;\n}\n\nfunction pieceKey(request: { bundleDir?: string; entryPath?: string }) {\n return request.bundleDir ?? request.entryPath;\n}\n\n// The most children the host can carry: the cores left after the reactor's\n// threads, or the memory left after the host, whichever is smaller.\nexport function defaultPoolSize(\n options: { reactorThreads?: number; heapMb?: number } = {},\n): number {\n const reactorThreads = Math.max(0, options.reactorThreads ?? 0);\n const cores =\n 2 * os.availableParallelism() -\n 1 -\n Math.floor(reactorThreads / REACTOR_THREADS_PER_CORE);\n const constrained = process.constrainedMemory();\n const limit =\n constrained > 0 && constrained < os.totalmem()\n ? constrained\n : os.totalmem();\n const perChild =\n RSS_PER_HEAP * (options.heapMb ?? DEFAULT_WORKER_HEAP_MB) * MIB;\n const memory = Math.floor((limit - process.memoryUsage.rss()) / perChild);\n return Math.max(1, Math.min(cores, memory, DEFAULT_POOL_MAX));\n}\n\n// cgroup v2 only; undefined outside a memory-limited container.\nexport function cgroupMemory(): ContainerMemory | undefined {\n try {\n const max = readFileSync(\"/sys/fs/cgroup/memory.max\", \"utf8\").trim();\n if (max === \"max\") return undefined;\n const stat = readFileSync(\"/sys/fs/cgroup/memory.stat\", \"utf8\");\n const anon = /^anon (\\d+)$/m.exec(stat)?.[1];\n if (!anon) return undefined;\n return { limit: Number(max), used: Number(anon) };\n } catch {\n return undefined;\n }\n}\n\n// At most one read a second: the reads are synchronous, on the main thread\n// the run dispatcher admits against.\nfunction cachedCgroupMemory(): () => ContainerMemory | undefined {\n let readAt = -Infinity;\n let last: ContainerMemory | undefined;\n return () => {\n const now = performance.now();\n if (now - readAt >= 1_000) {\n last = cgroupMemory();\n readAt = now;\n }\n return last;\n };\n}\n\n// A run's or a caller's handle on the pool. Holds no child of its own: each\n// request leases one, so a run whose steps are all core blocks forks nothing.\nexport class PieceWorkerSession implements IPieceWorker {\n private closed = false;\n\n constructor(\n private readonly pool: PieceWorkerPool,\n /** @internal */\n readonly lane: PieceWorkerLane,\n ) {}\n\n runAction(\n request: RunActionRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.runAction(request, options),\n );\n }\n\n resolveOptions(\n request: ResolveOptionsRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.resolveOptions(request, options),\n );\n }\n\n checkConnection(\n request: CheckConnectionRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.checkConnection(request, options),\n );\n }\n\n describePiece(\n request: DescribePieceRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.describePiece(request, options),\n );\n }\n\n runTriggerHook(\n request: TriggerHookRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.pool.request(this, pieceKey(request), (worker) =>\n worker.runTriggerHook(request, options),\n );\n }\n\n // Refuses this session's queued requests and kills any child serving one:\n // a run cancelled mid-step stops its piece code. Idempotent.\n close(): void {\n if (this.closed) return;\n this.closed = true;\n this.pool.closeSession(this);\n }\n\n /** @internal */\n isClosed(): boolean {\n return this.closed;\n }\n\n // IPieceWorker's teardown is this session's close: a caller holding one\n // through the interface ends its own requests, not the pool.\n dispose(): void {\n this.close();\n }\n}\n\nexport class PieceWorkerPool {\n readonly size: number;\n /** @internal */\n readonly telemetry: WorkflowTelemetry | undefined;\n private readonly maxQueueDepth: number;\n // Children reserved for trigger hooks; the supervisor runs as many at once.\n readonly triggerSlots: number;\n private readonly designSlots: number;\n private readonly minWarm: number;\n private readonly maxRequests: number;\n private readonly idleMs: number;\n private readonly maxConcurrentForks: number;\n private readonly heapMb: number;\n private readonly memory: () => ContainerMemory | undefined;\n private readonly createWorker: (options: PieceWorkerOptions) => IPieceWorker;\n private readonly workerOptions: PieceWorkerOptions;\n private readonly children = new Set<Child>();\n private readonly waiters: Record<PieceWorkerLane, Waiter[]> = {\n run: [],\n trigger: [],\n design: [],\n };\n private largestChild = FRESH_CHILD_BYTES;\n private idleTimer: NodeJS.Timeout | undefined;\n private bootTimer: NodeJS.Timeout | undefined;\n private disposed = false;\n\n constructor(options: PieceWorkerPoolOptions = {}) {\n const {\n size,\n maxQueueDepth,\n triggerSlots,\n designSlots,\n minWarm,\n maxRequests,\n idleMs,\n maxConcurrentForks,\n reactorThreads,\n memory,\n createWorker,\n ...workerOptions\n } = options;\n this.heapMb = workerOptions.heapMb ?? DEFAULT_WORKER_HEAP_MB;\n this.size = Math.max(\n 1,\n Math.trunc(\n size ?? defaultPoolSize({ reactorThreads, heapMb: this.heapMb }),\n ),\n );\n this.maxQueueDepth = Math.max(0, Math.trunc(maxQueueDepth ?? 0));\n this.triggerSlots = Math.max(\n 1,\n Math.trunc(triggerSlots ?? DEFAULT_TRIGGER_SLOTS),\n );\n this.designSlots = Math.max(\n 1,\n Math.trunc(designSlots ?? DEFAULT_DESIGN_SLOTS),\n );\n this.minWarm = Math.max(0, Math.trunc(minWarm ?? DEFAULT_MIN_WARM));\n this.maxRequests = Math.max(1, maxRequests ?? DEFAULT_MAX_REQUESTS);\n this.idleMs = Math.max(0, idleMs ?? DEFAULT_IDLE_MS);\n this.maxConcurrentForks = Math.max(\n 1,\n maxConcurrentForks ?? DEFAULT_MAX_CONCURRENT_FORKS,\n );\n this.memory = memory ?? cachedCgroupMemory();\n this.createWorker = createWorker ?? ((o) => new PieceWorker(o));\n this.workerOptions = { ...workerOptions, heapMb: this.heapMb };\n this.telemetry = workerOptions.telemetry;\n }\n\n // A handle for one run, the design-time editor, or the trigger supervisor.\n // Free until it makes a request; on a disposed pool every request rejects.\n session(lane: PieceWorkerLane = \"run\"): PieceWorkerSession {\n return new PieceWorkerSession(this, lane);\n }\n\n // Run children serving a request or idle, and requests waiting for one. The\n // wait is what a queue-depth alarm watches.\n stats(): PieceWorkerPoolStats {\n let active = 0;\n let idle = 0;\n for (const child of this.children) {\n if (child.lane !== \"run\") continue;\n if (child.busy) active++;\n else idle++;\n }\n return { size: this.size, active, idle, waiting: this.waiters.run.length };\n }\n\n // Kills every child, mid-request ones too, and refuses queued requests.\n // For shutdown; a live run does not survive it.\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n clearTimeout(this.bootTimer);\n this.bootTimer = undefined;\n for (const lane of LANES) {\n for (const waiter of this.waiters[lane].splice(0)) {\n waiter.reject(new PieceWorkerDisposedError());\n }\n }\n for (const child of this.children) child.worker.dispose();\n this.children.clear();\n }\n\n /** @internal — one request on a leased child. */\n async request<T>(\n session: PieceWorkerSession,\n key: string | undefined,\n fn: (worker: IPieceWorker) => Promise<T>,\n ): Promise<T> {\n if (session.isClosed()) throw new PieceWorkerSessionClosedError();\n const child = await this.lease(session, key);\n // Closed or disposed while it waited: the child is killed, not used.\n if (this.disposed) {\n this.giveBack(child, key);\n throw new PieceWorkerDisposedError();\n }\n if (session.isClosed()) {\n this.giveBack(child, key);\n throw new PieceWorkerSessionClosedError();\n }\n try {\n return await fn(child.worker);\n } finally {\n this.giveBack(child, key);\n }\n }\n\n /** @internal — a session that closed. */\n closeSession(session: PieceWorkerSession): void {\n const queue = this.waiters[session.lane];\n for (let i = queue.length - 1; i >= 0; i--) {\n if (queue[i].session !== session) continue;\n const [waiter] = queue.splice(i, 1);\n waiter.reject(new PieceWorkerSessionClosedError());\n }\n for (const child of this.children) {\n if (child.busy && child.session === session) {\n child.doomed = true;\n child.worker.dispose();\n }\n }\n }\n\n private lease(\n session: PieceWorkerSession,\n key: string | undefined,\n ): Promise<Child> {\n if (this.disposed) {\n return Promise.reject(new PieceWorkerDisposedError());\n }\n const queue = this.waiters[session.lane];\n // FIFO: a request arriving behind waiters must not overtake them.\n const child = queue.length === 0 ? this.take(session.lane, key) : undefined;\n if (child) {\n child.session = session;\n return Promise.resolve(child);\n }\n if (\n session.lane === \"run\" &&\n this.maxQueueDepth > 0 &&\n queue.length >= this.maxQueueDepth\n ) {\n return Promise.reject(\n new PieceWorkerPoolBusyError(this.size, queue.length),\n );\n }\n const wait = new Promise<Child>((resolve, reject) => {\n queue.push({ session, key, resolve, reject });\n });\n // The wait for a child; a run's own timings can't show it.\n return this.telemetry\n ? this.telemetry.phase(\"worker.acquire\", {}, () => wait)\n : wait;\n }\n\n // An idle child with the piece loaded, then the most recently used idle\n // child so the rest can idle out, then a new child.\n private take(lane: PieceWorkerLane, key: string | undefined) {\n let warm: Child | undefined;\n let recent: Child | undefined;\n for (const child of this.children) {\n if (child.lane !== lane || child.busy) continue;\n if (key && child.loaded.has(key)) {\n warm = child;\n break;\n }\n if (!recent || child.idleSince > recent.idleSince) recent = child;\n }\n const child = warm ?? recent ?? this.fork(lane);\n if (child) child.busy = true;\n return child;\n }\n\n private fork(lane: PieceWorkerLane): Child | undefined {\n let inLane = 0;\n let booting = 0;\n let firstBootEnds = Infinity;\n const now = performance.now();\n for (const child of this.children) {\n if (child.lane === lane) inLane++;\n if (!child.replied && now - child.forkedAt < BOOT_WINDOW_MS) {\n booting++;\n firstBootEnds = Math.min(\n firstBootEnds,\n child.forkedAt + BOOT_WINDOW_MS,\n );\n }\n }\n const capacity = {\n run: this.size,\n trigger: this.triggerSlots,\n design: this.designSlots,\n }[lane];\n if (inLane >= capacity) return undefined;\n // A lane's first child forks regardless of either limit, or its requests\n // would wait on another lane's. An out-of-memory kill takes the host.\n if (inLane > 0) {\n if (booting >= this.maxConcurrentForks) {\n this.redispatchAt(firstBootEnds - now);\n return undefined;\n }\n if (!this.roomForChild()) return undefined;\n }\n const child: Child = {\n worker: this.createWorker(this.workerOptions),\n lane,\n loaded: new Set(),\n requests: 0,\n busy: false,\n forkedAt: now,\n replied: false,\n doomed: false,\n idleSince: 0,\n session: undefined,\n };\n this.children.add(child);\n return child;\n }\n\n private roomForChild(): boolean {\n const memory = this.memory();\n if (!memory) return true;\n return memory.used + this.largestChild <= FORK_HEADROOM * memory.limit;\n }\n\n private giveBack(child: Child, key: string | undefined): void {\n child.busy = false;\n child.replied = true;\n child.session = undefined;\n child.requests++;\n child.idleSince = performance.now();\n const health = child.worker.health?.();\n if (health?.memory) {\n this.largestChild = Math.max(this.largestChild, health.memory.rss);\n }\n if (this.spent(child, health)) {\n this.retire(child);\n } else if (key) {\n child.loaded.add(key);\n }\n this.dispatch();\n this.scheduleIdleSweep();\n }\n\n private spent(child: Child, health: PieceWorkerHealth | undefined): boolean {\n if (this.disposed || child.doomed) return true;\n if (child.requests >= this.maxRequests) return true;\n if (!health) return false;\n // Dead or timed out: the next request would fork a stranger anyway.\n if (!health.alive || health.tlsPoisoned) return true;\n return (\n health.memory !== undefined &&\n health.memory.heapUsed > HEAP_RETIREMENT * this.heapMb * MIB\n );\n }\n\n private retire(child: Child): void {\n this.children.delete(child);\n child.worker.dispose();\n }\n\n // Serves waiters in order, each lane on its own.\n private dispatch(): void {\n if (this.disposed) return;\n for (const lane of LANES) {\n const queue = this.waiters[lane];\n while (queue.length > 0) {\n const child = this.take(lane, queue[0].key);\n if (!child) break;\n const waiter = queue.shift()!;\n child.session = waiter.session;\n waiter.resolve(child);\n }\n }\n }\n\n // A boot window that closes with no reply frees a fork; nothing else would\n // tell the waiters.\n private redispatchAt(ms: number): void {\n if (this.bootTimer || this.disposed) return;\n this.bootTimer = setTimeout(\n () => {\n this.bootTimer = undefined;\n this.dispatch();\n },\n Math.max(1, ms),\n );\n this.bootTimer.unref();\n }\n\n private scheduleIdleSweep(): void {\n if (this.idleTimer || this.disposed || this.idleMs === 0) return;\n if (this.retirable().length === 0) return;\n this.idleTimer = setTimeout(() => {\n this.idleTimer = undefined;\n this.sweepIdle();\n }, this.idleMs);\n this.idleTimer.unref();\n }\n\n // Retires children idle past idleMs. Trigger children stay: polls come back\n // on a schedule.\n private sweepIdle(): void {\n const now = performance.now();\n for (const child of this.retirable()) {\n if (now - child.idleSince >= this.idleMs) this.retire(child);\n }\n this.scheduleIdleSweep();\n }\n\n // Idle run children above the warm minimum, oldest first, and every idle\n // editor child: the editor is used now and then.\n private retirable(): Child[] {\n const idle = (lane: PieceWorkerLane) =>\n [...this.children]\n .filter((child) => child.lane === lane && !child.busy)\n .sort((a, b) => a.idleSince - b.idleSince);\n const run = idle(\"run\");\n return [\n ...run.slice(0, Math.max(0, run.length - this.minWarm)),\n ...idle(\"design\"),\n ];\n }\n}\n","// Structural mirror of the powerhouse/workflow document state (doc 08 §5.1).\n// The engine stays decoupled from the generated document-model types.\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport type { BlockResolution, StepPieceRecord } from \"./resolution.js\";\n\n// `schema` is a DYNAMIC prop's resolved child props, keyed by child name.\nexport interface PropertySettingDef {\n prop: string;\n mode?: string;\n schema?: unknown;\n}\n\nexport interface WorkflowTriggerDef {\n id: string;\n pieceName: string;\n pieceVersion: string;\n triggerName: string;\n connectionId?: string | null;\n // A REACTOR connection, for a trigger that declares requireReactor.\n reactorConnectionId?: string | null;\n config?: unknown;\n propertySettings?: PropertySettingDef[] | null;\n}\n\nexport interface WorkflowStepDef {\n id: string;\n key: string;\n name?: string;\n pieceName: string;\n pieceVersion: string;\n actionName: string;\n connectionId?: string | null;\n // A REACTOR connection, for an action that declares requireReactor.\n reactorConnectionId?: string | null;\n config: unknown;\n timeoutSeconds?: number | null;\n propertySettings?: PropertySettingDef[] | null;\n // Passed over at run time: not executed, continues on \"next\" with a null output.\n skip?: boolean | null;\n // The author's retry block, unresolved; `effectiveRetryPolicy` reads it.\n // Falls back to the workflow policy's `defaultRetry`.\n retry?: unknown;\n}\n\nexport interface WorkflowEdgeDef {\n id: string;\n from: string;\n to: string;\n port: string;\n condition?: string | null;\n}\n\nexport interface WorkflowVariableDef {\n key: string;\n value?: unknown;\n}\n\nexport interface WorkflowDefinition {\n name?: string;\n trigger?: WorkflowTriggerDef | null;\n steps: WorkflowStepDef[];\n edges: WorkflowEdgeDef[];\n variables?: WorkflowVariableDef[];\n}\n\nexport interface BlockExecution {\n block: BlockRef;\n // Step config with expressions already resolved against the run scope.\n config: unknown;\n connectionId?: string | null;\n reactorConnectionId?: string | null;\n step: WorkflowStepDef;\n // Run-wide secret values (SECRET variables) the executor redacts as well.\n redactValues?: string[];\n}\n\nexport interface BlockResult {\n output: unknown;\n // Output port routing the step's outgoing edges; defaults to \"next\".\n port?: string;\n // Secret values this step ran with. The live output keeps them, so the next\n // step still works; only the journaled copy has them replaced.\n redactValues?: string[];\n // The piece version this step ran, when a piece ran it.\n resolution?: BlockResolution;\n}\n\nexport interface BlockExecutor {\n execute(execution: BlockExecution): Promise<BlockResult>;\n}\n\n// REPLAYED: output reused from a prior run's journal instead of executing.\n// SKIPPED: never reached, or flagged `skip` (then it carries port \"next\").\n// INDETERMINATE: the step neither returned nor failed — a host call it made\n// timed out, so a write it asked for may well have been committed. Reporting\n// that as FAILED would be a claim nobody can stand behind, so it is its own\n// state: it takes no port, ends the run, and never replays on rerun.\nexport type StepExecutionStatus =\n | \"SUCCEEDED\"\n | \"FAILED\"\n | \"SKIPPED\"\n | \"REPLAYED\"\n | \"INDETERMINATE\";\n\nexport interface StepExecutionRecord {\n stepId: string;\n key: string;\n pieceName: string;\n // The step's action, or the trigger's name for a trigger test.\n blockName: string;\n status: StepExecutionStatus;\n // Resolved config the block ran with; absent for skipped steps.\n input?: unknown;\n output?: unknown;\n /**\n * Journaled in the output column in place of `output`, when there is no\n * output to hand a caller but the row still has to say something.\n *\n * One use today: a REPLAYED step whose journaled output the payload cap\n * truncated. The record's `output` stays absent — a caller must not be\n * handed a marker where real data goes — while the row keeps the marker, so\n * a SECOND rerun still knows the output is gone and tells a downstream step\n * by name instead of resolving it to nothing.\n */\n journaledOutput?: unknown;\n port?: string;\n error?: string;\n // The thrown error's name, e.g. ReactorAccessDeniedError.\n errorName?: string;\n // ISO times the block ran between; absent for skipped and replayed steps.\n startedAt?: string;\n endedAt?: string;\n // The piece version that ran; absent for an unresolved block.\n piece?: StepPieceRecord;\n // Hash of the step definition it ran from; rerun replays only an unchanged one.\n configHash?: string;\n // How many times the block ran, when its retry policy let it run more than\n // once. Absent for a single attempt, so an unretried step journals as it did.\n attempts?: number;\n}\n\n// CANCELLED: the run passed its `runTimeoutSeconds`, or a firing was skipped\n// because the workflow's concurrency mode is SINGLETON and a run was active.\n// Neither is a failure of the workflow, which is why it is not FAILED.\nexport type WorkflowRunStatus = \"SUCCEEDED\" | \"FAILED\" | \"CANCELLED\";\n\nexport interface WorkflowRunResult {\n status: WorkflowRunStatus;\n steps: StepExecutionRecord[];\n error?: string;\n errorName?: string;\n // What ran but deserves a look, e.g. an edge on a port nothing emits.\n warnings?: string[];\n}\n\nexport function stepBlock(\n step: Pick<WorkflowStepDef, \"pieceName\" | \"pieceVersion\" | \"actionName\">,\n): BlockRef {\n return {\n pieceName: step.pieceName,\n pieceVersion: step.pieceVersion,\n kind: \"action\",\n name: step.actionName,\n };\n}\n\nexport function triggerBlock(\n trigger: Pick<\n WorkflowTriggerDef,\n \"pieceName\" | \"pieceVersion\" | \"triggerName\"\n >,\n): BlockRef {\n return {\n pieceName: trigger.pieceName,\n pieceVersion: trigger.pieceVersion,\n kind: \"trigger\",\n name: trigger.triggerName,\n };\n}\n","// Secret references and the provider/store seams. Refs are server-minted\n// random ids — stable handles over mutable values, never content hashes.\n\nexport const SECRET_REF_PREFIX = \"secret://v1:\";\n\nconst SECRET_ID_PATTERN = /^[0-9a-f]{32}$/;\n\n// Read seam consumed by the engine (connection resolution).\nexport interface SecretProvider {\n get(ref: string): Promise<string>;\n}\n\nexport interface SecretStat {\n ref: string;\n label: string | null;\n version: number;\n status: \"ACTIVE\" | \"DELETED\";\n createdAt: string;\n updatedAt: string;\n}\n\n// Full lifecycle, implemented by managed backends. `get` is execution-context\n// only and must never be exposed over a transport.\nexport interface SecretStore extends SecretProvider {\n create(input: { value: string; label?: string }): Promise<SecretStat>;\n rotate(ref: string, value: string): Promise<SecretStat>;\n stat(ref: string): Promise<SecretStat>;\n list(): Promise<SecretStat[]>;\n delete(ref: string): Promise<void>;\n}\n\nexport class SecretNotFoundError extends Error {\n constructor(ref: string) {\n super(`No secret found for ref \"${ref}\"`);\n this.name = \"SecretNotFoundError\";\n }\n}\n\nexport class SecretDeletedError extends Error {\n constructor(ref: string) {\n super(`Secret \"${ref}\" has been deleted`);\n this.name = \"SecretDeletedError\";\n }\n}\n\nexport class InvalidSecretRefError extends Error {\n constructor(ref: string) {\n super(\n `Invalid secret ref \"${ref}\"; expected ${SECRET_REF_PREFIX}<32 hex chars>`,\n );\n this.name = \"InvalidSecretRefError\";\n }\n}\n\nexport function isSecretRef(ref: string): boolean {\n return (\n ref.startsWith(SECRET_REF_PREFIX) &&\n SECRET_ID_PATTERN.test(ref.slice(SECRET_REF_PREFIX.length))\n );\n}\n\n// Returns the 32-hex id; throws on anything else.\nexport function parseSecretRef(ref: string): string {\n if (!isSecretRef(ref)) throw new InvalidSecretRefError(ref);\n return ref.slice(SECRET_REF_PREFIX.length);\n}\n\nexport function secretRefFromId(id: string): string {\n if (!SECRET_ID_PATTERN.test(id)) throw new InvalidSecretRefError(id);\n return `${SECRET_REF_PREFIX}${id}`;\n}\n\nexport class InMemorySecretProvider implements SecretProvider {\n private readonly secrets: Map<string, string>;\n\n constructor(secrets: Record<string, string>) {\n this.secrets = new Map(Object.entries(secrets));\n }\n\n get(ref: string): Promise<string> {\n const value = this.secrets.get(ref);\n if (value === undefined)\n return Promise.reject(new SecretNotFoundError(ref));\n return Promise.resolve(value);\n }\n}\n","// {{…}} expressions over the run scope. Grammar and rules: README, \"Expressions\".\n\nexport interface ExpressionScope {\n trigger?: unknown;\n // A step contributes `output` when it succeeded and `error` when it did not.\n // The failed entry is what an error-port branch reads.\n steps: Record<string, { output?: unknown; error?: string }>;\n variables: Record<string, unknown>;\n}\n\nexport type PathSegment = string | number;\n\nexport interface PathTerm {\n kind: \"path\";\n segments: PathSegment[];\n // `?` suffix: a missing value resolves to null instead of failing.\n optional: boolean;\n source: string;\n}\n\nexport interface LiteralTerm {\n kind: \"literal\";\n value: string;\n}\n\nexport type ExpressionTerm = PathTerm | LiteralTerm;\n\n// `a || b || 'x'`: the first term with a value other than null or \"\".\nexport interface Expression {\n terms: ExpressionTerm[];\n source: string;\n}\n\nexport class ExpressionSyntaxError extends Error {\n constructor(source: string, detail: string) {\n super(`Invalid expression {{${source}}}: ${detail}`);\n this.name = \"ExpressionSyntaxError\";\n }\n}\n\nexport class UnresolvedReferenceError extends Error {\n constructor(readonly reference: string) {\n super(`Unresolved reference {{${reference}}}`);\n this.name = \"UnresolvedReferenceError\";\n }\n}\n\n/**\n * A value that exists but cannot be read, with the reason attached.\n *\n * The case it was written for: a rerun replaying a SUCCEEDED step whose\n * journaled output the payload cap truncated. The step must NOT run again — it\n * had side effects — but its output is genuinely gone, so a downstream step\n * that reads it has to be told, by name, rather than handed a truncation\n * marker or quietly made to re-run the step that produced it.\n *\n * The reason hangs off a SYMBOL key, so `JSON.stringify` drops it and nothing\n * can leak the wrapper into a payload as data.\n */\nconst UNAVAILABLE = Symbol(\"unavailable\");\n\nexport class UnavailableValueError extends Error {\n constructor(reason: string) {\n super(reason);\n this.name = \"UnavailableValueError\";\n }\n}\n\nexport function unavailableValue(reason: string): unknown {\n return { [UNAVAILABLE]: reason };\n}\n\nfunction unavailableReason(value: unknown): string | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const reason = (value as Record<symbol, unknown>)[UNAVAILABLE];\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/**\n * The reason of the first {@link unavailableValue} anywhere inside a value,\n * however deep, or undefined when there is none.\n *\n * A shallow check is not enough, and that was the hole: `{{steps.charge}}`\n * lands on the step's whole entry rather than on the wrapper, so the wrapper\n * sits one level down as `{ output: <wrapper> }`. The path check saw an\n * ordinary object, handed it over as data, and `JSON.stringify` then dropped\n * the symbol on the way to the piece — the downstream step received `{}` and\n * the reason was gone. Refusing by name is the whole point of the wrapper.\n */\nexport function unavailableValueReason(value: unknown): string | undefined {\n const own = unavailableReason(value);\n if (own !== undefined) return own;\n if (Array.isArray(value)) {\n for (const item of value) {\n const nested = unavailableValueReason(item);\n if (nested !== undefined) return nested;\n }\n return undefined;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const entry of Object.values(value)) {\n const nested = unavailableValueReason(entry);\n if (nested !== undefined) return nested;\n }\n }\n return undefined;\n}\n\n/** True for anything {@link unavailableValue} produced, at any depth of a\n * resolved value. Lets a caller refuse before a piece is handed it. */\nexport function containsUnavailableValue(value: unknown): boolean {\n return unavailableValueReason(value) !== undefined;\n}\n\n/** Throws {@link UnavailableValueError} when a resolved value holds an\n * unavailable wrapper at any depth; the gate every resolved input passes. */\nexport function assertNoUnavailableValue(value: unknown): void {\n const reason = unavailableValueReason(value);\n if (reason !== undefined) throw new UnavailableValueError(reason);\n}\n\nconst IDENT = /[A-Za-z0-9_$-]/;\n\n// A hand-rolled tokenizer: dot and bracket paths, quoted literals, `||`, `?`.\nexport function parseExpression(source: string): Expression {\n let i = 0;\n const fail = (detail: string): never => {\n throw new ExpressionSyntaxError(source, detail);\n };\n const skipSpace = () => {\n while (i < source.length && /\\s/.test(source[i])) i++;\n };\n const readString = (): string => {\n const quote = source[i++];\n let out = \"\";\n while (i < source.length && source[i] !== quote) {\n if (source[i] === \"\\\\\" && i + 1 < source.length) {\n out += source[i + 1];\n i += 2;\n continue;\n }\n out += source[i++];\n }\n if (source[i] !== quote) fail(\"unterminated string\");\n i++;\n return out;\n };\n const readIdent = (): string => {\n const start = i;\n while (i < source.length && IDENT.test(source[i])) i++;\n if (i === start) fail(`expected a name at position ${start}`);\n return source.slice(start, i);\n };\n const readTerm = (): ExpressionTerm => {\n skipSpace();\n const start = i;\n if (source[i] === \"'\" || source[i] === '\"') {\n return { kind: \"literal\", value: readString() };\n }\n const segments: PathSegment[] = [readIdent()];\n for (;;) {\n if (source[i] === \".\") {\n i++;\n segments.push(readIdent());\n continue;\n }\n if (source[i] === \"[\") {\n i++;\n skipSpace();\n if (source[i] === \"'\" || source[i] === '\"') {\n segments.push(readString());\n } else {\n const digits = /^\\d+/.exec(source.slice(i));\n if (!digits) fail(\"a bracket takes a quoted key or an index\");\n segments.push(Number(digits![0]));\n i += digits![0].length;\n }\n skipSpace();\n if (source[i] !== \"]\") fail(\"expected ]\");\n i++;\n continue;\n }\n break;\n }\n const optional = source[i] === \"?\";\n if (optional) i++;\n return {\n kind: \"path\",\n segments,\n optional,\n source: source.slice(start, i),\n };\n };\n\n const terms: ExpressionTerm[] = [readTerm()];\n for (;;) {\n skipSpace();\n if (i >= source.length) break;\n if (source.startsWith(\"||\", i)) {\n i += 2;\n terms.push(readTerm());\n continue;\n }\n fail(`unexpected \"${source[i]}\" at position ${i}`);\n }\n return { terms, source: source.trim() };\n}\n\ninterface Segment {\n kind: \"text\" | \"expression\";\n text: string;\n}\n\n// Splits text into literal runs and {{…}} bodies. `\\{{` is a literal `{{`;\n// `}}` inside a quoted literal does not close; an unclosed `{{` is text.\nexport function splitTemplate(text: string): Segment[] {\n const out: Segment[] = [];\n let pending = \"\";\n let cursor = 0;\n const flush = () => {\n if (pending) out.push({ kind: \"text\", text: pending });\n pending = \"\";\n };\n for (;;) {\n const open = text.indexOf(\"{{\", cursor);\n if (open < 0) break;\n if (open > 0 && text[open - 1] === \"\\\\\") {\n pending += text.slice(cursor, open - 1) + \"{{\";\n cursor = open + 2;\n continue;\n }\n let i = open + 2;\n let quote: string | undefined;\n let close = -1;\n for (; i < text.length; i++) {\n const char = text[i];\n if (quote) {\n if (char === \"\\\\\") i++;\n else if (char === quote) quote = undefined;\n continue;\n }\n if (char === \"'\" || char === '\"') quote = char;\n else if (text.startsWith(\"}}\", i)) {\n close = i;\n break;\n }\n }\n if (close < 0) break;\n pending += text.slice(cursor, open);\n flush();\n out.push({ kind: \"expression\", text: text.slice(open + 2, close) });\n cursor = close + 2;\n }\n pending += text.slice(cursor);\n flush();\n return out;\n}\n\n/** Every expression a string holds, parsed. */\nexport function expressionsIn(text: string): Expression[] {\n return splitTemplate(text)\n .filter((segment) => segment.kind === \"expression\")\n .map((segment) => parseExpression(segment.text));\n}\n\nconst MISSING = Symbol(\"missing\");\n\nexport function lookupPath(\n scope: ExpressionScope,\n segments: readonly PathSegment[],\n): unknown {\n let current: unknown = scope;\n for (const segment of segments) {\n if (current === null || typeof current !== \"object\") return MISSING;\n // Not missing and not readable: say which, before the path walks into it.\n // Shallow on purpose — a container holding one unavailable entry is still\n // readable for every other path through it.\n const blocked = unavailableReason(current);\n if (blocked !== undefined) throw new UnavailableValueError(blocked);\n const record = current as Record<string | number, unknown>;\n if (!Object.prototype.hasOwnProperty.call(record, segment)) return MISSING;\n current = record[segment];\n }\n // What the path landed on is what leaves resolution, so the check here is\n // DEEP: `steps.x.output` lands on the wrapper itself, but `steps.x` lands on\n // the entry holding it, and handing that over would drop the reason on the\n // symbol and give the piece a bare `{}`.\n assertNoUnavailableValue(current);\n return current === undefined ? MISSING : current;\n}\n\nconst isEmpty = (value: unknown) => value === null || value === \"\";\n\nexport function evaluateExpression(\n expression: Expression,\n scope: ExpressionScope,\n): unknown {\n const last = expression.terms.length - 1;\n let value: unknown = null;\n for (const [index, term] of expression.terms.entries()) {\n if (term.kind === \"literal\") {\n value = term.value;\n } else {\n const found = lookupPath(scope, term.segments);\n if (found === MISSING) {\n if (term.optional) value = null;\n else if (index === last)\n throw new UnresolvedReferenceError(term.source);\n else continue;\n } else value = found;\n }\n if (!isEmpty(value)) return value;\n }\n return value;\n}\n\nfunction interpolate(value: unknown): string {\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"object\") return JSON.stringify(value);\n return String(value as string | number | boolean);\n}\n\n// A string that is one {{…}} once trimmed yields the raw value; any other\n// string with expressions is interpolated text.\nexport function resolveTemplate(text: string, scope: ExpressionScope): unknown {\n const segments = splitTemplate(text);\n if (!segments.some((segment) => segment.kind === \"expression\")) {\n return segments.map((segment) => segment.text).join(\"\");\n }\n const meaningful = segments.filter(\n (segment) => segment.kind === \"expression\" || segment.text.trim() !== \"\",\n );\n if (meaningful.length === 1) {\n return evaluateExpression(parseExpression(meaningful[0].text), scope);\n }\n return segments\n .map((segment) =>\n segment.kind === \"text\"\n ? segment.text\n : interpolate(evaluateExpression(parseExpression(segment.text), scope)),\n )\n .join(\"\");\n}\n\n/** Evaluates every string in a value, nested ones included. */\nexport function resolveExpressions(\n value: unknown,\n scope: ExpressionScope,\n): unknown {\n if (typeof value === \"string\") return resolveTemplate(value, scope);\n if (Array.isArray(value)) {\n return value.map((item) => resolveExpressions(item, scope));\n }\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n resolveExpressions(entry, scope),\n ]),\n );\n }\n return value;\n}\n\n// Truthiness of a resolved condition; the strings \"false\" and \"0\" are falsy.\nexport function evaluateCondition(\n condition: string,\n scope: ExpressionScope,\n): boolean {\n const resolved = resolveTemplate(condition, scope);\n if (resolved === \"false\" || resolved === \"0\") return false;\n return Boolean(resolved);\n}\n","// Branch operators, after Activepieces' BranchOperator: one explicit operator\n// over typed operands. A wrongly typed operand fails the step, never coerces.\n\nexport type BranchOperandType =\n | \"text\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"list\"\n | \"any\";\n\nexport interface BranchOperatorSpec {\n label: string;\n // What `left` must hold; `right` is read as the same type, text for lists.\n left: BranchOperandType;\n // Whether `right` is read at all.\n binary: boolean;\n // Whether `caseSensitive` applies.\n text: boolean;\n test: (left: unknown, right: unknown, caseSensitive: boolean) => boolean;\n}\n\nexport class BranchConfigError extends Error {\n constructor(message: string) {\n super(`Branch: ${message}`);\n this.name = \"BranchConfigError\";\n }\n}\n\nfunction describe(value: unknown): string {\n if (value === undefined) return \"nothing\";\n const text = JSON.stringify(value);\n return text.length > 60 ? `${text.slice(0, 57)}...` : text;\n}\n\nfunction asText(value: unknown, side: string, caseSensitive: boolean): string {\n if (\n typeof value !== \"string\" &&\n typeof value !== \"number\" &&\n typeof value !== \"boolean\"\n ) {\n throw new BranchConfigError(`${side} must be text, got ${describe(value)}`);\n }\n const text = String(value);\n return caseSensitive ? text : text.toLowerCase();\n}\n\nconst DECIMAL = /^[-+]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][-+]?\\d+)?$/;\n\nfunction asNumber(value: unknown, side: string): number {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && DECIMAL.test(value.trim())) {\n return Number(value.trim());\n }\n throw new BranchConfigError(\n `${side} must be a number, got ${describe(value)}`,\n );\n}\n\nfunction asBoolean(value: unknown, side: string): boolean {\n if (typeof value === \"boolean\") return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n throw new BranchConfigError(\n `${side} must be true or false, got ${describe(value)}`,\n );\n}\n\nfunction asDate(value: unknown, side: string): number {\n const time =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\" && value.trim() !== \"\"\n ? Date.parse(value)\n : Number.NaN;\n if (!Number.isFinite(time)) {\n throw new BranchConfigError(\n `${side} must be a date, got ${describe(value)}`,\n );\n }\n return time;\n}\n\nfunction asList(value: unknown, side: string): unknown[] {\n if (Array.isArray(value)) return value;\n throw new BranchConfigError(`${side} must be a list, got ${describe(value)}`);\n}\n\nconst blank = (value: unknown) =>\n value === undefined || value === null || value === \"\";\n\nfunction textOp(\n label: string,\n test: (left: string, right: string) => boolean,\n): BranchOperatorSpec {\n return {\n label,\n left: \"text\",\n binary: true,\n text: true,\n test: (left, right, caseSensitive) =>\n test(\n asText(left, \"left\", caseSensitive),\n asText(right, \"right\", caseSensitive),\n ),\n };\n}\n\nfunction numberOp(\n label: string,\n test: (left: number, right: number) => boolean,\n): BranchOperatorSpec {\n return {\n label,\n left: \"number\",\n binary: true,\n text: false,\n test: (left, right) =>\n test(asNumber(left, \"left\"), asNumber(right, \"right\")),\n };\n}\n\nfunction dateOp(\n label: string,\n test: (left: number, right: number) => boolean,\n): BranchOperatorSpec {\n return {\n label,\n left: \"date\",\n binary: true,\n text: false,\n test: (left, right) => test(asDate(left, \"left\"), asDate(right, \"right\")),\n };\n}\n\nfunction unary(\n label: string,\n left: BranchOperandType,\n test: (left: unknown) => boolean,\n): BranchOperatorSpec {\n return { label, left, binary: false, text: false, test };\n}\n\nfunction listHas(\n left: unknown,\n right: unknown,\n caseSensitive: boolean,\n): boolean {\n const wanted = asText(right, \"right\", caseSensitive);\n return asList(left, \"left\").some((item) => {\n if (typeof item === \"object\" && item !== null) return false;\n const text = String(item);\n return (caseSensitive ? text : text.toLowerCase()) === wanted;\n });\n}\n\n// In the order the editor lists them.\nexport const BRANCH_OPERATORS = {\n TEXT_EXACTLY_MATCHES: textOp(\"Text is exactly\", (a, b) => a === b),\n TEXT_DOES_NOT_EXACTLY_MATCH: textOp(\"Text is not exactly\", (a, b) => a !== b),\n TEXT_CONTAINS: textOp(\"Text contains\", (a, b) => a.includes(b)),\n TEXT_DOES_NOT_CONTAIN: textOp(\n \"Text does not contain\",\n (a, b) => !a.includes(b),\n ),\n TEXT_STARTS_WITH: textOp(\"Text starts with\", (a, b) => a.startsWith(b)),\n TEXT_DOES_NOT_START_WITH: textOp(\n \"Text does not start with\",\n (a, b) => !a.startsWith(b),\n ),\n TEXT_ENDS_WITH: textOp(\"Text ends with\", (a, b) => a.endsWith(b)),\n TEXT_DOES_NOT_END_WITH: textOp(\n \"Text does not end with\",\n (a, b) => !a.endsWith(b),\n ),\n NUMBER_IS_EQUAL_TO: numberOp(\"Number equals\", (a, b) => a === b),\n NUMBER_IS_GREATER_THAN: numberOp(\"Number is greater than\", (a, b) => a > b),\n NUMBER_IS_LESS_THAN: numberOp(\"Number is less than\", (a, b) => a < b),\n DATE_IS_EQUAL: dateOp(\"Date is\", (a, b) => a === b),\n DATE_IS_BEFORE: dateOp(\"Date is before\", (a, b) => a < b),\n DATE_IS_AFTER: dateOp(\"Date is after\", (a, b) => a > b),\n BOOLEAN_IS_TRUE: unary(\"Is true\", \"boolean\", (v) => asBoolean(v, \"left\")),\n BOOLEAN_IS_FALSE: unary(\"Is false\", \"boolean\", (v) => !asBoolean(v, \"left\")),\n LIST_CONTAINS: {\n label: \"List contains\",\n left: \"list\",\n binary: true,\n text: true,\n test: listHas,\n },\n LIST_DOES_NOT_CONTAIN: {\n label: \"List does not contain\",\n left: \"list\",\n binary: true,\n text: true,\n test: (left, right, caseSensitive) => !listHas(left, right, caseSensitive),\n },\n LIST_IS_EMPTY: unary(\n \"List is empty\",\n \"list\",\n (v) => asList(v, \"left\").length === 0,\n ),\n LIST_IS_NOT_EMPTY: unary(\n \"List is not empty\",\n \"list\",\n (v) => asList(v, \"left\").length > 0,\n ),\n EXISTS: unary(\"Exists\", \"any\", (v) => !blank(v)),\n DOES_NOT_EXIST: unary(\"Does not exist\", \"any\", blank),\n} satisfies Record<string, BranchOperatorSpec>;\n\nexport type BranchOperator = keyof typeof BRANCH_OPERATORS;\n\n// Operators whose operand may name nothing: missing is what they test for.\nexport const EXISTENCE_OPERATORS: ReadonlySet<string> = new Set<BranchOperator>(\n [\"EXISTS\", \"DOES_NOT_EXIST\"],\n);\n\nconst OPERATORS: Record<string, BranchOperatorSpec> = BRANCH_OPERATORS;\n\nexport const DEFAULT_BRANCH_OPERATOR: BranchOperator = \"TEXT_EXACTLY_MATCHES\";\n\nexport interface BranchOutcome {\n operator: BranchOperator;\n left: unknown;\n right?: unknown;\n result: boolean;\n}\n\n// Config: { operator, left, right?, caseSensitive? }, expressions resolved.\nexport function evaluateBranch(config: unknown): BranchOutcome {\n if (config === null || typeof config !== \"object\" || Array.isArray(config)) {\n throw new BranchConfigError(\"the config must be an object\");\n }\n const { operator, left, right, caseSensitive } = config as Record<\n string,\n unknown\n >;\n if (operator === undefined || operator === null || operator === \"\") {\n throw new BranchConfigError(\"an operator is required\");\n }\n if (typeof operator !== \"string\" || !Object.hasOwn(OPERATORS, operator)) {\n throw new BranchConfigError(`unknown operator ${describe(operator)}`);\n }\n if (caseSensitive !== undefined && typeof caseSensitive !== \"boolean\") {\n throw new BranchConfigError(\"caseSensitive must be true or false\");\n }\n const spec = OPERATORS[operator];\n const result = spec.test(left, right, caseSensitive === true);\n return {\n operator: operator as BranchOperator,\n left,\n ...(spec.binary ? { right } : {}),\n result,\n };\n}\n","// A step's config with its expressions resolved, as the step receives it.\nimport { CORE_PIECE_NAME } from \"@powerhousedao/pieces-framework/workflow\";\nimport { EXISTENCE_OPERATORS } from \"../core/branch-operators.js\";\nimport {\n assertNoUnavailableValue,\n resolveExpressions,\n UnresolvedReferenceError,\n type ExpressionScope,\n} from \"./expressions.js\";\nimport type { WorkflowStepDef } from \"./types.js\";\n\ntype StepInputSource = Pick<\n WorkflowStepDef,\n \"pieceName\" | \"actionName\" | \"config\"\n>;\n\n/**\n * A step's resolved input, and the last gate before it crosses to the piece.\n *\n * The unavailable wrapper carries its reason on a symbol, so anything that\n * serializes it loses the reason — the worker boundary included. Checking the\n * whole resolved input here, at any depth, is what guarantees that no route\n * through resolution can hand a piece the wrapper as data: the path checks\n * inside `lookupPath` catch the ways an expression reaches one, and this\n * catches whatever they do not.\n */\nexport function resolveStepInput(\n step: StepInputSource,\n scope: ExpressionScope,\n): unknown {\n const input = resolveStepInputRaw(step, scope);\n assertNoUnavailableValue(input);\n return input;\n}\n\n// An existence test asks whether its operand names anything, so a reference\n// that resolves to nothing is its answer rather than an error.\nfunction resolveStepInputRaw(\n step: StepInputSource,\n scope: ExpressionScope,\n): unknown {\n const { config } = step;\n if (\n step.pieceName !== CORE_PIECE_NAME ||\n step.actionName !== \"branch\" ||\n config === null ||\n typeof config !== \"object\" ||\n Array.isArray(config) ||\n !Object.hasOwn(config, \"left\")\n ) {\n return resolveExpressions(config, scope);\n }\n const record = config as Record<string, unknown>;\n const operator = resolveExpressions(record.operator, scope);\n if (typeof operator !== \"string\" || !EXISTENCE_OPERATORS.has(operator)) {\n return resolveExpressions(config, scope);\n }\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [\n key,\n key === \"left\"\n ? resolveOrMissing(value, scope)\n : resolveExpressions(value, scope),\n ]),\n );\n}\n\nfunction resolveOrMissing(value: unknown, scope: ExpressionScope): unknown {\n try {\n return resolveExpressions(value, scope);\n } catch (error) {\n if (error instanceof UnresolvedReferenceError) return undefined;\n throw error;\n }\n}\n","// Resolves connection references into the auth value a piece reads from\n// ctx.auth, shaped per Activepieces auth kind (powerhouse/connection state).\n\nimport type { SecretProvider } from \"./secrets.js\";\nimport type { WorkflowDefinition } from \"./types.js\";\nimport {\n AppConnectionType,\n type AppConnectionValue,\n type BasicAuthConnectionValue,\n type OAuth2ConnectionValueWithApp,\n} from \"@powerhousedao/pieces-framework\";\n\n// The powerhouse/connection document model's own enum: the framework's\n// AppConnectionType, minus its hosted OAuth2 variants, with NO_AUTH as NONE.\nexport type ConnectionAuthType =\n | `${AppConnectionType.SECRET_TEXT}`\n | `${AppConnectionType.BASIC_AUTH}`\n | `${AppConnectionType.CUSTOM_AUTH}`\n | `${AppConnectionType.OAUTH2}`\n | `${AppConnectionType.OIDC}`\n | \"NONE\";\n\n// Mirrors the powerhouse/connection document state the resolver consumes.\nexport interface ConnectionSource {\n authType: ConnectionAuthType;\n config?: Record<string, unknown>;\n secretRefs?: { name: string; ref: string }[];\n}\n\n// Which step is asking. A resolver needs it to check the request against the\n// run's binding rather than trust the id it was handed.\n\n// piecePackage is the piece the caller resolved the block to.\nexport interface ConnectionRequest {\n piecePackage?: string;\n stepId?: string;\n stepKey?: string;\n}\n\n// The auth a piece reads, plus the concrete secret strings behind it. The\n// second half is what value-based journal redaction matches on.\nexport interface ResolvedConnection {\n auth: unknown;\n secretValues: string[];\n}\n\nexport interface EngineConnectionResolver {\n resolve(connectionId: string, request?: ConnectionRequest): Promise<unknown>;\n // Optional: hosts that predate redaction keep working without it. It takes\n // the same request, so authorization is not skipped to get the secrets.\n resolveWithSecrets?(\n connectionId: string,\n request?: ConnectionRequest,\n ): Promise<ResolvedConnection>;\n}\n\nexport class ConnectionNotFoundError extends Error {\n constructor(connectionId: string) {\n super(`No connection registered for id \"${connectionId}\"`);\n this.name = \"ConnectionNotFoundError\";\n }\n}\n\n// A step reached for a connection its workflow definition never declared.\n// Raised before any lookup, so it cannot say whether the id exists.\nexport class ConnectionNotBoundError extends Error {\n constructor(connectionId: string) {\n super(`Connection \"${connectionId}\" is not bound to this workflow`);\n this.name = \"ConnectionNotBoundError\";\n }\n}\n\nexport class UnsupportedAuthTypeError extends Error {\n constructor(authType: string) {\n super(`Auth type \"${authType}\" is not supported yet`);\n this.name = \"UnsupportedAuthTypeError\";\n }\n}\n\nasync function resolveSecrets(\n source: ConnectionSource,\n secrets: SecretProvider,\n): Promise<Record<string, string>> {\n const entries = await Promise.all(\n (source.secretRefs ?? []).map(\n async ({ name, ref }) => [name, await secrets.get(ref)] as const,\n ),\n );\n return Object.fromEntries(entries);\n}\n\n// Values are AppConnectionValue-shaped: pieces read auth.secret_text,\n// auth.username/password or auth.props.* depending on their auth kind.\nexport async function shapeAuthValue(\n source: ConnectionSource,\n secrets: SecretProvider,\n): Promise<unknown> {\n return (await shapeConnection(source, secrets)).auth;\n}\n\n// Only the values behind `secretRefs` are reported as secret: config fields\n// (a base URL, a username) are not, and redacting them would cost debuggability.\nexport async function shapeConnection(\n source: ConnectionSource,\n secrets: SecretProvider,\n): Promise<ResolvedConnection> {\n const resolved = await resolveSecrets(source, secrets);\n if (source.authType === \"OAUTH2\") return shapeOAuth2(source, resolved);\n return {\n auth: shapeAuth(source, resolved),\n secretValues: Object.values(resolved),\n };\n}\n\n// OAUTH2 keeps client_id in config and client_secret plus the host-written\n// token set (JSON) in secretRefs; the rest are the method's own props.\nfunction shapeOAuth2(\n source: ConnectionSource,\n resolved: Record<string, string>,\n): ResolvedConnection {\n const { client_secret: clientSecret, token, ...secretProps } = resolved;\n const { client_id: clientId, ...configProps } = source.config ?? {};\n if (!token) {\n throw new Error(\n \"This OAuth2 connection is not signed in; connect it first\",\n );\n }\n let tokens: Record<string, unknown>;\n try {\n tokens = JSON.parse(token) as Record<string, unknown>;\n } catch {\n throw new Error(\"Stored OAuth2 token is malformed; reconnect\");\n }\n const text = (value: unknown, fallback = \"\") =>\n typeof value === \"string\" ? value : fallback;\n const auth: OAuth2ConnectionValueWithApp = {\n type: AppConnectionType.OAUTH2,\n client_id: text(clientId),\n client_secret: text(clientSecret),\n redirect_url: text(tokens.redirect_url),\n access_token: text(tokens.access_token),\n refresh_token: text(tokens.refresh_token),\n token_type: text(tokens.token_type, \"Bearer\"),\n claimed_at: Number(tokens.claimed_at ?? 0),\n scope: text(tokens.scope),\n token_url: text(tokens.token_url),\n ...(typeof tokens.expires_in === \"number\"\n ? { expires_in: tokens.expires_in }\n : {}),\n data: (tokens.data ?? {}) as Record<string, unknown>,\n props: { ...configProps, ...secretProps },\n };\n // The token blob itself is never what a piece prints; its parts are.\n const secretValues = [\n clientSecret,\n auth.access_token,\n auth.refresh_token,\n ...Object.values(secretProps),\n ...tokenLikeValues(auth.data),\n ].filter((value): value is string => Boolean(value));\n return { auth, secretValues: [...new Set(secretValues)] };\n}\n\n// Keys naming a credential: id_token, authed_user.access_token, clientSecret.\n// Not every string: a scope or a team name would be blanked all over a log.\nconst TOKEN_KEY = /(token|secret)$/i;\n\nfunction tokenLikeValues(value: unknown, key = \"\"): string[] {\n if (typeof value === \"string\") return TOKEN_KEY.test(key) ? [value] : [];\n if (Array.isArray(value)) {\n return value.flatMap((item) => tokenLikeValues(item, key));\n }\n if (value !== null && typeof value === \"object\") {\n return Object.entries(value).flatMap(([name, item]) =>\n tokenLikeValues(item, name),\n );\n }\n return [];\n}\n\n// NONE is the persisted value; the framework's NO_AUTH case carries no value a\n// piece reads, so ctx.auth stays undefined rather than becoming that shape.\nfunction shapeAuth(\n source: ConnectionSource,\n resolved: Record<string, string>,\n): AppConnectionValue | undefined {\n switch (source.authType) {\n case \"NONE\":\n return undefined;\n case \"SECRET_TEXT\": {\n const values = Object.values(resolved);\n if (values.length !== 1) {\n throw new Error(\n `SECRET_TEXT connection must have exactly one secret ref, got ${values.length}`,\n );\n }\n return { type: AppConnectionType.SECRET_TEXT, secret_text: values[0] };\n }\n case \"BASIC_AUTH\": {\n const props = { ...source.config, ...resolved };\n return {\n type: AppConnectionType.BASIC_AUTH,\n username: props.username,\n password: props.password,\n } as BasicAuthConnectionValue;\n }\n case \"CUSTOM_AUTH\": {\n return {\n type: AppConnectionType.CUSTOM_AUTH,\n props: { ...source.config, ...resolved },\n };\n }\n default:\n throw new UnsupportedAuthTypeError(source.authType);\n }\n}\n\nexport class StaticConnectionResolver implements EngineConnectionResolver {\n private readonly connections: Map<string, ConnectionSource>;\n\n constructor(\n connections: Record<string, ConnectionSource>,\n private readonly secrets: SecretProvider,\n ) {\n this.connections = new Map(Object.entries(connections));\n }\n\n resolve(connectionId: string): Promise<unknown> {\n return this.resolveWithSecrets(connectionId).then(\n (resolved) => resolved.auth,\n );\n }\n\n resolveWithSecrets(connectionId: string): Promise<ResolvedConnection> {\n const source = this.connections.get(connectionId);\n if (!source) {\n return Promise.reject(new ConnectionNotFoundError(connectionId));\n }\n return shapeConnection(source, this.secrets);\n }\n}\n\n// Every connection a definition declares: the trigger's and each step's.\n\n// A templated id is left out — connectionId is never expression-resolved, so\n// it names no connection and a step cannot pick credentials at run time.\nexport function declaredConnectionIds(\n definition: WorkflowDefinition,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n const declare = (connectionId: string | null | undefined) => {\n if (connectionId && !connectionId.includes(\"{{\"))\n declared.add(connectionId);\n };\n declare(definition.trigger?.connectionId);\n for (const step of definition.steps) declare(step.connectionId);\n return declared;\n}\n\n// Every REACTOR connection a definition binds, kept apart from the auth\n// connections so neither resolves as the other.\nexport function declaredReactorConnectionIds(\n definition: WorkflowDefinition,\n): ReadonlySet<string> {\n const declared = new Set<string>();\n const declare = (connectionId: string | null | undefined) => {\n if (connectionId && !connectionId.includes(\"{{\"))\n declared.add(connectionId);\n };\n declare(definition.trigger?.reactorConnectionId);\n for (const step of definition.steps) declare(step.reactorConnectionId);\n return declared;\n}\n\n// The binding in force for the caller, or undefined when there is none. Read\n// per call because one executor serves every concurrent run.\nexport type ConnectionBindingLookup = () => ReadonlySet<string> | undefined;\n\n// Server-side connection binding (doc 08 §10): a step resolves only what the\n// definition its run pinned declared.\n\n// Without a binding nothing resolves, so a path that fails to establish one\n// fails closed.\nexport class BoundConnectionResolver implements EngineConnectionResolver {\n // Present only when the inner resolver has it, because its absence is what\n // tells a caller to fall back to guessing the secrets from the auth value.\n readonly resolveWithSecrets?: (\n connectionId: string,\n request?: ConnectionRequest,\n ) => Promise<ResolvedConnection>;\n\n constructor(\n private readonly inner: EngineConnectionResolver,\n private readonly binding: ConnectionBindingLookup,\n private readonly onRefused?: (\n connectionId: string,\n request?: ConnectionRequest,\n ) => void,\n ) {\n const withSecrets = inner.resolveWithSecrets?.bind(inner);\n if (!withSecrets) return;\n this.resolveWithSecrets = (connectionId, request) =>\n this.bound(connectionId, request)\n ? withSecrets(connectionId, request)\n : Promise.reject(new ConnectionNotBoundError(connectionId));\n }\n\n resolve(connectionId: string, request?: ConnectionRequest): Promise<unknown> {\n if (!this.bound(connectionId, request)) {\n return Promise.reject(new ConnectionNotBoundError(connectionId));\n }\n return this.inner.resolve(connectionId, request);\n }\n\n // Both paths ask the same question, so neither is a way around it.\n private bound(connectionId: string, request?: ConnectionRequest): boolean {\n if (this.binding()?.has(connectionId)) return true;\n this.onRefused?.(connectionId, request);\n return false;\n }\n}\n","// Content-addressed copies of downloaded attachments. A ref names its bytes,\n// so a cached file never goes stale; steps get a clone, never the cache file.\nimport { randomUUID } from \"node:crypto\";\nimport { constants } from \"node:fs\";\nimport {\n copyFile,\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n utimes,\n writeFile,\n} from \"node:fs/promises\";\nimport path from \"node:path\";\n\nexport interface CachedAttachmentMeta {\n fileName?: string;\n contentType?: string;\n size: number;\n}\n\nexport interface AttachmentCacheOptions {\n dir: string;\n // Total bytes kept; the least recently used entries go first.\n maxBytes: number;\n}\n\nconst META = \".json\";\n\nexport class AttachmentCache {\n constructor(private readonly options: AttachmentCacheOptions) {}\n\n private entry(ref: string): string {\n // attachment://v1:<sha256> -> v1-<sha256>; anything else is not cacheable.\n const match = /^attachment:\\/\\/(v\\d+):([a-f0-9]{64})$/i.exec(ref);\n if (!match) throw new Error(`Not a content-addressed reference: ${ref}`);\n return path.join(this.options.dir, `${match[1]}-${match[2].toLowerCase()}`);\n }\n\n static cacheable(ref: string): boolean {\n return /^attachment:\\/\\/v\\d+:[a-f0-9]{64}$/i.test(ref);\n }\n\n // Copies a cached ref to destPath, or returns undefined on a miss.\n async get(\n ref: string,\n destPath: string,\n ): Promise<CachedAttachmentMeta | undefined> {\n const file = this.entry(ref);\n let meta: CachedAttachmentMeta;\n try {\n meta = JSON.parse(\n await readFile(file + META, \"utf8\"),\n ) as CachedAttachmentMeta;\n // A file whose size no longer matches was tampered with or torn.\n if ((await stat(file)).size !== meta.size) {\n await this.remove(file);\n return undefined;\n }\n } catch {\n return undefined;\n }\n // A clone where the filesystem has one: a piece writing to its copy never\n // reaches the cache.\n await copyFile(file, destPath, constants.COPYFILE_FICLONE);\n const now = new Date();\n await utimes(file, now, now).catch(() => undefined);\n return meta;\n }\n\n // Adopts a file just downloaded to srcPath, leaving srcPath in place.\n async put(\n ref: string,\n srcPath: string,\n meta: Omit<CachedAttachmentMeta, \"size\">,\n ): Promise<void> {\n if (this.options.maxBytes <= 0) return;\n const file = this.entry(ref);\n const size = (await stat(srcPath)).size;\n if (size > this.options.maxBytes) return;\n await mkdir(this.options.dir, { recursive: true });\n const tmp = `${file}.${randomUUID()}.tmp`;\n try {\n await copyFile(srcPath, tmp, constants.COPYFILE_FICLONE);\n await writeFile(file + META, JSON.stringify({ ...meta, size }));\n // Rename last: a reader never sees a file without its metadata.\n await rename(tmp, file);\n } catch (error) {\n await rm(tmp, { force: true });\n throw error;\n }\n await this.evict();\n }\n\n private async remove(file: string): Promise<void> {\n await rm(file, { force: true });\n await rm(file + META, { force: true });\n }\n\n private async evict(): Promise<void> {\n const names = await readdir(this.options.dir).catch(() => [] as string[]);\n const entries = await Promise.all(\n names\n .filter((name) => !name.endsWith(META) && !name.endsWith(\".tmp\"))\n .map(async (name) => {\n const file = path.join(this.options.dir, name);\n const info = await stat(file).catch(() => undefined);\n return info\n ? { file, size: info.size, used: info.mtimeMs }\n : undefined;\n }),\n );\n const live = entries\n .filter((e) => e !== undefined)\n .sort((a, b) => b.used - a.used);\n let total = 0;\n for (const entry of live) {\n total += entry.size;\n if (total > this.options.maxBytes) await this.remove(entry.file);\n }\n }\n}\n","// What the core piece declares beyond Activepieces' metadata. The descriptor\n// builder copies these; the in-process executor routes by `portOf`.\n\nexport interface PropHints {\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport function withHints<P extends object>(property: P, hints: PropHints): P {\n return { ...property, ...hints };\n}\n\nexport const shownWhen = (prop: string, oneOf: unknown[]): PropHints => ({\n showWhen: { prop, oneOf },\n});\n\nexport interface PortedAction {\n ports: readonly string[];\n // The port a successful result leaves on.\n portOf: (output: unknown) => string;\n}\n\nexport function withPorts<A extends object>(\n action: A,\n ported: PortedAction,\n): A & PortedAction {\n return Object.assign(action, ported);\n}\n\nexport function isPorted(action: unknown): action is PortedAction {\n const candidate = action as Partial<PortedAction> | null;\n return (\n typeof candidate?.portOf === \"function\" && Array.isArray(candidate.ports)\n );\n}\n\n// A form the editor draws instead of the trigger's props, e.g. \"schedule\".\nexport function withDisplay<T extends object>(\n trigger: T,\n display: string,\n): T & { display: string } {\n return Object.assign(trigger, { display });\n}\n","import { createAction, Property } from \"@powerhousedao/pieces-framework\";\nimport {\n BRANCH_PORTS,\n NEXT_PORT,\n PIECE_ACTION_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n BRANCH_OPERATORS,\n DEFAULT_BRANCH_OPERATOR,\n evaluateBranch,\n type BranchOutcome,\n} from \"./branch-operators.js\";\nimport { shownWhen, withHints, withPorts } from \"./hints.js\";\n\nconst operators = Object.entries(BRANCH_OPERATORS);\nconst BINARY_OPERATORS = operators\n .filter(([, spec]) => spec.binary)\n .map(([name]) => name);\nconst TEXT_OPERATORS = operators\n .filter(([, spec]) => spec.text)\n .map(([name]) => name);\n\nexport const branchAction = withPorts(\n createAction({\n name: \"branch\",\n displayName: \"Branch\",\n description:\n \"Takes the true port when the operator holds for its operands, else the \" +\n \"false port. An operand of the wrong type (a number operator on text, a \" +\n \"list operator on something that is not a list) fails the step.\",\n requireAuth: false,\n props: {\n left: Property.ShortText({\n displayName: \"Value\",\n description: \"What to test, usually an expression.\",\n required: true,\n placeholder: \"{{steps.fetch.output.status}}\",\n }),\n operator: Property.StaticDropdown({\n displayName: \"Condition\",\n description: \"How the value is tested.\",\n required: true,\n defaultValue: DEFAULT_BRANCH_OPERATOR,\n options: {\n options: operators.map(([value, spec]) => ({\n value,\n label: spec.label,\n })),\n },\n }),\n right: withHints(\n Property.ShortText({\n displayName: \"Compared with\",\n description: \"The value the condition compares to.\",\n required: true,\n }),\n shownWhen(\"operator\", BINARY_OPERATORS),\n ),\n caseSensitive: withHints(\n Property.Checkbox({\n displayName: \"Case sensitive\",\n description: \"Match letter case exactly.\",\n required: false,\n }),\n shownWhen(\"operator\", TEXT_OPERATORS),\n ),\n },\n run: (ctx) => Promise.resolve(evaluateBranch(ctx.propsValue)),\n }),\n {\n ports: BRANCH_PORTS,\n portOf: (output) => ((output as BranchOutcome).result ? \"true\" : \"false\"),\n },\n);\n\nfunction assertionText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null) return \"\";\n return JSON.stringify(value);\n}\n\nfunction normalizedList(entries: unknown): string[] {\n const list =\n typeof entries === \"string\"\n ? [entries]\n : Array.isArray(entries)\n ? entries\n : [];\n return list\n .map((entry) => String(entry).trim().toLowerCase())\n .filter(Boolean);\n}\n\n// Model output is the motivating case: an empty completion, or a classifier\n// answering the wrong question, must not flow on to a step with a side effect.\nexport const assertAction = withPorts(\n createAction({\n name: \"assert\",\n displayName: \"Assert\",\n description:\n \"Fails the step when its value is blank or rejected, so a bad value stops \" +\n \"the run instead of reaching a step with a side effect.\",\n requireAuth: false,\n props: {\n value: Property.ShortText({\n displayName: \"Value\",\n description:\n \"e.g. {{steps.describe.output}} - the run fails when it is blank.\",\n required: true,\n }),\n rejectValues: Property.Array({\n displayName: \"Rejected values\",\n description:\n \"One per line; the run fails when the value matches any of them.\",\n required: false,\n }),\n allowValues: Property.Array({\n displayName: \"Allowed values\",\n description:\n \"One per line; when set, anything else fails. Safer than a reject list for model output.\",\n required: false,\n }),\n allowEmpty: Property.Checkbox({\n displayName: \"Allow empty\",\n description: \"Accept a blank value instead of failing.\",\n required: false,\n }),\n message: Property.ShortText({\n displayName: \"Failure message\",\n description: \"Replaces the default error.\",\n required: false,\n }),\n },\n run: (ctx) => {\n const { value, rejectValues, allowValues, allowEmpty, message } =\n ctx.propsValue as Record<string, unknown>;\n const trimmed = assertionText(value).trim();\n const fail = (reason: string) =>\n Promise.reject(\n new Error(\n typeof message === \"string\" && message\n ? message\n : `Assert: ${reason}`,\n ),\n );\n if (!trimmed && allowEmpty !== true) return fail(\"value is empty\");\n if (normalizedList(rejectValues).includes(trimmed.toLowerCase())) {\n return fail(`value is a rejected value (\"${trimmed}\")`);\n }\n // An allow-list is the safer gate for model output: anything unforeseen\n // fails here rather than reaching a step that writes.\n const allowed = normalizedList(allowValues);\n if (allowed.length > 0 && !allowed.includes(trimmed.toLowerCase())) {\n return fail(\n `value \"${trimmed}\" is not one of the allowed values (${allowed.join(\", \")})`,\n );\n }\n return Promise.resolve({ value });\n },\n }),\n { ports: PIECE_ACTION_PORTS, portOf: () => NEXT_PORT },\n);\n","// The core triggers. The host feeds them, the way the reactor piece's document\n// triggers are fed: schedule.ts, webhook.ts and the manual fire mutation.\nimport {\n createTrigger,\n Property,\n TriggerStrategy,\n} from \"@powerhousedao/pieces-framework\";\nimport {\n SCHEDULE_MODES,\n SCHEDULE_UNIT_MS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport { shownWhen, withDisplay, withHints } from \"./hints.js\";\n\n// A hook that runs would mean the host stopped feeding this trigger.\nfunction hostFed(name: string): () => Promise<never> {\n return () =>\n Promise.reject(\n new Error(`The \"${name}\" trigger is fired by the host, not by its hooks`),\n );\n}\n\nconst hooks = (name: string) => ({\n onEnable: hostFed(name),\n onDisable: hostFed(name),\n run: hostFed(name),\n});\n\nconst options = (entries: [value: string, label: string][]) => ({\n options: entries.map(([value, label]) => ({ value, label })),\n});\n\nexport const scheduleTrigger = withDisplay(\n createTrigger({\n name: \"schedule\",\n displayName: \"Schedule\",\n description:\n \"Fires on a five-field cron expression, or every so many minutes, hours or days.\",\n type: TriggerStrategy.POLLING,\n requireAuth: false,\n props: {\n mode: Property.StaticDropdown({\n displayName: \"Runs\",\n description: \"cron or interval.\",\n required: true,\n defaultValue: \"cron\",\n options: options([\n [SCHEDULE_MODES[0], \"On a cron schedule\"],\n [SCHEDULE_MODES[1], \"At a fixed interval\"],\n ]),\n }),\n cron: withHints(\n Property.ShortText({\n displayName: \"Cron expression\",\n description:\n \"Five fields, e.g. 0 9 * * 1-5 runs at 09:00 on weekdays.\",\n required: true,\n defaultValue: \"0 9 * * 1-5\",\n }),\n shownWhen(\"mode\", [\"cron\"]),\n ),\n every: withHints(\n Property.Number({\n displayName: \"Every\",\n description: \"A whole number of units, at least 1.\",\n required: true,\n defaultValue: 15,\n }),\n shownWhen(\"mode\", [\"interval\"]),\n ),\n unit: withHints(\n Property.StaticDropdown({\n displayName: \"Unit\",\n description: \"minutes, hours or days.\",\n required: true,\n defaultValue: \"minutes\",\n options: {\n options: Object.keys(SCHEDULE_UNIT_MS).map((unit) => ({\n value: unit,\n label: unit.charAt(0).toUpperCase() + unit.slice(1),\n })),\n },\n }),\n shownWhen(\"mode\", [\"interval\"]),\n ),\n timezone: Property.ShortText({\n displayName: \"Timezone\",\n description: \"An IANA name such as Europe/Lisbon. Defaults to UTC.\",\n required: false,\n defaultValue: \"UTC\",\n }),\n },\n sampleData: {\n scheduledFor: \"2026-09-28T09:00:00.000Z\",\n firedAt: \"2026-09-28T09:00:00.120Z\",\n timezone: \"UTC\",\n cron: \"0 9 * * 1-5\",\n },\n ...hooks(\"schedule\"),\n }),\n \"schedule\",\n);\n\n// Every scheme that verifies a signature, and so needs a secret.\nconst SIGNED_SCHEMES = [\"token\", \"hmac\", \"hmac-prefixed\", \"hmac-timestamped\"];\n\n// Schemes that compute a digest, and so take a hash and an encoding.\nconst HMAC_SCHEMES = [\"hmac\", \"hmac-prefixed\", \"hmac-timestamped\"];\n\n// A managed secret's ref, drawn as a secret picker rather than a text field.\nconst SECRET_REF_TYPE = \"PH_SECRET_REF\";\n\nexport const webhookTrigger = createTrigger({\n name: \"webhook\",\n displayName: \"Webhook\",\n description:\n \"Fires on an HTTP delivery to the workflow's endpoint. Ask for the URL \" +\n \"with the webhookEndpoint query rather than constructing it.\",\n type: TriggerStrategy.WEBHOOK,\n requireAuth: false,\n props: {\n methods: Property.StaticDropdown({\n displayName: \"Method\",\n description: \"The HTTP method a delivery must use.\",\n required: true,\n defaultValue: \"POST\",\n options: options([\n [\"POST\", \"POST\"],\n [\"ANY\", \"Any\"],\n [\"GET\", \"GET\"],\n [\"PUT\", \"PUT\"],\n [\"PATCH\", \"PATCH\"],\n [\"DELETE\", \"DELETE\"],\n ]),\n }),\n // Named by wire format, not by sender: one brand name would mislead.\n scheme: Property.StaticDropdown({\n displayName: \"Verification\",\n description: \"How a delivery proves its sender.\",\n required: true,\n defaultValue: \"none\",\n options: options([\n [\"none\", \"None — the URL's token only\"],\n [\"token\", \"Shared token in a header\"],\n [\"hmac\", \"HMAC digest\"],\n [\"hmac-prefixed\", \"HMAC digest with a label (sha256=…)\"],\n [\"hmac-timestamped\", \"HMAC digest, timestamped (t=…,v1=…)\"],\n ]),\n }),\n // Hidden while unverified: a secret there would never be checked.\n secretRef: withHints(\n {\n ...Property.ShortText({\n displayName: \"Secret\",\n description:\n \"The shared secret: the value the header must equal, or the key the sender signs with\",\n required: true,\n }),\n type: SECRET_REF_TYPE as never,\n },\n shownWhen(\"scheme\", SIGNED_SCHEMES),\n ),\n header: withHints(\n Property.ShortText({\n displayName: \"Header\",\n description:\n \"Where the token or signature is read from. Defaults to the header the chosen scheme conventionally uses; set it only if the sender differs\",\n required: false,\n advanced: true,\n }),\n shownWhen(\"scheme\", SIGNED_SCHEMES),\n ),\n toleranceSeconds: withHints(\n Property.Number({\n displayName: \"Replay window (seconds)\",\n description:\n \"Rejects a delivery signed longer ago than this, so a captured request expires. Default 300\",\n required: false,\n advanced: true,\n }),\n shownWhen(\"scheme\", [\"hmac-timestamped\"]),\n ),\n algorithm: withHints(\n Property.StaticDropdown({\n displayName: \"Hash\",\n description: \"How the digest was computed.\",\n required: false,\n advanced: true,\n options: options([\n [\"sha256\", \"SHA-256 (default)\"],\n [\"sha1\", \"SHA-1\"],\n [\"sha512\", \"SHA-512\"],\n ]),\n }),\n shownWhen(\"scheme\", HMAC_SCHEMES),\n ),\n encoding: withHints(\n Property.StaticDropdown({\n displayName: \"Digest encoding\",\n description: \"How the digest is written.\",\n required: false,\n advanced: true,\n options: options([\n [\"hex\", \"Hexadecimal (default)\"],\n [\"base64\", \"Base64\"],\n ]),\n }),\n shownWhen(\"scheme\", HMAC_SCHEMES),\n ),\n prefix: withHints(\n Property.ShortText({\n displayName: \"Signature label\",\n description:\n \"The text before the digest. Left empty it is the hash name and an equals sign, e.g. sha256=. Tick No label when the sender sends the digest alone\",\n required: false,\n advanced: true,\n }),\n { emptyChoice: \"No label\", ...shownWhen(\"scheme\", [\"hmac-prefixed\"]) },\n ),\n dedupeField: Property.ShortText({\n displayName: \"Event id field\",\n description:\n \"Where the sender puts its own event id, so a redelivery is accepted without a second run. A bare name reads a query param or a top-level body field; prefix with header: or body: to read a header or a nested path (header:x-delivery-id, body:data.object.id)\",\n required: false,\n advanced: true,\n }),\n dedupeTtlSeconds: Property.Number({\n displayName: \"Dedupe window (seconds)\",\n description: \"How long an event id is remembered. Default 300\",\n required: false,\n advanced: true,\n }),\n challengeField: Property.ShortText({\n displayName: \"Challenge field\",\n description:\n \"Echo this field back instead of running, for senders that verify the endpoint before registering it. Same header:/body: prefixes as the event id field\",\n required: false,\n advanced: true,\n }),\n responseMode: Property.StaticDropdown({\n displayName: \"Response\",\n description: \"Waiting holds the sender's socket open for the whole run\",\n required: false,\n advanced: true,\n defaultValue: \"async\",\n options: options([\n [\"async\", \"Answer immediately (202)\"],\n [\"sync\", \"Wait for the run (200)\"],\n ]),\n }),\n responseStatus: Property.Number({\n displayName: \"Success status\",\n description: \"Status returned on acceptance. Default 202 async, 200 sync\",\n required: false,\n advanced: true,\n }),\n },\n sampleData: {\n method: \"POST\",\n path: \"/\",\n headers: { \"content-type\": \"application/json\" },\n queryParams: {},\n body: { event: \"ping\" },\n },\n ...hooks(\"webhook\"),\n});\n\nexport const manualTrigger = createTrigger({\n name: \"manual\",\n displayName: \"Manual\",\n description:\n \"Fires only when something asks it to, with the fire mutation. The trigger \" +\n \"to use for a workflow driven by a test or a script.\",\n type: TriggerStrategy.MANUAL,\n requireAuth: false,\n props: {},\n sampleData: null,\n ...hooks(\"manual\"),\n});\n","","// The core piece ships with the runtime, so it carries the runtime's version.\nimport pkg from \"../../../package.json\" with { type: \"json\" };\n\nexport const CORE_PIECE_VERSION: string = pkg.version;\n","// The built-in core piece: branching, assertions, and the triggers that belong\n// to no service. The runtime registers it itself and always runs this copy.\nimport { createPiece, PieceCategory } from \"@powerhousedao/pieces-framework\";\nimport { CORE_PIECE_NAME } from \"@powerhousedao/pieces-framework/workflow\";\nimport { assertAction, branchAction } from \"./actions.js\";\nimport { manualTrigger, scheduleTrigger, webhookTrigger } from \"./triggers.js\";\nimport { CORE_PIECE_VERSION } from \"./version.js\";\n\nexport { CORE_PIECE_NAME, CORE_PIECE_VERSION };\nexport * from \"./branch-operators.js\";\nexport { isPorted, type PortedAction, type PropHints } from \"./hints.js\";\n\nexport const corePiece = createPiece({\n displayName: \"Core\",\n description:\n \"The engine's own blocks: branching, assertions, and the triggers that \" +\n \"belong to no service.\",\n logoUrl: \"\",\n authors: [\"powerhouse\"],\n auth: undefined,\n categories: [PieceCategory.CORE],\n actions: [branchAction, assertAction],\n triggers: [scheduleTrigger, webhookTrigger, manualTrigger],\n});\n","// Pieces the runtime ships and registers itself. They are this package's own\n// code, so they are described and run in process rather than in the worker.\nimport type { BlockIdentity } from \"@powerhousedao/pieces-framework/block-type\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport type { LocalPiece } from \"./activepieces/resolver.js\";\nimport {\n buildDescriptor,\n type PieceDescriptor,\n} from \"./activepieces/descriptor.js\";\nimport { getActions, type ApPiece } from \"./activepieces/types.js\";\nimport {\n CORE_PIECE_NAME,\n CORE_PIECE_VERSION,\n corePiece,\n isPorted,\n} from \"./core/index.js\";\n\nexport interface BuiltinPiece {\n name: string;\n version: string;\n piece: ApPiece;\n}\n\nconst BUILTIN_PIECES: readonly BuiltinPiece[] = [\n {\n name: CORE_PIECE_NAME,\n version: CORE_PIECE_VERSION,\n piece: corePiece as unknown as ApPiece,\n },\n];\n\nexport function builtinPiece(name: string): BuiltinPiece | undefined {\n return BUILTIN_PIECES.find((entry) => entry.name === name);\n}\n\nexport function isBuiltinPiece(name: string): boolean {\n return builtinPiece(name) !== undefined;\n}\n\n// As the resolver sees it: installed, with nothing on disk to load.\nexport function builtinLocalPieces(): LocalPiece[] {\n return BUILTIN_PIECES.map(({ name, version }) => ({ name, version }));\n}\n\nconst descriptors = new Map<string, PieceDescriptor>();\n\nexport function describeBuiltinPiece(builtin: BuiltinPiece): PieceDescriptor {\n let descriptor = descriptors.get(builtin.name);\n if (!descriptor) {\n descriptor = buildDescriptor(\n builtin.piece,\n { packageName: builtin.name, version: builtin.version },\n { routed: true, hostFed: true },\n );\n descriptors.set(builtin.name, descriptor);\n }\n return descriptor;\n}\n\n// What a block's edges may leave on: a built-in block's own list, else the\n// ports every piece action or trigger declares.\nexport function blockPorts(\n block: BlockIdentity,\n): readonly string[] | undefined {\n const builtin = builtinPiece(block.pieceName);\n if (builtin) {\n const descriptor = describeBuiltinPiece(builtin);\n const entries: { name: string; ports: readonly string[] }[] =\n block.kind === \"trigger\" ? descriptor.triggers : descriptor.actions;\n return entries.find((entry) => entry.name === block.name)?.ports;\n }\n return block.kind === \"trigger\" ? TRIGGER_PORTS : PIECE_ACTION_PORTS;\n}\n\nexport class UnknownBuiltinActionError extends Error {\n constructor(piece: string, action: string) {\n super(`${piece} has no action \"${action}\"`);\n this.name = \"UnknownBuiltinActionError\";\n }\n}\n\n// Only propsValue is served: a built-in action reaches nothing else.\nexport async function runBuiltinAction(\n builtin: BuiltinPiece,\n actionName: string,\n propsValue: Record<string, unknown>,\n): Promise<{ output: unknown; port?: string }> {\n const action = getActions(builtin.piece)[actionName] as unknown;\n if (!action || typeof (action as { run?: unknown }).run !== \"function\") {\n throw new UnknownBuiltinActionError(builtin.name, actionName);\n }\n const output = await (\n action as { run: (ctx: unknown) => Promise<unknown> }\n ).run({ propsValue });\n return {\n output,\n ...(isPorted(action) ? { port: action.portOf(output) } : {}),\n };\n}\n","// What a block resolved to: the piece version that runs and where it came\n// from. A version mismatch never fails; only `missing` does.\nimport type {\n BlockIdentity,\n BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\n\nexport type PieceOrigin = \"local\" | \"registry\" | \"activepieces\" | \"npm\";\n\nexport type BlockMatch =\n | \"exact\"\n | \"compatible\"\n | \"fallback\"\n | \"installed\"\n | \"missing\";\n\nexport interface BlockResolution {\n requested: BlockRef;\n // No source: a caller outside a reactor, which tries every download source.\n resolved?: { version: string; source?: PieceOrigin };\n match: BlockMatch;\n // Human text for the badge; absent when the pin ran as written.\n note?: string;\n // Newest version any source offers, for \"update available\".\n latestVersion?: string;\n // Set when nothing resolved and a source could not be asked.\n unreachable?: string;\n}\n\n// What a step's journal row keeps of its resolution.\nexport interface StepPieceRecord {\n version: string;\n source?: PieceOrigin;\n match: BlockMatch;\n note?: string;\n}\n\nexport function pieceRecord(\n resolution: BlockResolution | undefined,\n): StepPieceRecord | undefined {\n if (!resolution?.resolved) return undefined;\n return {\n version: resolution.resolved.version,\n ...(resolution.resolved.source\n ? { source: resolution.resolved.source }\n : {}),\n match: resolution.match,\n ...(resolution.note ? { note: resolution.note } : {}),\n };\n}\n\n// How a block reads in a message: `@acme/piece-http@1.2.0 action \"send\"`.\nexport function blockLabel(block: BlockIdentity | BlockRef): string {\n const version = \"pieceVersion\" in block ? `@${block.pieceVersion}` : \"\";\n return `${block.pieceName}${version} ${block.kind} \"${block.name}\"`;\n}\n\nexport class UnknownBlockError extends Error {\n constructor(\n block: BlockIdentity | BlockRef,\n detail = `No executor registered for ${blockLabel(block)}`,\n ) {\n super(detail);\n this.name = \"UnknownBlockError\";\n }\n}\n\nexport function unpinnedNote(block: BlockRef): string {\n return `${block.pieceName} ${block.kind} \"${block.name}\" pins \"${block.pieceVersion}\", which is not an exact semver version`;\n}\n\n// The message a missing resolution fails with.\nexport function missingError(resolution: BlockResolution): Error {\n return new UnknownBlockError(resolution.requested, resolution.note);\n}\n\nconst RESOLUTION = Symbol.for(\"reactor-workflow.block-resolution\");\n\n// A failed step still journals what it resolved to.\nexport function withResolution<T>(\n error: T,\n resolution: BlockResolution | undefined,\n): T {\n if (resolution && error !== null && typeof error === \"object\") {\n (error as Record<symbol, unknown>)[RESOLUTION] = resolution;\n }\n return error;\n}\n\nexport function resolutionOf(error: unknown): BlockResolution | undefined {\n if (error === null || typeof error !== \"object\") return undefined;\n return (error as Record<symbol, BlockResolution | undefined>)[RESOLUTION];\n}\n","import {\n blockKey,\n isExactVersion,\n type BlockKind,\n type BlockRef,\n} from \"@powerhousedao/pieces-framework/block-type\";\nimport { childLogger } from \"document-model\";\nimport { randomUUID } from \"node:crypto\";\nimport { lstat, mkdir, realpath, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n bundleResolver,\n pieceModuleRef,\n type PieceResolver,\n} from \"../activepieces/resolver.js\";\nimport type { ActionContextIdentity } from \"../activepieces/context/action.js\";\nimport { hostCallTimeoutForStep } from \"../activepieces/context/limits.js\";\nimport {\n rewriteFileRefs,\n type StagedFile,\n} from \"../activepieces/context/files.js\";\nimport {\n FileTooLargeError,\n maxFileBytes,\n} from \"../activepieces/context/limits.js\";\nimport { AttachmentCache } from \"./attachment-cache.js\";\nimport { PieceWorker, type IPieceWorker } from \"../activepieces/worker/host.js\";\nimport type { ReactorTap } from \"../activepieces/worker/reactor-rpc.js\";\nimport { DEFAULT_EGRESS_POLICY } from \"../activepieces/worker/egress.js\";\nimport {\n LOG_WRITE,\n OUTPUT_UPDATE,\n STORE_DELETE,\n STORE_GET,\n STORE_PUT,\n type EgressPolicy,\n type HostCallHandlers,\n type HostNotifyHandlers,\n type PieceLogEntry,\n type StagedInput,\n} from \"../activepieces/worker/protocol.js\";\nimport type { StoreScopeName } from \"../activepieces/context/store-scope.js\";\nimport {\n collectSecretValues,\n redactError,\n redactMessage,\n rememberSecrets,\n} from \"../activepieces/worker/redact.js\";\nimport type {\n ConnectionRequest,\n EngineConnectionResolver,\n ResolvedConnection,\n} from \"./connections.js\";\nimport type { BlockExecution, BlockExecutor, BlockResult } from \"./types.js\";\nimport type { WorkflowTelemetry } from \"../../telemetry.js\";\nimport { builtinPiece, isBuiltinPiece, runBuiltinAction } from \"../builtin.js\";\nimport {\n blockLabel,\n missingError,\n UnknownBlockError,\n unpinnedNote,\n withResolution,\n type BlockResolution,\n type PieceOrigin,\n} from \"./resolution.js\";\n\nexport { UnknownBlockError };\n\nexport class TriggerBlockAsStepError extends Error {\n constructor(block: BlockRef) {\n super(\n `${blockLabel(block)} is a trigger and cannot run as a workflow step`,\n );\n this.name = \"TriggerBlockAsStepError\";\n }\n}\n\n// The host's attachment store, as the engine needs it: materialize a\n// reference to a path the worker can read, and ingest a path the worker wrote.\n// Both directions go through the filesystem, so bytes never enter IPC.\nexport interface AttachmentPort {\n read(\n ref: string,\n destPath: string,\n signal?: AbortSignal,\n ): Promise<{ fileName?: string; contentType?: string }>;\n // Whether the running workflow may read the ref, without fetching it: a\n // cached copy is only handed over after the same check a download makes.\n authorize?(ref: string): Promise<void>;\n write(\n file: {\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n },\n signal?: AbortSignal,\n ): Promise<string>;\n}\n\nconst ATTACHMENT_REF = /^attachment:\\/\\//i;\n\n// Collects every attachment reference appearing as a string in a step config.\n// Deliberately type-agnostic: the worker decides which of them to hydrate\n// (only FILE props go through toApFile), so staging a reference no one reads\n// costs one file, while missing one would fail the step.\nfunction collectRefs(value: unknown, found: Set<string>): void {\n if (typeof value === \"string\") {\n if (ATTACHMENT_REF.test(value)) found.add(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectRefs(entry, found);\n return;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const entry of Object.values(value)) collectRefs(entry, found);\n }\n}\n\n// The durable `ctx.store`, as the engine needs it: one call per operation, so\n// a piece that checkpoints mid-loop keeps what it wrote if the step then dies.\n\n// Which scope a step's keys belong to is the host's business; the executor is\n// shared across runs and must not decide it.\nexport interface PieceStorePort {\n get(key: string, scope: StoreScopeName): Promise<unknown>;\n put(key: string, value: unknown, scope: StoreScopeName): Promise<void>;\n delete(key: string, scope: StoreScopeName): Promise<void>;\n}\n\n// One key operation as it arrives from the worker.\ninterface StoreCallPayload {\n key?: unknown;\n value?: unknown;\n scope?: unknown;\n}\n\n// An unrecognised scope is treated as FLOW, the narrower partition: a bad\n// name must never widen what a step can reach.\nfunction storeScopeOf(payload: unknown): StoreScopeName {\n const scope = (payload as StoreCallPayload | undefined)?.scope;\n return scope === \"PROJECT\" ? \"PROJECT\" : \"FLOW\";\n}\n\nfunction storeKeyOf(payload: unknown): string {\n const key = (payload as StoreCallPayload | undefined)?.key;\n if (typeof key !== \"string\" || key === \"\") {\n throw new Error(\"Store call carried no key\");\n }\n return key;\n}\n\n// The handlers served to a running step or trigger hook. A rejection becomes\n// the error the piece sees, which is what an over-limit write should do.\nexport function storeHandlers(port: PieceStorePort): HostCallHandlers {\n return {\n [STORE_GET]: (payload) =>\n port.get(storeKeyOf(payload), storeScopeOf(payload)),\n [STORE_PUT]: async (payload) => {\n await port.put(\n storeKeyOf(payload),\n (payload as StoreCallPayload).value,\n storeScopeOf(payload),\n );\n return null;\n },\n [STORE_DELETE]: async (payload) => {\n await port.delete(storeKeyOf(payload), storeScopeOf(payload));\n return null;\n },\n };\n}\n\nconst logger = childLogger([\"workflow\", \"piece-staging\"]);\n\nexport interface ActivepiecesBlockExecutorOptions {\n cacheDir: string;\n // Which piece version, from which source, runs a block. Without one a\n // block runs its pin, fetched from any download source.\n resolveBlock?: (block: BlockRef) => Promise<BlockResolution>;\n connections?: EngineConnectionResolver;\n // The worker piece steps go to. A function is asked once per step, so a\n // host handing each run its own child answers with that run's.\n worker?: IPieceWorker | (() => IPieceWorker | undefined);\n defaultTimeoutMs?: number;\n // Both are needed for ctx.files to work: a directory the host and the forked\n // worker share, and somewhere to put what the piece wrote. Without them a\n // piece calling ctx.files falls back to inline data URIs.\n stagingRoot?: string;\n attachments?: AttachmentPort;\n // Keeps downloaded attachments by content so later steps and runs skip the\n // download. Needs `attachments.authorize`.\n attachmentCache?: AttachmentCache;\n // Without it `ctx.store` falls back to the worker's heap, which a step\n // timeout discards.\n pieceStore?: PieceStorePort;\n // Where a block's piece comes from. Defaults to fetching the pinned\n // version into `cacheDir`, which is what a published piece needs.\n resolver?: PieceResolver;\n // ctx.reactor over the reactor RPC, for an action that declares requireReactor;\n // undefined when it declares none. Asked per step.\n reactorAccess?: (\n request: StepReactorRequest,\n ) => Promise<ReactorTap | undefined>;\n // Where a step's piece may connect to. Left unset it is the default policy,\n // which refuses private address space; `null` runs the piece unrestricted.\n egress?: EgressPolicy | null;\n // Taps on a running step. Each is opt-in because it costs the worker an IPC\n // message per event, and neither is asked for unless someone reads it.\n onPieceLog?: (entry: PieceLogEntry, execution: BlockExecution) => void;\n onPartialOutput?: (output: unknown, execution: BlockExecution) => void;\n // The run, workflow and project a step belongs to, asked per step: the\n // executor is shared across runs. The step name is the step's key.\n identity?: () => Omit<ActionContextIdentity, \"stepName\"> | undefined;\n // Whether this step runs as a single-step test, asked per step likewise.\n stepTest?: () => boolean;\n telemetry?: WorkflowTelemetry;\n}\n\nexport interface StepReactorRequest {\n block: ParsedBlockType;\n reactorConnectionId?: string | null;\n}\n\n// The notify handlers served to one step. Unlike a store call, nothing here\n// answers the piece: these are reports, and the step never waits on them.\nfunction stepTaps(\n options: ActivepiecesBlockExecutorOptions,\n execution: BlockExecution,\n values: string[],\n): HostNotifyHandlers | undefined {\n const { onPieceLog, onPartialOutput } = options;\n if (!onPieceLog && !onPartialOutput) return undefined;\n const handlers: HostNotifyHandlers = {};\n if (onPieceLog) {\n // A piece logging its own outgoing request is a common idiom, so this is\n // one of the likeliest places for a credential to reach the host log.\n handlers[LOG_WRITE] = (payload) => {\n const entry = payload as PieceLogEntry;\n // Returned, not discarded: a sink that rejects is the host's to catch.\n return onPieceLog(\n { ...entry, message: redactMessage(entry.message, { values }) },\n execution,\n );\n };\n }\n if (onPartialOutput) {\n handlers[OUTPUT_UPDATE] = (payload) => onPartialOutput(payload, execution);\n }\n return handlers;\n}\n\n// Mutated in place rather than rewrapped: callers classify on the error's\n// class, and a new one would lose that.\n\n// `stack` embeds the message as it was at construction, so a caller logging\n// the error object rather than `.message` would otherwise still print it.\nfunction redactThrown(error: unknown, values: string[]): unknown {\n if (error instanceof Error) {\n error.message = redactMessage(error.message, { values });\n if (error.stack) error.stack = redactMessage(error.stack, { values });\n return rememberSecrets(error, values);\n }\n return rememberSecrets(redactError(error, { values }), values);\n}\n\n// Shipped by the workflow package, which versions it with the host.\nconst HOST_SHIPPED_PIECE = \"@powerhousedao/piece-reactor\";\n\n// The host's own code, so it always runs the installed copy.\nexport function isHostBound(packageName: string): boolean {\n return packageName === HOST_SHIPPED_PIECE || isBuiltinPiece(packageName);\n}\n\nexport type { BlockKind };\n\n// A block's piece with the version and source it runs at.\nexport interface ParsedBlockType {\n packageName: string;\n version: string;\n source?: PieceOrigin;\n kind: BlockKind;\n // Action or trigger name within the piece.\n name: string;\n}\n\n// The piece a resolution runs; undefined for a missing one.\nexport function resolvedBlock(\n resolution: BlockResolution,\n): ParsedBlockType | undefined {\n const { requested, resolved } = resolution;\n if (!resolved || resolution.match === \"missing\") return undefined;\n return {\n packageName: requested.pieceName,\n version: resolved.version,\n ...(resolved.source ? { source: resolved.source } : {}),\n kind: requested.kind,\n name: requested.name,\n };\n}\n\n// Without a host policy a block runs exactly what it pins.\nexport function pinnedResolution(block: BlockRef): BlockResolution {\n if (!isExactVersion(block.pieceVersion)) {\n return { requested: block, match: \"missing\", note: unpinnedNote(block) };\n }\n return {\n requested: block,\n resolved: { version: block.pieceVersion },\n match: \"exact\",\n };\n}\n\n// Executes piece actions: a built-in piece in process, any other through the\n// piece worker.\nexport class ActivepiecesBlockExecutor implements BlockExecutor {\n // Only set when nothing was supplied: the fallback this executor owns and\n // must dispose. A supplied worker belongs to whoever supplied it.\n private own: PieceWorker | undefined;\n\n private readonly resolver: PieceResolver;\n\n constructor(private readonly options: ActivepiecesBlockExecutorOptions) {\n this.resolver =\n options.resolver ?? bundleResolver({ cacheDir: options.cacheDir });\n }\n\n private worker(): IPieceWorker {\n const supplied = this.options.worker;\n if (typeof supplied === \"function\") {\n const worker = supplied();\n if (worker) return worker;\n } else if (supplied) {\n return supplied;\n }\n return (this.own ??= new PieceWorker({\n telemetry: this.options.telemetry,\n }));\n }\n\n async execute(execution: BlockExecution): Promise<BlockResult> {\n const resolution = this.options.resolveBlock\n ? await this.options.resolveBlock(execution.block)\n : pinnedResolution(execution.block);\n const parsed = resolvedBlock(resolution);\n if (!parsed) throw missingError(resolution);\n if (parsed.kind !== \"action\") {\n throw new TriggerBlockAsStepError(execution.block);\n }\n try {\n const builtin = builtinPiece(parsed.packageName);\n const result = builtin\n ? await runBuiltinAction(\n builtin,\n parsed.name,\n execution.config as Record<string, unknown>,\n )\n : await this.run(execution, parsed);\n return { ...result, resolution };\n } catch (error) {\n throw withResolution(error, resolution);\n }\n }\n\n private async run(\n execution: BlockExecution,\n parsed: ParsedBlockType,\n ): Promise<BlockResult> {\n // One staging directory per execution, removed in the finally below. A\n // host crash can still leave one behind, which is why it lives under a\n // root the host can sweep at startup.\n const stagingDir = this.options.stagingRoot\n ? path.join(this.options.stagingRoot, randomUUID())\n : undefined;\n\n // Bundle fetch and connection resolution belong inside the catch: a secret\n // provider or a resolver can fail with the credential in its own message.\n const runSecrets = execution.redactValues ?? [];\n let redactValues: string[] = [...runSecrets];\n try {\n const ref = {\n name: parsed.packageName,\n version: parsed.version,\n ...(parsed.source ? { source: parsed.source } : {}),\n };\n const telemetry = this.options.telemetry;\n const piece = await (telemetry\n ? telemetry.phase(\"piece.resolve\", {}, () => this.resolver.resolve(ref))\n : this.resolver.resolve(ref));\n const connection = await this.resolveConnection(execution.connectionId, {\n piecePackage: parsed.packageName,\n stepId: execution.step.id,\n stepKey: execution.step.key,\n });\n const auth = connection?.auth;\n redactValues = [...runSecrets, ...(connection?.secretValues ?? [])];\n\n const timeoutMs = execution.step.timeoutSeconds\n ? execution.step.timeoutSeconds * 1000\n : this.options.defaultTimeoutMs;\n // Staging and ingest count against the step's timeout, not only the\n // piece's own run.\n const deadline = timeoutMs ? Date.now() + timeoutMs : undefined;\n const signal = deadline ? AbortSignal.timeout(timeoutMs!) : undefined;\n const stagedInputs = await this.stageInputs(\n execution.config,\n stagingDir,\n signal,\n );\n const remainingMs = deadline\n ? Math.max(1, deadline - Date.now())\n : undefined;\n const pieceStore = this.options.pieceStore;\n const notifications = stepTaps(this.options, execution, redactValues);\n const egress =\n this.options.egress === undefined\n ? DEFAULT_EGRESS_POLICY\n : this.options.egress;\n const reactorTap = await this.options.reactorAccess?.({\n block: parsed,\n reactorConnectionId: execution.reactorConnectionId,\n });\n const result = await this.worker().runAction(\n {\n ...pieceModuleRef(piece),\n actionName: parsed.name,\n propsValue: execution.config as Record<string, unknown>,\n auth,\n identity: {\n ...this.options.identity?.(),\n stepName: execution.step.key,\n },\n ...(redactValues.length > 0 ? { redactValues } : {}),\n ...(this.options.stepTest?.() ? { stepTest: true } : {}),\n ...(stagingDir ? { stagingDir } : {}),\n ...(stagedInputs ? { stagedInputs } : {}),\n ...(pieceStore ? { durableStore: true } : {}),\n ...(this.options.onPieceLog ? { captureLogs: true } : {}),\n ...(this.options.onPartialOutput ? { liveOutput: true } : {}),\n ...(egress ? { egress } : {}),\n },\n {\n ...(remainingMs ? { timeoutMs: remainingMs } : {}),\n // Never shorter than the step's own timeout: a step given two\n // minutes must not have its host calls cut off after ten seconds.\n hostCallTimeoutMs: hostCallTimeoutForStep(timeoutMs),\n ...(pieceStore ? { hostCalls: storeHandlers(pieceStore) } : {}),\n ...(notifications ? { notifications } : {}),\n ...(reactorTap ? { reactor: reactorTap } : {}),\n },\n );\n return {\n output: await this.ingestFiles(\n result.output,\n result.files,\n stagingDir,\n signal,\n ),\n redactValues,\n };\n } catch (error) {\n // The child already stripped what it threw; this covers what the host\n // itself raises (bundle fetch, connection resolution, file ingest).\n throw redactThrown(error, redactValues);\n } finally {\n if (stagingDir) await rm(stagingDir, { recursive: true, force: true });\n }\n }\n\n private async resolveConnection(\n connectionId: string | null | undefined,\n request: ConnectionRequest,\n ): Promise<ResolvedConnection | undefined> {\n const connections = this.options.connections;\n if (!connectionId || !connections) return undefined;\n // The request travels with both, so taking the secret-bearing path never\n // means skipping the check on who is asking.\n if (connections.resolveWithSecrets) {\n return connections.resolveWithSecrets(connectionId, request);\n }\n const auth = await connections.resolve(connectionId, request);\n return { auth, secretValues: [...collectSecretValues(auth)] };\n }\n\n private async stageInputs(\n config: unknown,\n stagingDir: string | undefined,\n signal: AbortSignal | undefined,\n ): Promise<StagedInput[] | undefined> {\n const port = this.options.attachments;\n if (!stagingDir || !port) return undefined;\n const refs = new Set<string>();\n collectRefs(config, refs);\n if (refs.size === 0) return undefined;\n await mkdir(stagingDir, { recursive: true });\n const staged: StagedInput[] = [];\n let index = 0;\n for (const ref of refs) {\n const destPath = path.join(stagingDir, `in-${index++}`);\n try {\n const meta = await this.readAttachment(port, ref, destPath, signal);\n staged.push({ ref, path: destPath, ...meta });\n } catch (error) {\n if (signal?.aborted) throw error;\n staged.push({\n ref,\n path: \"\",\n error: error instanceof Error ? error.message : String(error),\n });\n // Staging is opportunistic: refs are collected from the whole config\n // without knowing which props are FILE, because the prop schema lives\n // in the worker. So a ref this step was never going to open must not\n // fail it -- a dispatch carrying one as data is the ordinary case. A\n // FILE prop that did need it still fails, in the worker, naming the\n // reference it could not resolve.\n logger.debug(\n \"Left @ref unstaged: @error\",\n ref,\n error instanceof Error ? error.message : String(error),\n );\n }\n }\n return staged;\n }\n\n // The cache answers only after the port's own read check.\n private async readAttachment(\n port: AttachmentPort,\n ref: string,\n destPath: string,\n signal: AbortSignal | undefined,\n ): Promise<{ fileName?: string; contentType?: string }> {\n const cache = this.options.attachmentCache;\n if (!cache || !port.authorize || !AttachmentCache.cacheable(ref)) {\n return port.read(ref, destPath, signal);\n }\n await port.authorize(ref);\n const hit = await cache.get(ref, destPath).catch(() => undefined);\n if (hit) {\n return {\n ...(hit.fileName !== undefined ? { fileName: hit.fileName } : {}),\n ...(hit.contentType !== undefined\n ? { contentType: hit.contentType }\n : {}),\n };\n }\n const meta = await port.read(ref, destPath, signal);\n await cache.put(ref, destPath, meta).catch((error: unknown) => {\n logger.debug(\n \"Could not cache @ref: @error\",\n ref,\n error instanceof Error ? error.message : String(error),\n );\n });\n return meta;\n }\n\n // A file the worker reports must be one it wrote into this step's staging\n // directory: the host reads the path, and piece code runs in the worker.\n private async checkStagedFile(\n file: StagedFile,\n stagingDir: string | undefined,\n ): Promise<number> {\n if (!stagingDir) {\n throw new Error(\n `Refusing to ingest \"${file.fileName}\": no staging directory`,\n );\n }\n const root = await realpath(stagingDir);\n const resolved = path.resolve(file.path);\n const info = await lstat(resolved).catch(() => undefined);\n // A hard link (nlink > 1) could point at any file the host user owns.\n if (\n !info?.isFile() ||\n info.nlink !== 1 ||\n path.dirname(await realpath(resolved)) !== root ||\n path.dirname(resolved) !== path.resolve(stagingDir)\n ) {\n throw new Error(\n `Refusing to ingest \"${file.fileName}\": it is not a file the step wrote`,\n );\n }\n const limit = maxFileBytes();\n if (info.size > limit) throw new FileTooLargeError(info.size, limit);\n return info.size;\n }\n\n // A provisional apfile:// token only becomes a real reference once the step\n // has returned, so a piece that writes a file and then reads it back by URL\n // within the same run would not work. No action needs that today; the fix is\n // a bidirectional worker channel, which is its own design.\n private async ingestFiles(\n output: unknown,\n files: StagedFile[] | undefined,\n stagingDir: string | undefined,\n signal: AbortSignal | undefined,\n ): Promise<unknown> {\n if (!files || files.length === 0) return output;\n const port = this.options.attachments;\n if (!port) {\n throw new Error(\n `The action wrote ${files.length} file(s) through ctx.files, but no attachment store is configured for this reactor`,\n );\n }\n const refs = new Map<string, string>();\n for (const file of files) {\n const size = await this.checkStagedFile(file, stagingDir);\n refs.set(\n file.token,\n await port.write(\n {\n path: path.resolve(file.path),\n fileName: file.fileName,\n size,\n contentType: file.contentType,\n },\n signal,\n ),\n );\n }\n return rewriteFileRefs(output, refs);\n }\n\n dispose(): void {\n this.own?.dispose();\n this.own = undefined;\n }\n}\n\n// Routes explicit handlers first, then the piece executor. Handlers, keyed\n// by blockKey, let a host serve blocks of its own in its process.\nexport class CompositeBlockExecutor implements BlockExecutor {\n constructor(\n private readonly pieces: BlockExecutor,\n private readonly handlers: Record<string, BlockExecutor> = {},\n ) {}\n\n execute(execution: BlockExecution): Promise<BlockResult> {\n const handler = this.handlers[blockKey(execution.block)] as\n | BlockExecutor\n | undefined;\n if (handler) return handler.execute(execution);\n return this.pieces.execute(execution);\n }\n}\n","// Per-step retry, as the coordinator runs it.\n//\n// The workflow document has carried a step `retry` block and a workflow\n// `defaultRetry` since its first version and nothing read either one, so an\n// author who set `maxAttempts: 3` got exactly one attempt and no warning\n// (W3.3, backlog item 4). This is the policy, resolved; `coordinator.ts`\n// applies it.\n//\n// It lives in the piece layer rather than beside the rest of the policy\n// because the coordinator is here and nothing under `src/pieces` may import\n// `src/reactor`.\n\nexport type BackoffKind = \"FIXED\" | \"EXPONENTIAL\";\n\n/** A retry policy with every field resolved; `maxAttempts` is already clamped. */\nexport interface EffectiveRetryPolicy {\n maxAttempts: number;\n backoff: BackoffKind;\n initialDelaySeconds: number;\n maxDelaySeconds: number;\n /** Empty means every error is retryable; see {@link isRetryableError}. */\n retryOn: readonly string[];\n}\n\n/**\n * A step's attempt ceiling.\n *\n * Clamped rather than trusted: `maxAttempts` is author input with no bound in\n * the schema, and each attempt re-runs a side effect and holds the run's\n * worker slot. Ten is well past any useful retry and far short of a workflow\n * that cannot be stopped.\n */\nexport const MAX_STEP_ATTEMPTS = 10;\n\n/** The ceiling on one backoff wait, whatever `maxDelaySeconds` says: the wait\n * holds the run's worker slot, and the run deadline bounds the rest. */\nexport const MAX_RETRY_DELAY_MS = 5 * 60_000;\n\nfunction positive(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0\n ? value\n : null;\n}\n\n/** Resolves an author-written retry block; null when it asks for one attempt,\n * which is the same thing as no retry policy and saves every reader a branch. */\nexport function effectiveRetryPolicy(\n retry: unknown,\n): EffectiveRetryPolicy | null {\n if (typeof retry !== \"object\" || retry === null) return null;\n const record = retry as Record<string, unknown>;\n const asked = positive(record.maxAttempts) ?? 1;\n const maxAttempts = Math.min(Math.trunc(asked), MAX_STEP_ATTEMPTS);\n if (maxAttempts <= 1) return null;\n const initial = positive(record.initialDelaySeconds) ?? 0;\n const max = positive(record.maxDelaySeconds) ?? initial;\n return {\n maxAttempts,\n backoff: record.backoff === \"EXPONENTIAL\" ? \"EXPONENTIAL\" : \"FIXED\",\n initialDelaySeconds: initial,\n maxDelaySeconds: Math.max(initial, max),\n retryOn: Array.isArray(record.retryOn)\n ? record.retryOn.filter(\n (entry): entry is string => typeof entry === \"string\",\n )\n : [],\n };\n}\n\n/** How long to wait before `attempt` (1-based: attempt 2 is the first retry).\n * EXPONENTIAL doubles from the initial delay, capped both by the author's\n * `maxDelaySeconds` and by {@link MAX_RETRY_DELAY_MS}. */\nexport function retryDelayMs(\n retry: EffectiveRetryPolicy,\n attempt: number,\n): number {\n const initial = retry.initialDelaySeconds * 1000;\n const raw =\n retry.backoff === \"EXPONENTIAL\"\n ? initial * 2 ** Math.max(0, attempt - 2)\n : initial;\n return Math.max(\n 0,\n Math.min(raw, retry.maxDelaySeconds * 1000, MAX_RETRY_DELAY_MS),\n );\n}\n\n/**\n * Whether `retryOn` admits this error.\n *\n * The schema calls its entries \"error classes\", which in a workflow is a loose\n * notion: a piece throws whatever it likes, and what reaches here may be an\n * `Error` subclass of the engine's, an HTTP failure formatted by the piece\n * framework, or a string. So an entry matches the error's CLASS NAME exactly,\n * or appears anywhere in its message — case-insensitively in both cases. That\n * makes `[\"HostCallTimeoutError\"]` and `[\"429\"]` both work, which is what an\n * author writing one of these actually means.\n *\n * An EMPTY list admits everything. The schema's own reading (\"everything else\n * fails terminally on attempt 1\") would make the shipped default — an empty\n * `retryOn` — turn every `maxAttempts` into a lie, so empty is read as\n * \"unrestricted\" and a non-empty list as the filter it is.\n */\nexport function isRetryableError(\n retry: EffectiveRetryPolicy,\n error: unknown,\n): boolean {\n if (retry.retryOn.length === 0) return true;\n const name = (error instanceof Error ? error.name : \"\").toLowerCase();\n const message = (\n error instanceof Error ? error.message : String(error)\n ).toLowerCase();\n return retry.retryOn.some((entry) => {\n const needle = entry.trim().toLowerCase();\n if (needle === \"\") return false;\n return needle === name || message.includes(needle);\n });\n}\n","// A DYNAMIC prop's children are resolved at design time and stored beside the\n// step as `propertySettings[].schema`; the run checks the value against them.\nimport type { PropertySettingDef } from \"./types.js\";\n\n// Non-retryable: the config has to change before the step can succeed.\nexport class DynamicPropertiesError extends Error {\n constructor(\n message: string,\n readonly prop: string,\n readonly missing: string[],\n ) {\n super(message);\n this.name = \"DynamicPropertiesError\";\n }\n}\n\ninterface ChildProp {\n name: string;\n label: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n// Accepts the piece's own props map or the editor's descriptor list.\nfunction requiredChildren(schema: unknown): ChildProp[] {\n const entries: [string, unknown][] = Array.isArray(schema)\n ? schema\n .filter(isRecord)\n .filter((entry) => typeof entry.name === \"string\")\n .map((entry) => [entry.name as string, entry])\n : isRecord(schema)\n ? Object.entries(schema)\n : [];\n return entries\n .filter(([, prop]) => isRecord(prop) && prop.required === true)\n .map(([name, prop]) => {\n const displayName = (prop as Record<string, unknown>).displayName;\n return {\n name,\n label:\n typeof displayName === \"string\" && displayName !== \"\"\n ? `${displayName} (${name})`\n : name,\n };\n });\n}\n\nfunction isBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n\n/** Throws a DynamicPropertiesError naming the first prop whose value does not\n * satisfy its resolved children. Settings without a schema are ignored. */\nexport function checkDynamicProperties(\n config: unknown,\n settings: readonly PropertySettingDef[] | null | undefined,\n): void {\n if (!settings || settings.length === 0) return;\n const values = isRecord(config) ? config : {};\n for (const setting of settings) {\n if (setting.schema === undefined || setting.schema === null) continue;\n const raw = values[setting.prop];\n if (!isBlank(raw) && !isRecord(raw)) {\n throw new DynamicPropertiesError(\n `Property \"${setting.prop}\" must be an object of fields, received ${Array.isArray(raw) ? \"array\" : typeof raw}`,\n setting.prop,\n [],\n );\n }\n const value = isRecord(raw) ? raw : {};\n const missing = requiredChildren(setting.schema).filter((child) =>\n isBlank(value[child.name]),\n );\n if (missing.length > 0) {\n throw new DynamicPropertiesError(\n `Property \"${setting.prop}\" is missing required fields: ${missing.map((child) => child.label).join(\", \")}`,\n setting.prop,\n missing.map((child) => child.name),\n );\n }\n }\n}\n","import { createHash } from \"node:crypto\";\nimport type { WorkflowStepDef } from \"./types.js\";\n\n// JSON with object keys sorted at every depth, so key order never changes a hash.\nexport function canonicalJson(value: unknown): string {\n return JSON.stringify(sortKeys(value) ?? null);\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (value === null || typeof value !== \"object\") return value;\n const record = value as Record<string, unknown>;\n return Object.fromEntries(\n Object.keys(record)\n .sort()\n .filter((key) => record[key] !== undefined)\n .map((key) => [key, sortKeys(record[key])]),\n );\n}\n\nexport function hashOf(...parts: string[]): string {\n const hash = createHash(\"sha256\");\n for (const part of parts) hash.update(part).update(\"\\u0000\");\n return hash.digest(\"hex\").slice(0, 16);\n}\n\n// What a step runs from: its block, config, connection and dynamic-prop\n// schemas. Field modes are editor-only.\nexport function stepConfigHash(step: WorkflowStepDef): string {\n const schemas = (step.propertySettings ?? [])\n .filter(\n (setting) => setting.schema !== null && setting.schema !== undefined,\n )\n .map((setting) => ({ prop: setting.prop, schema: setting.schema }));\n return hashOf(\n step.pieceName,\n step.pieceVersion,\n step.actionName,\n canonicalJson({\n config: step.config ?? {},\n connectionId: step.connectionId ?? null,\n propertySettings: schemas,\n // Only when set, so a step without one keeps its hash.\n ...(step.reactorConnectionId\n ? { reactorConnectionId: step.reactorConnectionId }\n : {}),\n }),\n );\n}\n","import {\n containsRedactedMarker,\n redact,\n redactMessage,\n secretsFor,\n} from \"../activepieces/worker/redact.js\";\nimport { PieceWorkerError } from \"../activepieces/worker/host.js\";\nimport {\n evaluateCondition,\n unavailableValue,\n UnavailableValueError,\n type ExpressionScope,\n} from \"./expressions.js\";\nimport {\n effectiveRetryPolicy,\n isRetryableError,\n retryDelayMs,\n type EffectiveRetryPolicy,\n} from \"./retry.js\";\nimport { resolveStepInput } from \"./step-input.js\";\nimport { checkDynamicProperties } from \"./dynamic-props.js\";\nimport { isIndeterminateError } from \"../activepieces/indeterminate.js\";\nimport {\n referenceDocuments,\n undeclaredPortEdges,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport { stepConfigHash } from \"./canonical.js\";\nimport type { BlockRef } from \"@powerhousedao/pieces-framework/block-type\";\nimport { blockLabel, pieceRecord, resolutionOf } from \"./resolution.js\";\nimport {\n stepBlock,\n triggerBlock,\n type BlockExecutor,\n type StepExecutionRecord,\n type WorkflowDefinition,\n type WorkflowRunResult,\n type WorkflowStepDef,\n} from \"./types.js\";\n\n/** One step a prior run already completed, as a rerun replays it. */\nexport interface ReplayedStep {\n output?: unknown;\n port?: string | null;\n /**\n * The step SUCCEEDED, but the run journal truncated its output past the\n * payload cap, so there is nothing to replay.\n *\n * It still replays, rather than running again: the step had side effects and\n * re-running it would charge the card twice (backlog item 15). Its scope\n * entry carries an unavailable value instead of data, so a downstream step\n * that reads `steps.<key>.output…` fails the rerun by name.\n */\n outputTruncated?: boolean;\n /**\n * What the journal holds in place of that output — the truncation marker\n * itself — to be journaled again on this run's REPLAYED row.\n *\n * Opaque to the engine: it is never resolved, only written back. Without it\n * the REPLAYED row's output is NULL, and the NEXT rerun reads a NULL as an\n * ordinary replay with no output: the truncation fact is gone after one\n * generation, and a downstream step is handed nothing instead of being told\n * by name why there is nothing.\n */\n truncatedOutput?: unknown;\n}\n\nexport interface RunWorkflowOptions {\n definition: WorkflowDefinition;\n executor: BlockExecutor;\n // Exposed to expressions as {{trigger.payload...}}.\n triggerPayload?: unknown;\n // Journaled outputs from a prior run, keyed by step id; matching steps\n // replay (output injected, port re-taken) instead of executing.\n completedSteps?: Map<string, ReplayedStep>;\n // The workflow policy's `defaultRetry`, for steps with no `retry` of their\n // own. Absent enforces no retry, which is what a definition with no policy\n // (every legacy document) means.\n defaultRetry?: EffectiveRetryPolicy | null;\n // Epoch ms the run must be over by (`policy.runTimeoutSeconds`). Checked\n // before each step and while a retry waits; past it the run is CANCELLED.\n deadline?: number;\n // Test seam for the retry waits, so a suite does not sleep through them.\n sleep?: (ms: number) => Promise<void>;\n // Called as each step reaches a terminal state, so a run that dies\n // mid-flight leaves the steps it finished behind. Ordinal is execution\n // order; skips are excluded, being knowable only once the run completes.\n onStep?: (\n record: StepExecutionRecord,\n ordinal: number,\n ) => void | Promise<void>;\n // Resolved secret variables: kept out of every journaled record and error.\n redactValues?: string[];\n // Scope entries of steps outside the definition; a single-step test reads\n // its upstream steps' test outputs from here.\n priorSteps?: ExpressionScope[\"steps\"];\n // A block's declared output ports; an edge on any other is a warning.\n declaredPorts?: (block: BlockRef) => readonly string[] | undefined;\n}\n\n// Edges no run can take, because their source never emits that port.\nexport function deadPortWarnings(\n definition: WorkflowDefinition,\n declaredPorts: (block: BlockRef) => readonly string[] | undefined,\n): string[] {\n const blocks = new Map<string, { key: string; block: BlockRef }>(\n definition.steps.map((step) => [\n step.id,\n { key: step.key, block: stepBlock(step) },\n ]),\n );\n if (definition.trigger) {\n blocks.set(definition.trigger.id, {\n key: \"trigger\",\n block: triggerBlock(definition.trigger),\n });\n }\n return undeclaredPortEdges(definition.edges, (id) => {\n const source = blocks.get(id);\n return source ? declaredPorts(source.block) : undefined;\n }).map((edge) => {\n const source = blocks.get(edge.from)!;\n const target = blocks.get(edge.to)?.key ?? edge.to;\n return `Edge from \"${source.key}\" to \"${target}\" leaves on port \"${edge.port}\", which ${blockLabel(source.block)} never takes`;\n });\n}\n\nfunction withPiece(\n piece: StepExecutionRecord[\"piece\"],\n): Pick<StepExecutionRecord, \"piece\"> {\n return piece ? { piece } : {};\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\n// A piece's own error crosses the worker inside a PieceWorkerError.\nexport function errorNameOf(error: unknown): string | undefined {\n if (error instanceof PieceWorkerError) return error.serialized.name;\n return error instanceof Error ? error.name : undefined;\n}\n\n// A record is journal material, read back by the editor and kept in the\n// database, so it never carries the live value a downstream step reads.\nfunction journaled(value: unknown, values: string[] | undefined): unknown {\n return value === undefined ? undefined : redact(value, { values });\n}\n\n/** What a run that passed `policy.runTimeoutSeconds` ends CANCELLED with. */\n/** The error name a run its deadline cancelled is journaled with; it is what\n * marks the run as resumable, unlike a firing that was refused. */\nexport const RUN_DEADLINE_ERROR_NAME = \"RunDeadlineExceeded\";\n\nexport const RUN_DEADLINE_REASON =\n \"Run exceeded its runTimeoutSeconds and was cancelled\";\n\n// Sequential v1 of the RunCoordinator (doc 08 §7.3): walks the steps+edges\n// graph, resolving each step's config against prior outputs before executing.\nexport async function runWorkflow(\n options: RunWorkflowOptions,\n): Promise<WorkflowRunResult> {\n const { definition, executor } = options;\n const runSecrets = options.redactValues ?? [];\n const scope: ExpressionScope = {\n trigger: { payload: options.triggerPayload },\n steps: { ...options.priorSteps },\n variables: Object.fromEntries(\n (definition.variables ?? []).map((v) => [v.key, v.value ?? null]),\n ),\n };\n\n const records = new Map<string, StepExecutionRecord>();\n // edgeId -> taken; an edge is decided once its source ran or was skipped.\n const edgeDecisions = new Map<string, boolean>();\n let runFailed: string | undefined;\n // Set instead of runFailed when the run ran out of time: the workflow did\n // not fail, it was stopped, and the status says so.\n let runCancelled: string | undefined;\n let runFailedName: string | undefined;\n let executedCount = 0;\n const sleep =\n options.sleep ??\n ((ms: number) =>\n new Promise<void>((resolve) => {\n // A pending retry wait must not be what keeps the process alive.\n setTimeout(resolve, ms).unref();\n }));\n\n // Null while there is time left; the reason once there is not.\n const outOfTime = (): string | undefined => {\n if (options.deadline === undefined) return undefined;\n if (Date.now() < options.deadline) return undefined;\n return RUN_DEADLINE_REASON;\n };\n\n // A failing journal write must not cost us the step's completed work: the\n // run carries on, and finishRun's final sweep repairs the missing row.\n const journal = async (record: StepExecutionRecord) => {\n if (!options.onStep) return;\n const ordinal = executedCount++;\n try {\n await options.onStep(record, ordinal);\n } catch {\n // Durability is the bonus here; run correctness is not at stake.\n }\n };\n\n const decideOutgoing = (sourceId: string, port: string | undefined) => {\n for (const edge of definition.edges) {\n if (edge.from !== sourceId) continue;\n const portMatches = port !== undefined && edge.port === port;\n let taken = portMatches;\n if (taken && edge.condition) {\n try {\n taken = evaluateCondition(edge.condition, scope);\n } catch (error) {\n taken = false;\n runFailed ??= `Condition of edge \"${edge.id}\": ${errorMessage(error)}`;\n }\n }\n edgeDecisions.set(edge.id, taken);\n }\n };\n\n // Trigger edges fire on the trigger's implicit \"next\" port.\n if (definition.trigger) {\n decideOutgoing(definition.trigger.id, \"next\");\n }\n\n const inboundEdges = (step: WorkflowStepDef) =>\n definition.edges.filter((edge) => edge.to === step.id);\n\n const isEntryStep = (step: WorkflowStepDef) =>\n !definition.trigger && inboundEdges(step).length === 0;\n\n const skipStep = (step: WorkflowStepDef) => {\n records.set(step.id, {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"SKIPPED\",\n });\n decideOutgoing(step.id, undefined);\n };\n\n // The journal keeps a redacted copy, so a replay would hand the marker to\n // the next step. Refusing is loud; replaying it would be silently wrong.\n const refuseReplay = (step: WorkflowStepDef) => {\n const error =\n `Journaled output of step \"${step.key}\" was redacted and cannot be ` +\n \"replayed; fire the workflow again instead of rerunning it\";\n records.set(step.id, {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"FAILED\",\n error,\n });\n runFailed = error;\n };\n\n // An author-skipped step continues on \"next\" as if it output nothing.\n const passStep = async (step: WorkflowStepDef) => {\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"SKIPPED\",\n output: null,\n port: \"next\",\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output: null };\n decideOutgoing(step.id, \"next\");\n };\n\n const executeStep = async (step: WorkflowStepDef) => {\n if (step.skip === true) {\n await passStep(step);\n return;\n }\n const replay = options.completedSteps?.get(step.id);\n if (replay) {\n if (containsRedactedMarker(replay.output)) {\n refuseReplay(step);\n return;\n }\n const port = replay.port ?? \"next\";\n // Truncated: the step is completed, its output is not available. Both\n // halves have to be true at once, or the rerun either re-runs a side\n // effect or hands a marker on as data.\n const output = replay.outputTruncated\n ? unavailableValue(\n `Output of step \"${step.key}\" is unavailable: it succeeded in the ` +\n \"run being rerun, but the run journal truncated its output past \" +\n \"the payload cap. The step is not re-run, because it had side \" +\n \"effects. Fire the workflow again instead of rerunning it.\",\n )\n : replay.output;\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"REPLAYED\",\n // Not the wrapper: that is a run-scope device and carries its reason on\n // a symbol. The marker goes on `journaledOutput` instead, which is what\n // carries the truncation fact into the NEXT rerun — a NULL output\n // column reads as an ordinary replay with nothing to replay, and the\n // fact would be gone after one generation.\n output: replay.outputTruncated ? undefined : replay.output,\n ...(replay.outputTruncated && replay.truncatedOutput !== undefined\n ? { journaledOutput: replay.truncatedOutput }\n : {}),\n port,\n configHash: stepConfigHash(step),\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output };\n decideOutgoing(step.id, port);\n return;\n }\n\n // One resolved policy per step: its own `retry`, else the workflow's. A\n // step that DECLARES a block overrides, whatever the block resolves to —\n // `{maxAttempts: 1}` is an author saying \"not this one\", and inheriting\n // the workflow default over it would be the opposite of an override.\n const retry =\n step.retry === undefined || step.retry === null\n ? (options.defaultRetry ?? null)\n : effectiveRetryPolicy(step.retry);\n const maxAttempts = retry?.maxAttempts ?? 1;\n const startedAt = new Date().toISOString();\n let input: unknown;\n\n // Resolution is OUTSIDE the retry loop on purpose. It reads the scope and\n // nothing else, and no attempt of this step changes the scope, so every\n // attempt would resolve the very same value — while a resolution error is\n // deterministic by construction: a reference to a key that does not exist\n // names nothing on attempt five either. Inside the loop it burned the\n // whole retry budget, backoff waits and all, on an error that could not\n // come right, and held the run's worker slot while it did.\n try {\n input = resolveStepInput(step, scope);\n checkDynamicProperties(input, step.propertySettings);\n } catch (error) {\n await endStep(step, { error, input, startedAt, attempt: 1 });\n return;\n }\n\n for (let attempt = 1; ; attempt++) {\n const attempts = attempt > 1 ? { attempts: attempt } : {};\n try {\n const result = await executor.execute({\n block: stepBlock(step),\n config: input,\n connectionId: step.connectionId,\n reactorConnectionId: step.reactorConnectionId,\n step,\n ...(runSecrets.length > 0 ? { redactValues: runSecrets } : {}),\n });\n const port = result.port ?? \"next\";\n const values = [...runSecrets, ...(result.redactValues ?? [])];\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"SUCCEEDED\",\n input: journaled(input, values),\n // Documents go into the record as references; the scope keeps them whole.\n output: journaled(referenceDocuments(result.output), values),\n port,\n startedAt,\n endedAt: new Date().toISOString(),\n ...withPiece(pieceRecord(result.resolution)),\n configHash: stepConfigHash(step),\n ...attempts,\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output: result.output };\n decideOutgoing(step.id, port);\n return;\n } catch (error) {\n // A host call that timed out may have committed the write it asked\n // for, so neither the step's failure nor its success is knowable. It\n // is not retried either: a retry would be a second write.\n const indeterminate = isIndeterminateError(error);\n const retryable =\n retry !== null &&\n attempt < maxAttempts &&\n !indeterminate &&\n // A value that is gone stays gone, and an expression that names\n // nothing names nothing on the next attempt either.\n !(error instanceof UnavailableValueError) &&\n isRetryableError(retry, error);\n if (retryable) {\n const stopped = await waitForRetry(retryDelayMs(retry, attempt + 1));\n // The deadline fell during the wait (or was already past): the run\n // is over, so NO further attempt runs. The attempt that failed is\n // journaled as the record of work done, without taking an error\n // port — nothing downstream may run after the run has ended — and\n // the run reads CANCELLED, since the clock stopped it rather than\n // the workflow failing.\n if (stopped !== undefined) {\n await endStep(step, {\n error,\n input,\n startedAt,\n attempt,\n cancelled: stopped,\n });\n return;\n }\n continue;\n }\n await endStep(step, { error, input, startedAt, attempt });\n return;\n }\n }\n };\n\n /**\n * A retry wait, clipped to the run's deadline.\n *\n * Undefined when there is room for both the wait and another attempt.\n * Otherwise the reason the run is over: the wait is served out only as far\n * as the deadline, never past it, and the caller runs no further attempt.\n * Sleeping the full backoff and leaving the deadline to \"the next attempt's\n * own check\" meant that attempt ran its side effect after the run had\n * expired, and the run then ended FAILED rather than CANCELLED.\n */\n async function waitForRetry(waitMs: number): Promise<string | undefined> {\n const expired = outOfTime();\n if (expired !== undefined) return expired;\n if (options.deadline === undefined) {\n if (waitMs > 0) await sleep(waitMs);\n return undefined;\n }\n const remaining = options.deadline - Date.now();\n if (waitMs >= remaining) {\n if (remaining > 0) await sleep(remaining);\n return RUN_DEADLINE_REASON;\n }\n if (waitMs > 0) await sleep(waitMs);\n // The wait fitted, but a slow timer can still land on the deadline.\n return outOfTime();\n }\n\n /**\n * The terminal end of a step that threw: its record, its error port, and\n * what that means for the run.\n *\n * One place for it, because three paths reach it — a deterministic\n * resolution failure before the first attempt, an exhausted or refused\n * retry, and a retry the run's deadline cut short.\n */\n async function endStep(\n step: WorkflowStepDef,\n outcome: {\n error: unknown;\n input: unknown;\n startedAt: string;\n attempt: number;\n // Set when the clock is why there is no further attempt; the run is\n // CANCELLED rather than FAILED, and no error port is taken.\n cancelled?: string;\n },\n ): Promise<void> {\n const { error, input, startedAt, attempt } = outcome;\n // A failed step is exactly where an input gets inspected, so it is\n // redacted with the same secrets the successful path uses.\n const values = [...runSecrets, ...secretsFor(error)];\n const detail = redactMessage(errorMessage(error), { values });\n const indeterminate = isIndeterminateError(error);\n const errorName = errorNameOf(error);\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: indeterminate ? \"INDETERMINATE\" : \"FAILED\",\n input: journaled(input, values),\n error: detail,\n ...(errorName ? { errorName } : {}),\n startedAt,\n endedAt: new Date().toISOString(),\n ...withPiece(pieceRecord(resolutionOf(error))),\n configHash: stepConfigHash(step),\n ...(attempt > 1 ? { attempts: attempt } : {}),\n };\n records.set(step.id, record);\n await journal(record);\n if (indeterminate) {\n // No port, so nothing downstream runs and no error branch claims to\n // have handled something that may have succeeded.\n runFailed = `Step \"${step.key}\" is INDETERMINATE: ${detail}`;\n runFailedName = errorName;\n return;\n }\n if (outcome.cancelled !== undefined) {\n runCancelled = outcome.cancelled;\n return;\n }\n // The same redacted text the journal took: an error-port branch writing\n // the reason somewhere a person will read must not widen what a failure\n // discloses.\n scope.steps[step.key] = { error: detail };\n decideOutgoing(step.id, \"error\");\n const errorHandled = definition.edges.some(\n (edge) => edge.from === step.id && edgeDecisions.get(edge.id),\n );\n if (!errorHandled) {\n const failedAfter = attempt > 1 ? ` after ${attempt} attempts` : \"\";\n runFailed = `Step \"${step.key}\" failed${failedAfter}: ${detail}`;\n runFailedName = errorName;\n }\n }\n\n // Before a step that will execute, never during it: a step is the unit of\n // work and killing one mid-flight would leave a side effect with no record.\n // Not before a step that would only be skipped, so the outcome does not\n // depend on graph shape. `??=`, not `=`: a retry wait that ran out the\n // clock has already set this, and a timer that fired a hair early must not\n // clear it.\n const expiredBeforeStep = (): boolean => {\n runCancelled ??= outOfTime();\n return runCancelled !== undefined;\n };\n\n let progressed = true;\n while (progressed && !runFailed && !runCancelled) {\n progressed = false;\n for (const step of definition.steps) {\n if (records.has(step.id)) continue;\n const inbound = inboundEdges(step);\n if (isEntryStep(step)) {\n if (expiredBeforeStep()) break;\n await executeStep(step);\n progressed = true;\n // Independent roots are otherwise free to run their side effects\n // before the outer loop notices the run is already over.\n if (runFailed || runCancelled) break;\n continue;\n }\n if (inbound.length === 0) continue;\n const decided = inbound.every((edge) => edgeDecisions.has(edge.id));\n if (!decided) continue;\n const reachable = inbound.some((edge) => edgeDecisions.get(edge.id));\n if (reachable) {\n if (expiredBeforeStep()) break;\n await executeStep(step);\n } else {\n skipStep(step);\n }\n progressed = true;\n if (runFailed || runCancelled) break;\n }\n }\n\n // Steps never reached (dangling, cyclic, or after a terminal failure).\n for (const step of definition.steps) {\n if (!records.has(step.id)) skipStep(step);\n }\n\n // A FAILED record with a taken error edge is a handled failure; only\n // unhandled ones set runFailed above.\n const steps = definition.steps.map((step) => records.get(step.id)!);\n const warnings = options.declaredPorts\n ? deadPortWarnings(definition, options.declaredPorts)\n : [];\n const noted = warnings.length > 0 ? { warnings } : {};\n if (runFailed) {\n return {\n status: \"FAILED\",\n steps,\n error: runFailed,\n ...(runFailedName ? { errorName: runFailedName } : {}),\n ...noted,\n };\n }\n // The deadline is the last word: a run whose final step happened to finish\n // in time still reads CANCELLED if the loop stopped for the clock, and the\n // steps it did complete are journaled either way.\n if (runCancelled) {\n return {\n status: \"CANCELLED\",\n steps,\n error: runCancelled,\n errorName: RUN_DEADLINE_ERROR_NAME,\n ...noted,\n };\n }\n return { status: \"SUCCEEDED\", steps, ...noted };\n}\n","// The pieces this reactor holds locally, by piece name.\n\n// A holder, not a finder: resolving a package is the host's package manager's\n// job, and this runtime must not depend on reactor-api to have it done.\nimport { childLogger } from \"document-model\";\nimport {\n builtinLocalPieces,\n isBuiltinPiece,\n type LocalPiece,\n} from \"../pieces/index.js\";\n\nconst logger = childLogger([\"workflow\", \"piece-registry\"]);\n\nfunction pieceLocation(piece: LocalPiece): string {\n return piece.entryPath ?? piece.bundleDir ?? piece.entryUrl ?? \"?\";\n}\n\nexport class PieceRegistry {\n private byName = new Map<string, LocalPiece>();\n\n // Replaces the whole set: what the host reports is everything it holds, so\n // a piece missing from it is a piece the reactor no longer has.\n setPieces(pieces: readonly LocalPiece[]): void {\n const found = new Map<string, LocalPiece>();\n for (const piece of pieces) {\n // The first claim keeps the name; the host hands pieces in package-name order.\n const held = found.get(piece.name);\n if (!held) {\n found.set(piece.name, piece);\n continue;\n }\n logger.warn(\n \"Piece @name is shipped twice; keeping @kept, ignoring @ignored\",\n piece.name,\n `${held.version} (${pieceLocation(held)})`,\n `${piece.version} (${pieceLocation(piece)})`,\n );\n }\n this.byName = found;\n const names = [...found.keys()].join(\", \");\n // \"Holding\" meant one thing when every piece was code on this disk. A\n // package loaded from a registry contributes the declaration, not the code.\n const held = [...found.values()].filter(\n (piece) => piece.entryPath ?? piece.bundleDir,\n ).length;\n const served = found.size - held;\n // Names go through the logger's values: it substitutes `@`-prefixed\n // tokens, and a scoped package name printed inline comes out as null/pack.\n if (found.size > 0) {\n const what =\n served === 0\n ? `${held} package piece(s) on disk`\n : held === 0\n ? `${served} package piece(s), fetched when first run`\n : `${held} on disk and ${served} fetched when first run`;\n logger.info(`Holding ${what}: @names`, names);\n } else {\n logger.debug(\"Holding no package pieces\");\n }\n }\n\n lookup = (name: string): LocalPiece | undefined => this.byName.get(name);\n\n entries(): LocalPiece[] {\n return [...this.byName.values()];\n }\n\n // Name -> installed version.\n versions(): Record<string, string> {\n return Object.fromEntries(\n [...this.byName.values()].map((piece) => [piece.name, piece.version]),\n );\n }\n\n /** Test seam: a suite that filled the registry starts the next from nothing. */\n reset(): void {\n this.byName = new Map();\n }\n}\n\n// One registry for the runtime, the way the bundle cache is one directory.\nexport const packagePieces = new PieceRegistry();\n\n// What the runtime can run as installed: its built-in pieces, which always\n// answer for their names, then the host's.\nexport function installedPiece(name: string): LocalPiece | undefined {\n return (\n builtinLocalPieces().find((piece) => piece.name === name) ??\n packagePieces.lookup(name)\n );\n}\n\nexport function installedPieces(): LocalPiece[] {\n return [\n ...builtinLocalPieces(),\n ...packagePieces.entries().filter((piece) => !isBuiltinPiece(piece.name)),\n ];\n}\n","// Spans and metrics for runs, steps, workers and the reactor a step reaches.\n// The host passes its tracer and meter; absent, the global API's (no-op until registered).\nimport {\n context as otelContext,\n metrics,\n SpanStatusCode,\n trace,\n type Attributes,\n type BatchObservableCallback,\n type Context,\n type Counter,\n type Histogram,\n type Meter,\n type ObservableGauge,\n type Span,\n type Tracer,\n} from \"@opentelemetry/api\";\nimport type {\n WorkerPhaseTiming,\n WorkerTimings,\n} from \"./pieces/activepieces/worker/protocol.js\";\nimport {\n resolutionOf,\n type BlockResolution,\n} from \"./pieces/engine/resolution.js\";\nimport type { BlockExecutor } from \"./pieces/engine/types.js\";\n\nexport const TELEMETRY_SCOPE = \"@powerhousedao/reactor-workflow\";\n\nexport interface WorkflowTelemetryOptions {\n tracer?: Tracer;\n meter?: Meter;\n}\n\nexport interface WorkerPoolStats {\n size: number;\n active: number;\n idle: number;\n waiting: number;\n}\n\nexport class WorkflowTelemetry {\n readonly tracer: Tracer;\n private readonly meter: Meter;\n private readonly runs: Counter;\n private readonly runDuration: Histogram;\n private readonly stepDuration: Histogram;\n private readonly phaseDuration: Histogram;\n private dispatcherGauges?: Record<\n \"inFlight\" | \"waiting\" | \"loop\",\n ObservableGauge\n >;\n private poolGauges?: Record<\n \"size\" | \"active\" | \"idle\" | \"waiting\",\n ObservableGauge\n >;\n\n constructor(options: WorkflowTelemetryOptions = {}) {\n this.tracer = options.tracer ?? trace.getTracer(TELEMETRY_SCOPE);\n this.meter = options.meter ?? metrics.getMeter(TELEMETRY_SCOPE);\n this.runs = this.meter.createCounter(\"workflow.runs\", {\n description: \"Runs finished, by status and trigger kind\",\n unit: \"{run}\",\n });\n this.runDuration = this.meter.createHistogram(\"workflow.run.duration\", {\n description: \"Run duration from fire to the journal closing it\",\n unit: \"ms\",\n });\n this.stepDuration = this.meter.createHistogram(\"workflow.step.duration\", {\n description: \"Step duration, by piece and status\",\n unit: \"ms\",\n });\n this.phaseDuration = this.meter.createHistogram(\"workflow.phase.duration\", {\n description:\n \"Duration of one part of a run: load, journal writes, worker, reactor calls\",\n unit: \"ms\",\n });\n }\n\n // `name` is also the `phase` attribute on workflow.phase.duration.\n phase<T>(\n name: string,\n attributes: Attributes,\n fn: (span: Span) => Promise<T>,\n parent?: Context,\n ): Promise<T> {\n const started = performance.now();\n return this.span(`workflow.${name}`, attributes, fn, parent).finally(() =>\n this.recordPhase(name, performance.now() - started),\n );\n }\n\n // The child's own marks, as spans under its request. `forkedAt` starts the\n // boot span when this response is the child's first.\n workerTimings(\n request: Span,\n timings: WorkerTimings,\n forkedAt: number,\n ipc: { sent: number; received: number },\n ): void {\n const under = (span: Span) => trace.setSpan(otelContext.active(), span);\n const child = (\n name: string,\n start: number,\n end: number,\n parent: Span = request,\n attributes?: Attributes,\n ): Span => {\n const span = this.tracer.startSpan(\n `workflow.worker.${name}`,\n { startTime: start, ...(attributes ? { attributes } : {}) },\n under(parent),\n );\n span.end(end);\n this.recordPhase(`worker.${name}`, end - start);\n return span;\n };\n const ready = finite(timings.ready);\n if (ready !== undefined && forkedAt > 0) {\n child(\"boot\", forkedAt, Math.max(forkedAt, ready));\n }\n const received = finite(timings.received);\n const sent = finite(timings.sent);\n // A request queued behind boot only starts travelling once the child is up.\n const delivered = Math.max(ipc.sent, ready ?? 0);\n if (received !== undefined) {\n child(\"ipc.in\", delivered, Math.max(delivered, received));\n }\n // Parents first, so a nested phase finds the span it ran inside.\n const byName = new Map<string, Span>();\n const phases = Array.isArray(timings.phases) ? timings.phases : [];\n for (const phase of phases\n .filter(knownPhase)\n .sort((a, b) => a.start - b.start)) {\n const parent = phase.parent ? byName.get(phase.parent) : undefined;\n byName.set(\n phase.name,\n child(\n phase.name,\n phase.start,\n phase.end,\n parent,\n phaseAttributes(phase.attributes),\n ),\n );\n }\n if (sent !== undefined) {\n child(\"ipc.out\", sent, Math.max(sent, ipc.received));\n }\n request.setAttributes(workerMemory(timings.memory));\n }\n\n recordPhase(name: string, ms: number): void {\n this.phaseDuration.record(ms, { phase: name });\n }\n\n span<T>(\n name: string,\n attributes: Attributes,\n fn: (span: Span) => Promise<T>,\n parent: Context = otelContext.active(),\n ): Promise<T> {\n return this.tracer.startActiveSpan(\n name,\n { attributes },\n parent,\n async (span) => {\n try {\n return await fn(span);\n } catch (error) {\n failSpan(span, error);\n throw error;\n } finally {\n span.end();\n }\n },\n );\n }\n\n recordRun(ms: number, status: string, triggerKind: string): void {\n const attributes = {\n \"run.status\": status,\n \"trigger.kind\": metricTriggerKind(triggerKind),\n };\n this.runs.add(1, attributes);\n this.runDuration.record(ms, attributes);\n }\n\n recordStep(ms: number, pieceName: string, status: string): void {\n this.stepDuration.record(ms, {\n \"piece.name\": pieceName,\n \"step.status\": status,\n });\n }\n\n // Gauges read on each collection. Returns the unobserve a disposed pool calls,\n // so a replaced runtime's pool stops reporting and can be collected.\n observeWorkerPool(stats: () => WorkerPoolStats): () => void {\n this.poolGauges ??= this.createPoolGauges();\n const { size, active, idle, waiting } = this.poolGauges;\n const observables = [size, active, idle, waiting];\n const callback: BatchObservableCallback = (result) => {\n const current = stats();\n result.observe(size, current.size);\n result.observe(active, current.active);\n result.observe(idle, current.idle);\n result.observe(waiting, current.waiting);\n };\n this.meter.addBatchObservableCallback(callback, observables);\n return () =>\n this.meter.removeBatchObservableCallback(callback, observables);\n }\n\n // Runs admitted and waiting across workflows, and the loop that admits them.\n observeDispatcher(\n stats: () => { inFlight: number; waiting: number; utilization: number },\n ): () => void {\n // Created once: a replaced runtime re-observes the same instruments.\n this.dispatcherGauges ??= {\n inFlight: this.meter.createObservableGauge(\"workflow.runs.in_flight\", {\n description: \"Runs admitted and not yet finished\",\n unit: \"{run}\",\n }),\n waiting: this.meter.createObservableGauge(\"workflow.runs.waiting\", {\n description: \"Runs waiting for admission across workflows\",\n unit: \"{run}\",\n }),\n loop: this.meter.createObservableGauge(\n \"workflow.host.event_loop.utilization\",\n {\n description: \"Main thread busy share over the last second\",\n unit: \"1\",\n },\n ),\n };\n const { inFlight, waiting, loop } = this.dispatcherGauges;\n const observables = [inFlight, waiting, loop];\n const callback: BatchObservableCallback = (result) => {\n const current = stats();\n result.observe(inFlight, current.inFlight);\n result.observe(waiting, current.waiting);\n result.observe(loop, current.utilization);\n };\n this.meter.addBatchObservableCallback(callback, observables);\n return () =>\n this.meter.removeBatchObservableCallback(callback, observables);\n }\n\n private createPoolGauges() {\n const gauge = (name: string, description: string) =>\n this.meter.createObservableGauge(name, { description, unit: \"{worker}\" });\n return {\n size: gauge(\"workflow.worker.pool.size\", \"Most run children\"),\n active: gauge(\n \"workflow.worker.pool.active\",\n \"Children serving a request\",\n ),\n idle: gauge(\"workflow.worker.pool.idle\", \"Warm children waiting\"),\n waiting: gauge(\n \"workflow.worker.pool.waiting\",\n \"Requests waiting for a child\",\n ),\n };\n }\n}\n\n// The child is piece code: only the phases it is built to report, well-formed,\n// become spans and metric labels.\nconst WORKER_PHASES = new Set([\n \"piece.load\",\n \"reactor.open\",\n \"models\",\n \"action\",\n]);\nconst WORKER_ATTRIBUTES: Record<string, \"boolean\" | \"string\"> = {\n \"piece.cached\": \"boolean\",\n \"document.type\": \"string\",\n};\nconst MAX_ATTRIBUTE_LENGTH = 256;\n\nfunction finite(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value)\n ? value\n : undefined;\n}\n\nfunction knownPhase(phase: unknown): phase is WorkerPhaseTiming {\n if (typeof phase !== \"object\" || phase === null) return false;\n const { name, start, end, parent } = phase as Partial<WorkerPhaseTiming>;\n return (\n typeof name === \"string\" &&\n WORKER_PHASES.has(name) &&\n (parent === undefined || WORKER_PHASES.has(parent)) &&\n finite(start) !== undefined &&\n finite(end) !== undefined &&\n end! >= start!\n );\n}\n\nfunction phaseAttributes(attributes: unknown): Attributes | undefined {\n if (typeof attributes !== \"object\" || attributes === null) return undefined;\n const kept: Attributes = {};\n for (const [key, type] of Object.entries(WORKER_ATTRIBUTES)) {\n const value = (attributes as Record<string, unknown>)[key];\n if (typeof value !== type) continue;\n kept[key] =\n typeof value === \"string\"\n ? value.slice(0, MAX_ATTRIBUTE_LENGTH)\n : (value as boolean);\n }\n return Object.keys(kept).length > 0 ? kept : undefined;\n}\n\nconst MB = 2 ** 20;\n\n// The child's memory as it answered, in MB, on the request span.\nfunction workerMemory(memory: unknown): Attributes {\n if (typeof memory !== \"object\" || memory === null) return {};\n const attributes: Attributes = {};\n for (const [key, name] of [\n [\"rss\", \"worker.memory.rss_mb\"],\n [\"heapUsed\", \"worker.memory.heap_used_mb\"],\n [\"heapTotal\", \"worker.memory.heap_total_mb\"],\n [\"external\", \"worker.memory.external_mb\"],\n ] as const) {\n const bytes = finite((memory as Record<string, unknown>)[key]);\n if (bytes !== undefined) attributes[name] = bytes / MB;\n }\n return attributes;\n}\n\n// Piece trigger kinds embed author-typed names; metrics keep only \"piece\".\nfunction metricTriggerKind(triggerKind: string): string {\n return triggerKind.startsWith(\"piece:\") ? \"piece\" : triggerKind;\n}\n\n// A step's piece as a metric attribute: the name only once it resolved to a\n// real piece, since a workflow author can type any string into the document.\nfunction metricPieceName(\n step: { pieceName: string },\n resolution: BlockResolution | undefined,\n): string {\n return resolution?.resolved && resolution.match !== \"missing\"\n ? step.pieceName\n : \"unresolved\";\n}\n\n// One `workflow.step` span per executed block, and its duration by piece.\nexport function tracedSteps(\n executor: BlockExecutor,\n telemetry: WorkflowTelemetry,\n): BlockExecutor {\n return {\n execute(execution) {\n const { step } = execution;\n const started = performance.now();\n let status = \"FAILED\";\n let resolution: BlockResolution | undefined;\n return telemetry\n .span(\n \"workflow.step\",\n {\n \"step.id\": step.id,\n \"step.key\": step.key,\n \"piece.name\": step.pieceName,\n \"action.name\": step.actionName,\n },\n async (span) => {\n try {\n const result = await executor.execute(execution);\n resolution = result.resolution;\n status = \"SUCCEEDED\";\n const version = resolution?.resolved?.version;\n if (version) span.setAttribute(\"piece.version\", version);\n return result;\n } catch (error) {\n resolution = resolutionOf(error);\n throw error;\n }\n },\n )\n .finally(() => {\n telemetry.recordStep(\n performance.now() - started,\n metricPieceName(step, resolution),\n status,\n );\n });\n },\n };\n}\n\nexport function failSpan(span: Span, error: unknown): void {\n span.recordException(error instanceof Error ? error : String(error));\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n}\n\n// Every promise-returning method of `target` runs in a span parented on `parent`.\nexport function tracedMethods<T extends object>(\n target: T,\n telemetry: WorkflowTelemetry,\n prefix: string,\n parent: Context,\n): T {\n return new Proxy(target, {\n get(object, property, receiver) {\n const value = Reflect.get(object, property, receiver) as unknown;\n if (typeof value !== \"function\" || typeof property !== \"string\") {\n return value;\n }\n const phase = `${prefix}.${property}`;\n return (...args: unknown[]) =>\n telemetry.tracer.startActiveSpan(\n `workflow.${phase}`,\n {},\n parent,\n (span) => {\n const started = performance.now();\n const end = (error?: unknown) => {\n if (error !== undefined) failSpan(span, error);\n span.end();\n telemetry.recordPhase(phase, performance.now() - started);\n };\n let result: unknown;\n try {\n result = (value as (...a: unknown[]) => unknown).apply(\n object,\n args,\n );\n } catch (error) {\n end(error);\n throw error;\n }\n // A synchronous method answers synchronously.\n if (!(result instanceof Promise)) {\n end();\n return result;\n }\n return result.then(\n (resolved: unknown) => {\n end();\n return resolved;\n },\n (error: unknown) => {\n end(error);\n throw error;\n },\n );\n },\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2KA,SAAgB,WAAW,OAA0C;CAGnE,QADE,OAAO,MAAM,YAAY,aAAa,MAAM,QAAQ,IAAI,MAAM,YAC9C,CAAC;AACrB;AAGA,SAAgB,YAAY,OAA2C;CAGrE,QADE,OAAO,MAAM,aAAa,aAAa,MAAM,SAAS,IAAI,MAAM,aAC/C,CAAC;AACtB;;;;ACrKA,MAAa,qBAAqB;AAalC,MAAM,sCAA2C,IAAI,IAAI,CACvD,sBACF,CAAC;AAED,SAAS,MAAM,OAAyB;CACtC,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,OAAQ,MAA6B;CAC3C,OAAO,OAAO,SAAS,YAAY,oBAAoB,IAAI,IAAI;AACjE;AAEA,SAAS,QAAQ,OAAyB;CACxC,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,OAAQ,MAAkC,wBAAwB;AACpE;;;;;;;;;AAUA,SAAgB,qBAAqB,OAAyB;CAC5D,IAAI,QAAQ,KAAK,KAAK,MAAM,KAAK,GAAG,OAAO;CAC3C,MAAM,aACJ,OACC;CACH,IAAI,QAAQ,YAAY,UAAU,KAAK,MAAM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