@powerhousedao/reactor-workflow 6.2.3-dev.43 → 6.2.3-dev.45

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.
@@ -1 +0,0 @@
1
- {"version":3,"file":"piece-registry-gj2DNNkB.js","names":["logger","gunzip","gunzipCb","pkg.version","CORE_PIECE_NAME","logger"],"sources":["../src/pieces/activepieces/registry-source.ts","../src/pieces/activepieces/fetch.ts","../src/pieces/activepieces/resolver.ts","../src/pieces/activepieces/worker/transport.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/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/dynamic-props.ts","../src/pieces/engine/canonical.ts","../src/pieces/engine/coordinator.ts","../src/reactor/piece-registry.ts"],"sourcesContent":["// 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\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 { pieceRegistrySource } 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): { source: BundleSource; url: string }[] {\n const all = allTarballSources(name, version);\n return only ? all.filter(({ source }) => only.includes(source)) : all;\n}\n\nfunction allTarballSources(\n name: string,\n version: string,\n): { source: BundleSource; url: string }[] {\n const registry = pieceRegistrySource();\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): Promise<{ tgz: Buffer; source: BundleSource }> {\n const sources = tarballSources(name, version, only);\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 await runInstall(workspace, timeoutMs);\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// 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 );\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(): { file: string; args: string[]; shell: boolean } {\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 ],\n shell: windows,\n };\n}\n\nasync function runInstall(cwd: string, timeoutMs: number): Promise<void> {\n const { file, args, shell } = installCommand();\n await new Promise<void>((resolve, reject) => {\n execFile(\n file,\n args,\n // No network of its own to configure and no bunfig to inherit: npm reads\n // the ambient registry config, which is the host's to set.\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","// 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","// 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 { existsSync } from \"node:fs\";\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// A forked node child on this machine, over its IPC channel.\nexport function createForkTransport(entryPath: string): IPieceWorkerTransport {\n const child: ChildProcess = fork(entryPath, [], {\n // Empty env: the child gets no host secrets and no inherited TLS overrides.\n env: {},\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 child.kill(\"SIGKILL\");\n },\n };\n}\n","import { configuredMaxFileBytes } 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 {\n createForkTransport,\n defaultEntryPath,\n type IPieceWorkerTransport,\n type PieceWorkerTransportFactory,\n type TransportExit,\n} from \"./transport.js\";\nimport type {\n CheckConnectionRequest,\n DescribePieceRequest,\n HostCallHandlers,\n HostCallMessage,\n HostCallResponse,\n HostNotifyHandlers,\n HostNotifyMessage,\n ResolveOptionsRequest,\n RunActionRequest,\n SerializedPieceError,\n TriggerHookRequest,\n WorkerResponse,\n} from \"./protocol.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 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}\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}\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\ntype ChildMessage = WorkerResponse | HostCallMessage | HostNotifyMessage;\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 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}\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}\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 worker: IPieceWorkerTransport | undefined;\n private queue: Promise<unknown> = Promise.resolve();\n private nextId = 1;\n\n constructor(options: PieceWorkerOptions = {}) {\n const entryPath = options.entryPath;\n this.connect =\n options.transport ??\n (() => createForkTransport(entryPath ?? defaultEntryPath()));\n this.defaultTimeoutMs = options.defaultTimeoutMs ?? 30_000;\n this.hostCallTimeoutMs = options.hostCallTimeoutMs;\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: RequestTaps = {},\n ): Promise<PieceWorkerResult> {\n const run = this.queue.then(() =>\n this.execute(type, request, timeoutMs ?? this.defaultTimeoutMs, taps),\n );\n this.queue = run.catch(() => undefined);\n return run;\n }\n\n dispose(): void {\n this.worker?.kill();\n this.worker = undefined;\n }\n\n private spawn(): IPieceWorkerTransport {\n if (this.worker) return this.worker;\n const worker = this.connect();\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 execute(\n type: WorkerRequestType,\n request: WorkerRequest,\n timeoutMs: number,\n taps: RequestTaps,\n ): Promise<PieceWorkerResult> {\n const worker = this.spawn();\n const id = this.nextId++;\n\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 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 (response.type === \"host-call\" || response.type === \"host-notify\") {\n return;\n }\n if (response.id !== id) return;\n cleanup();\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 };\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 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 worker.send(\n jsonSafe({\n id,\n type,\n request: {\n maxFileBytes: configuredMaxFileBytes(),\n deadline,\n ...(this.hostCallTimeoutMs\n ? { hostCallTimeoutMs: this.hostCallTimeoutMs }\n : {}),\n ...request,\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 = 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","// A bounded set of piece workers, handed out one per run (doc 08 §7, doc 03 §5).\n\n// PieceWorker serializes its requests, so one shared worker makes every\n// connector step on the server wait for every other.\n\n// The pool answers both halves of that: N sessions run at once, and each holds\n// a child of its own, killed when the session closes.\n\n// So a run starts on a clean heap, waits only on itself, and takes nothing\n// with it when it ends.\nimport {\n PieceWorker,\n type IPieceWorker,\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\";\n\n// Thrown when a session asks for a slot 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} runs 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\nexport interface PieceWorkerPoolOptions extends PieceWorkerOptions {\n // How many sessions may hold a worker at once. Each one is a child process,\n // so this is the server's real connector concurrency.\n size?: number;\n // How many sessions may wait for a slot. 0 is unbounded, which is what the\n // single shared worker effectively did: latency rather than failure.\n maxQueueDepth?: number;\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\nconst DEFAULT_SIZE = 4;\n\ninterface Waiter {\n session: PieceWorkerSession;\n resolve: () => void;\n reject: (error: unknown) => void;\n}\n\n// One run's claim on a worker. Lazy on purpose: a run whose steps are all\n// document or core blocks never takes a slot and never forks a child.\nexport class PieceWorkerSession implements IPieceWorker {\n private worker: IPieceWorker | undefined;\n private taking: Promise<IPieceWorker> | undefined;\n private held = false;\n private closed = false;\n\n constructor(private readonly pool: PieceWorkerPool) {}\n\n runAction(\n request: RunActionRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.request((worker) => worker.runAction(request, options));\n }\n\n resolveOptions(\n request: ResolveOptionsRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.request((worker) => worker.resolveOptions(request, options));\n }\n\n checkConnection(\n request: CheckConnectionRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.request((worker) => worker.checkConnection(request, options));\n }\n\n describePiece(\n request: DescribePieceRequest,\n options?: { timeoutMs?: number },\n ): Promise<PieceWorkerResult> {\n return this.request((worker) => worker.describePiece(request, options));\n }\n\n runTriggerHook(\n request: TriggerHookRequest,\n options?: RequestOptions,\n ): Promise<PieceWorkerResult> {\n return this.request((worker) => worker.runTriggerHook(request, options));\n }\n\n // Kills this session's child and frees its slot for whoever is waiting.\n\n // Idempotent: a caller closing in a `finally` must not have to care whether\n // the run failed before it ever reached a piece step.\n close(): void {\n if (this.closed) return;\n this.closed = true;\n // Still queueing: the request fails now rather than when a slot happens\n // to free, which for a saturated pool may be never.\n this.pool.cancel(this);\n this.worker?.dispose();\n this.worker = undefined;\n this.pool.forget(this);\n this.giveBack();\n }\n\n // IPieceWorker's teardown is this session's close: a caller holding one\n // through the interface ends the run's child, not the pool.\n dispose(): void {\n this.close();\n }\n\n private async request<T>(fn: (worker: IPieceWorker) => Promise<T>) {\n const worker = await this.take();\n // Closed while this was waiting — a shutdown landing mid-run.\n\n // Its worker is already killed, and PieceWorker forks a replacement on the\n // next request, so dispatching now would leak a child the pool never sees.\n if (this.closed) throw new PieceWorkerSessionClosedError();\n return fn(worker);\n }\n\n private take(): Promise<IPieceWorker> {\n if (this.closed) {\n return Promise.reject(new PieceWorkerSessionClosedError());\n }\n if (this.worker) return Promise.resolve(this.worker);\n // Memoized: two steps entering at once must not take two slots, even\n // though the coordinator runs a run's steps one after another.\n this.taking ??= this.acquire();\n return this.taking;\n }\n\n private async acquire(): Promise<IPieceWorker> {\n await this.pool.acquire(this);\n this.held = true;\n // Closed while queueing: hand the slot straight back rather than fork a\n // child for a run that is already over.\n if (this.closed) {\n this.giveBack();\n throw new PieceWorkerSessionClosedError();\n }\n this.worker = this.pool.build();\n return this.worker;\n }\n\n private giveBack(): void {\n if (!this.held) return;\n this.held = false;\n this.pool.release();\n }\n}\n\n// Sized once at construction. Sessions queue for a slot in the order they ask\n// for one, so a burst of runs is served first-come rather than at random.\nexport class PieceWorkerPool {\n readonly size: number;\n private readonly maxQueueDepth: number;\n private readonly createWorker: (options: PieceWorkerOptions) => IPieceWorker;\n private readonly workerOptions: PieceWorkerOptions;\n private readonly sessions = new Set<PieceWorkerSession>();\n private readonly waiters: Waiter[] = [];\n private inUse = 0;\n private disposed = false;\n\n constructor(options: PieceWorkerPoolOptions = {}) {\n const { size, maxQueueDepth, createWorker, ...workerOptions } = options;\n this.size = Math.max(1, Math.trunc(size ?? DEFAULT_SIZE));\n this.maxQueueDepth = Math.max(0, Math.trunc(maxQueueDepth ?? 0));\n this.createWorker = createWorker ?? ((o) => new PieceWorker(o));\n this.workerOptions = workerOptions;\n }\n\n // A run's claim on a worker, for the length of the run. Free until its\n // first piece step, so opening one per run costs nothing.\n session(): PieceWorkerSession {\n if (this.disposed) throw new Error(\"Piece worker pool is disposed\");\n const session = new PieceWorkerSession(this);\n this.sessions.add(session);\n return session;\n }\n\n // Sessions holding a worker, and sessions waiting for one. The wait is what\n // a queue-depth alarm watches: it is invisible in a run's own timings.\n stats(): { size: number; active: number; waiting: number } {\n return {\n size: this.size,\n active: this.inUse,\n waiting: this.waiters.length,\n };\n }\n\n // Closes every session — killing the children mid-run — and refuses the ones\n // still queueing. For shutdown; a live run does not survive it.\n dispose(): void {\n this.disposed = true;\n // Queued sessions hear why before the closing below turns their wait into\n // the more ordinary \"your session closed\".\n for (const waiter of this.waiters.splice(0)) {\n waiter.reject(new Error(\"Piece worker pool is disposed\"));\n }\n for (const session of [...this.sessions]) session.close();\n this.sessions.clear();\n }\n\n /** @internal — a session taking its slot. */\n acquire(session: PieceWorkerSession): Promise<void> {\n if (this.disposed) {\n return Promise.reject(new Error(\"Piece worker pool is disposed\"));\n }\n if (this.inUse < this.size) {\n this.inUse++;\n return Promise.resolve();\n }\n if (this.maxQueueDepth > 0 && this.waiters.length >= this.maxQueueDepth) {\n return Promise.reject(\n new PieceWorkerPoolBusyError(this.size, this.waiters.length),\n );\n }\n return new Promise<void>((resolve, reject) => {\n this.waiters.push({ session, resolve, reject });\n });\n }\n\n /** @internal — a session that closed while queueing. */\n cancel(session: PieceWorkerSession): void {\n const index = this.waiters.findIndex((w) => w.session === session);\n if (index < 0) return;\n const [waiter] = this.waiters.splice(index, 1);\n waiter.reject(new PieceWorkerSessionClosedError());\n }\n\n /** @internal — a session giving its slot back. */\n release(): void {\n const next = this.waiters.shift();\n // Handed straight on rather than counted down and up again, so a slot\n // freed with someone waiting cannot be taken by a later arrival.\n if (next) {\n next.resolve();\n return;\n }\n this.inUse = Math.max(0, this.inUse - 1);\n }\n\n /** @internal — one child for one session. */\n build(): IPieceWorker {\n return this.createWorker(this.workerOptions);\n }\n\n /** @internal — a session that closed itself. */\n forget(session: PieceWorkerSession): void {\n this.sessions.delete(session);\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 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 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}\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 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\").\nexport type StepExecutionStatus =\n | \"SUCCEEDED\"\n | \"FAILED\"\n | \"SKIPPED\"\n | \"REPLAYED\";\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 port?: string;\n error?: 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}\n\nexport type WorkflowRunStatus = \"SUCCEEDED\" | \"FAILED\";\n\nexport interface WorkflowRunResult {\n status: WorkflowRunStatus;\n steps: StepExecutionRecord[];\n error?: 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\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 const record = current as Record<string | number, unknown>;\n if (!Object.prototype.hasOwnProperty.call(record, segment)) return MISSING;\n current = record[segment];\n }\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 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// An existence test asks whether its operand names anything, so a reference\n// that resolves to nothing is its answer rather than an error.\nexport function resolveStepInput(\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// 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","// 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 { mkdir, 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 type {\n ReactorCreateInput,\n ReactorCreateSubmission,\n ReactorExecuteInput,\n ReactorJobState,\n ReactorService,\n ReactorSubmission,\n ReactorWaitInput,\n} from \"../activepieces/context/reactor.js\";\nimport {\n rewriteFileRefs,\n type StagedFile,\n} from \"../activepieces/context/files.js\";\nimport { PieceWorker, type IPieceWorker } from \"../activepieces/worker/host.js\";\nimport { DEFAULT_EGRESS_POLICY } from \"../activepieces/worker/egress.js\";\nimport {\n LOG_WRITE,\n OUTPUT_UPDATE,\n REACTOR_FIND,\n REACTOR_GET,\n REACTOR_MODEL,\n REACTOR_MODELS,\n REACTOR_SUBMIT,\n REACTOR_SUBMIT_CREATE,\n REACTOR_WAIT,\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 { 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 ): Promise<{ fileName?: string; contentType?: string }>;\n write(file: {\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\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 host's half of `ctx.reactor`: the same operations the piece calls, run\n// against the reactor this host serves. See activepieces/context/reactor.ts.\n\n// Registered per step and only for a piece the host resolved locally, so a\n// fetched bundle forging these calls finds no handler and is refused.\nexport type ReactorPort = Omit<ReactorService, \"execute\" | \"create\"> & {\n // Enqueues the write and answers at once.\n submit(input: ReactorExecuteInput): Promise<ReactorSubmission>;\n // Enqueues the create and answers at once, with what completes it.\n submitCreate(input: ReactorCreateInput): Promise<ReactorCreateSubmission>;\n // Holds for at most `maxWaitMs`, then answers the job's state as it stands.\n wait(input: ReactorWaitInput): Promise<ReactorJobState>;\n};\n\n// Held well under the worker's host-call cap, whatever the child asks for.\nexport const MAX_REACTOR_WAIT_MS = 5_000;\n\nfunction waitMs(value: unknown): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 0;\n return Math.min(Math.max(Math.floor(value), 0), MAX_REACTOR_WAIT_MS);\n}\n\n// Payloads arrive from the child, which runs piece code: a call is checked\n// here rather than trusted to have come from our own proxy.\nfunction reactorInput(payload: unknown): Record<string, unknown> {\n if (\n typeof payload !== \"object\" ||\n payload === null ||\n Array.isArray(payload)\n ) {\n throw new Error(\"Reactor call carried no input object\");\n }\n return payload as Record<string, unknown>;\n}\n\nfunction requiredString(\n payload: Record<string, unknown>,\n field: string,\n): string {\n const value = payload[field];\n if (typeof value !== \"string\" || value === \"\") {\n throw new Error(`Reactor call carried no \"${field}\"`);\n }\n return value;\n}\n\nfunction optionalString(\n payload: Record<string, unknown>,\n field: string,\n): string | undefined {\n const value = payload[field];\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\nfunction reactorActions(payload: Record<string, unknown>) {\n const actions = payload.actions;\n if (!Array.isArray(actions) || actions.length === 0) {\n throw new Error(\"Reactor call carried no actions\");\n }\n return actions.map((entry, index) => {\n const action = entry as Record<string, unknown> | null;\n if (!action || typeof action.type !== \"string\") {\n throw new Error(`Reactor call: actions[${index}] needs a string \"type\"`);\n }\n return {\n type: action.type,\n input: action.input,\n ...(typeof action.scope === \"string\" ? { scope: action.scope } : {}),\n };\n });\n}\n\n// A page size the host will serve. The value arrives from piece code, so it\n// is clamped here rather than trusted; a host may cap it further.\nconst MAX_FIND_LIMIT = 100;\n\nfunction findLimit(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.min(Math.max(Math.floor(value), 1), MAX_FIND_LIMIT);\n}\n\n// The state match, as the host will accept it. Both halves must be strings and\n// the path must name something: a match with an empty path would silently pass\n// every document, which is the opposite of what a step asking to match wants.\nfunction findMatch(\n value: unknown,\n): { path: string; value: string } | undefined {\n if (typeof value !== \"object\" || value === null) return undefined;\n const record = value as Record<string, unknown>;\n const path = record.path;\n const wanted = record.value;\n if (typeof path !== \"string\" || path.trim() === \"\") return undefined;\n if (typeof wanted !== \"string\") return undefined;\n return { path: path.trim(), value: wanted };\n}\n\nfunction executeInput(payload: unknown): ReactorExecuteInput {\n const input = reactorInput(payload);\n return {\n documentId: requiredString(input, \"documentId\"),\n ...(optionalString(input, \"branch\")\n ? { branch: optionalString(input, \"branch\") }\n : {}),\n actions: reactorActions(input),\n };\n}\n\nexport function reactorHandlers(port: ReactorPort): HostCallHandlers {\n return {\n [REACTOR_MODELS]: () => port.models(),\n [REACTOR_MODEL]: (payload) =>\n port.model(requiredString(reactorInput(payload), \"documentType\")),\n [REACTOR_GET]: (payload) => {\n const input = reactorInput(payload);\n return port.get({\n documentId: requiredString(input, \"documentId\"),\n ...(optionalString(input, \"branch\")\n ? { branch: optionalString(input, \"branch\") }\n : {}),\n });\n },\n [REACTOR_FIND]: (payload) => {\n const input = reactorInput(payload);\n return port.find({\n ...(optionalString(input, \"documentType\")\n ? { documentType: optionalString(input, \"documentType\") }\n : {}),\n ...(optionalString(input, \"parentId\")\n ? { parentId: optionalString(input, \"parentId\") }\n : {}),\n ...(findLimit(input.limit) !== undefined\n ? { limit: findLimit(input.limit) }\n : {}),\n ...(findMatch(input.match) ? { match: findMatch(input.match) } : {}),\n ...(input.withState === true ? { withState: true } : {}),\n });\n },\n [REACTOR_SUBMIT_CREATE]: (payload) => {\n const input = reactorInput(payload);\n return port.submitCreate({\n documentType: requiredString(input, \"documentType\"),\n ...(optionalString(input, \"name\")\n ? { name: optionalString(input, \"name\") }\n : {}),\n ...(optionalString(input, \"parentId\")\n ? { parentId: optionalString(input, \"parentId\") }\n : {}),\n });\n },\n [REACTOR_SUBMIT]: (payload) => port.submit(executeInput(payload)),\n [REACTOR_WAIT]: (payload) => {\n const input = reactorInput(payload);\n return port.wait({\n jobId: requiredString(input, \"jobId\"),\n maxWaitMs: waitMs(input.maxWaitMs),\n });\n },\n };\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 // 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 // Serves `ctx.reactor`, and only to a piece the resolver answered locally.\n // Without it even a package piece finds the member throwing.\n reactor?: ReactorPort;\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}\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// The one piece served `ctx.reactor`. Its actions are the reactor surface --\n// find, get, create, dispatch, schemas -- so the port is what it is for.\n\n// Identity, not provenance: a piece is not handed the reactor for having been\n// installed locally, shipped first-party, or registered in the host's registry.\nexport const REACTOR_PORT_PIECE = \"@powerhousedao/piece-reactor\";\n\nexport function servesReactorPort(packageName: string): boolean {\n return packageName === REACTOR_PORT_PIECE;\n}\n\n// The host's own code, so it always runs the installed copy.\nexport function isHostBound(packageName: string): boolean {\n return servesReactorPort(packageName) || 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 }\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 piece = await this.resolver.resolve({\n name: parsed.packageName,\n version: parsed.version,\n ...(parsed.source ? { source: parsed.source } : {}),\n });\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 const stagedInputs = await this.stageInputs(execution.config, stagingDir);\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 // One piece reaches the reactor: the one whose whole job is reaching it.\n // Not a question of where the bundle came from -- see REACTOR_PORT_PIECE.\n const reactor = servesReactorPort(parsed.packageName)\n ? this.options.reactor\n : undefined;\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 ...(reactor ? { reactorAccess: true } : {}),\n ...(this.options.onPieceLog ? { captureLogs: true } : {}),\n ...(this.options.onPartialOutput ? { liveOutput: true } : {}),\n ...(egress ? { egress } : {}),\n },\n {\n ...(timeoutMs ? { timeoutMs } : {}),\n ...(pieceStore || reactor\n ? {\n hostCalls: {\n ...(pieceStore ? storeHandlers(pieceStore) : {}),\n ...(reactor ? reactorHandlers(reactor) : {}),\n },\n }\n : {}),\n ...(notifications ? { notifications } : {}),\n },\n );\n return {\n output: await this.ingestFiles(result.output, result.files),\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 ): 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 port.read(ref, destPath);\n staged.push({ ref, path: destPath, ...meta });\n } catch (error) {\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 // 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 ): 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 refs.set(\n file.token,\n await port.write({\n path: file.path,\n fileName: file.fileName,\n size: file.size,\n contentType: file.contentType,\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","// 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 }),\n );\n}\n","import {\n containsRedactedMarker,\n redact,\n redactMessage,\n secretsFor,\n} from \"../activepieces/worker/redact.js\";\nimport { evaluateCondition, type ExpressionScope } from \"./expressions.js\";\nimport { resolveStepInput } from \"./step-input.js\";\nimport { checkDynamicProperties } from \"./dynamic-props.js\";\nimport { undeclaredPortEdges } 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\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, { output?: unknown; port?: string | null }>;\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 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// 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 let executedCount = 0;\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 const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"REPLAYED\",\n output: replay.output,\n port,\n configHash: stepConfigHash(step),\n };\n records.set(step.id, record);\n await journal(record);\n scope.steps[step.key] = { output: replay.output };\n decideOutgoing(step.id, port);\n return;\n }\n const startedAt = new Date().toISOString();\n let input: unknown;\n try {\n input = resolveStepInput(step, scope);\n checkDynamicProperties(input, step.propertySettings);\n const result = await executor.execute({\n block: stepBlock(step),\n config: input,\n connectionId: step.connectionId,\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 output: journaled(result.output, values),\n port,\n startedAt,\n endedAt: new Date().toISOString(),\n ...withPiece(pieceRecord(result.resolution)),\n configHash: stepConfigHash(step),\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 } catch (error) {\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 record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n pieceName: step.pieceName,\n blockName: step.actionName,\n status: \"FAILED\",\n input: journaled(input, values),\n error: detail,\n startedAt,\n endedAt: new Date().toISOString(),\n ...withPiece(pieceRecord(resolutionOf(error))),\n configHash: stepConfigHash(step),\n };\n records.set(step.id, record);\n await journal(record);\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 runFailed = `Step \"${step.key}\" failed: ${detail}`;\n }\n }\n };\n\n let progressed = true;\n while (progressed && !runFailed) {\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 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) 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 await executeStep(step);\n } else {\n skipStep(step);\n }\n progressed = true;\n if (runFailed) 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 return runFailed\n ? { status: \"FAILED\", steps, error: runFailed, ...noted }\n : { 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"],"mappings":";;;;;;;;;;;;;;AAYA,MAAMA,WAAS,YAAY,CAAC,YAAY,gBAAgB,CAAC;AAazD,SAAS,OAAO,SAAsC;CACpD,OAAO;EACL;EACA,aAAa,gBACX,cACI,GAAG,QAAQ,6CACX,GAAG,QAAQ;EAGjB,WAAW,SAAS,GAAG,QAAQ,UAAU,mBAAmB,IAAI;EAChE,aAAa,MAAM,YACjB,GAAG,QAAQ,oBAAoB,KAAK,GAAG,QAAQ;CACnD;AACF;AAKA,IAAI;AAEJ,SAAgB,oBAAoB,KAA+B;CACjE,MAAM,UAAU,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE,KAAK;CACnD,IAAI,YAAY,IAAI;EAClB,aAAa,KAAA;EACb;CACF;CACA,IAAI,YAAY,YAAY,SAAS;CACrC,aAAa,OAAO,OAAO;CAC3B,SAAO,KAAK,8BAA8B,WAAW,SAAS;AAChE;AAEA,SAAgB,sBAAuD;CACrE,OAAO;AACT;;;AClDA,MAAMC,WAAS,UAAUC,MAAQ;AAIjC,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAEjC,IAAI,eAAe;AACnB,IAAI,iBAAiB;AAcrB,SAAgB,qBAA6B;CAC3C,OAAO;AACT;AAEA,SAAgB,cAAc,MAAc,SAAyB;CACnE,OAAO,GAAG,aAAa,GAAG,KAAK,QAAQ,KAAK,GAAG,EAAE,GAAG,QAAQ;AAC9D;AAEA,SAAgB,cAAc,MAAc,SAAyB;CACnE,MAAM,WAAW,KAAK,WAAW,GAAG,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK;CAC7D,OAAO,GAAG,eAAe,GAAG,KAAK,KAAK,SAAS,GAAG,QAAQ;AAC5D;AAIA,M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