@powerhousedao/reactor-workflow 6.2.3-dev.22 → 6.2.3-dev.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +106 -0
- package/dist/{descriptor-Doax7KPd.js → descriptor-E4swpRpd.js} +10 -4
- package/dist/descriptor-E4swpRpd.js.map +1 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +99 -82
- package/dist/index.js.map +1 -1
- package/dist/{piece-registry-lsGsY9fT.js → piece-registry-CYXV_aEv.js} +6 -2
- package/dist/piece-registry-CYXV_aEv.js.map +1 -0
- package/dist/{piece-registry-BH39cD-k.d.ts → piece-registry-q4bgYbXa.d.ts} +17 -2
- package/dist/piece-registry-q4bgYbXa.d.ts.map +1 -0
- package/dist/{redact-ChAU8USo.js → redact-C2y8tU--.js} +37 -2
- package/dist/redact-C2y8tU--.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +3 -3
- package/dist/worker-entry.js +114 -31
- package/dist/worker-entry.js.map +1 -1
- package/package.json +7 -7
- package/dist/descriptor-Doax7KPd.js.map +0 -1
- package/dist/piece-registry-BH39cD-k.d.ts.map +0 -1
- package/dist/piece-registry-lsGsY9fT.js.map +0 -1
- package/dist/redact-ChAU8USo.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"piece-registry-lsGsY9fT.js","names":["logger","gunzip","gunzipCb","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/secrets.ts","../src/pieces/engine/expressions.ts","../src/pieces/engine/connections.ts","../src/pieces/engine/blocks.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 — so only the base URL differs.\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, under the filename their CDN would serve it as. */\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.replace(\"/\", \"-\")}-${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 CDN_PIECES_URL = \"https://cdn.activepieces.com/pieces/bundled/\";\nconst NPM_REGISTRY_URL = \"https://registry.npmjs.org\";\n\nexport function cdnTarballUrl(name: string, version: string): string {\n return `${CDN_PIECES_URL}${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 `${NPM_REGISTRY_URL}/${name}/-/${unscoped}-${version}.tgz`;\n}\n\n// name/version come from a workflow step's blockType, an unconstrained string.\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}\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): { 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): Promise<{ tgz: Buffer; source: BundleSource }> {\n const sources = tarballSources(name, version);\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): Promise<BundleSource> {\n const { tgz, source } = await downloadTarball(name, version, timeoutMs);\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\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 = path.join(cacheDir, `${name.replace(\"/\", \"-\")}-${version}`);\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(name, version, timeoutMs, staging);\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 = `${options.cacheDir}\\u0000${options.name}@${options.version}`;\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 = path.join(\n cacheDir,\n `${name.replace(\"/\", \"-\")}-${version}.install`,\n );\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 );\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. Two sources, one seam.\n\n// A published piece is a bundle fetched from a registry and cached on disk; a\n// first-party piece ships inside an installed reactor package and is already\n// on disk, with no version to fetch and no cache to warm.\nimport { ensurePieceBundle } 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 rather than a bundle\n // fetched from a registry. Only these are offered host capabilities.\n local: boolean;\n}\n\nexport interface PieceResolver {\n // entryUrl: where a package-provided piece is served, for a package this\n // host loaded from a registry and so has no copy of on disk.\n resolve(\n name: string,\n version: string,\n entryUrl?: string,\n ): 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// The published path: fetch (or reuse) the bundle for an exact version.\nexport function bundleResolver(options: {\n cacheDir: string;\n timeoutMs?: number;\n}): PieceResolver {\n return {\n async resolve(\n name: string,\n version: string,\n entryUrl?: string,\n ): Promise<ResolvedPiece> {\n const bundle = await ensurePieceBundle({\n name,\n version,\n cacheDir: options.cacheDir,\n ...(entryUrl ? { entryUrl } : {}),\n ...(options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n });\n return { name, version, bundleDir: bundle.dir, local: false };\n },\n };\n}\n\n// An installed package wins over the registry for its own name, whatever\n// version the block type asked for: the installed copy is the one this reactor\n// runs, and a fetched bundle of the same name would shadow it silently.\nexport function localFirstResolver(\n lookup: LocalPieceLookup,\n fallback: PieceResolver,\n): PieceResolver {\n return {\n async resolve(name: string, version: string): Promise<ResolvedPiece> {\n const local = await lookup(name);\n if (!local) return fallback.resolve(name, version);\n // Declared but not on this disk: the package came from a registry, so\n // the piece is fetched from where that registry serves it.\n if (!local.entryPath && !local.bundleDir && local.entryUrl) {\n return fallback.resolve(name, local.version, local.entryUrl);\n }\n return {\n name,\n version: local.version,\n ...(local.entryPath ? { entryPath: local.entryPath } : {}),\n ...(local.bundleDir ? { bundleDir: local.bundleDir } : {}),\n local: true,\n };\n },\n };\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}\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 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 }\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 // A piece's app.checkConnection over resolved credentials; the output is a\n // 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 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: { maxFileBytes: configuredMaxFileBytes(), ...request },\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","// 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","// Minimal {{path}} expression resolution over the run scope (doc 08 §4.6).\n// A whole-string expression yields the raw value; embedded ones interpolate.\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: without it a branch\n // can route on a failure but cannot say what the failure was.\n steps: Record<string, { output?: unknown; error?: string }>;\n variables: Record<string, unknown>;\n}\n\nconst WHOLE_EXPRESSION = /^\\{\\{\\s*([^{}]+?)\\s*\\}\\}$/;\nconst EMBEDDED_EXPRESSION = /\\{\\{\\s*([^{}]+?)\\s*\\}\\}/g;\n\nexport function lookupPath(scope: ExpressionScope, path: string): unknown {\n let current: unknown = scope;\n for (const segment of path.split(\".\")) {\n if (current === null || typeof current !== \"object\") return undefined;\n current = (current as Record<string, unknown>)[segment];\n }\n return current;\n}\n\nconst STRING_LITERAL = /^(['\"])(.*)\\1$/;\n\n// \"a.b || c.d || 'default'\": first term that isn't undefined/null/\"\" wins.\nexport function resolveExpression(\n scope: ExpressionScope,\n expression: string,\n): unknown {\n for (const term of expression.split(\"||\")) {\n const trimmed = term.trim();\n if (!trimmed) continue;\n const literal = STRING_LITERAL.exec(trimmed);\n const value = literal ? literal[2] : lookupPath(scope, trimmed);\n if (value !== undefined && value !== null && value !== \"\") return value;\n }\n return undefined;\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\nexport function resolveExpressions(\n value: unknown,\n scope: ExpressionScope,\n): unknown {\n if (typeof value === \"string\") {\n const whole = WHOLE_EXPRESSION.exec(value);\n if (whole) return resolveExpression(scope, whole[1]);\n return value.replaceAll(EMBEDDED_EXPRESSION, (_, path: string) =>\n interpolate(resolveExpression(scope, path)),\n );\n }\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 = resolveExpressions(condition, scope);\n if (resolved === \"false\" || resolved === \"0\") return false;\n return Boolean(resolved);\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} from \"@powerhousedao/pieces-framework\";\n\n// The powerhouse/connection document model's own enum: the framework's\n// AppConnectionType, minus its OAuth2 variants, with NO_AUTH persisted 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 package the caller already resolved the block type to,\n// so a resolver never re-parses a block type to learn which piece is asking.\nexport interface ConnectionRequest {\n blockType: string;\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 return {\n auth: shapeAuth(source, resolved),\n secretValues: Object.values(resolved),\n };\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","import { 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 { ReactorService } 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_CREATE,\n REACTOR_EXECUTE,\n REACTOR_FIND,\n REACTOR_GET,\n REACTOR_MODEL,\n REACTOR_MODELS,\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\";\n\nexport class UnknownBlockTypeError extends Error {\n constructor(blockType: string) {\n super(`No executor registered for block type \"${blockType}\"`);\n this.name = \"UnknownBlockTypeError\";\n }\n}\n\nexport class TriggerBlockAsStepError extends Error {\n constructor(blockType: string) {\n super(`Trigger block type \"${blockType}\" cannot run as a workflow step`);\n this.name = \"TriggerBlockAsStepError\";\n }\n}\n\n// Core blocks. core#branch routes on its (already resolved) condition: equal\n// to `equals` when that is set, otherwise truthiness. core#assert fails the\n// run on blank or rejected values.\nexport class CoreBlockExecutor implements BlockExecutor {\n static handles(blockType: string): boolean {\n return blockType.startsWith(\"core#\");\n }\n\n execute(execution: BlockExecution): Promise<BlockResult> {\n if (execution.blockType === \"core#branch\") {\n const { condition, equals } = execution.config as {\n condition?: unknown;\n equals?: unknown;\n };\n // Trimmed and case-insensitive: the condition is often model output.\n const normalize = (value: unknown) =>\n (typeof value === \"string\"\n ? value\n : value === undefined || value === null\n ? \"\"\n : JSON.stringify(value)\n )\n .trim()\n .toLowerCase();\n const taken =\n typeof equals === \"string\"\n ? normalize(condition) === normalize(equals)\n : Boolean(condition) && condition !== \"false\" && condition !== \"0\";\n return Promise.resolve({\n output: { condition: condition ?? null },\n port: taken ? \"true\" : \"false\",\n });\n }\n if (execution.blockType === \"core#assert\") {\n return this.assert(execution);\n }\n return Promise.reject(new UnknownBlockTypeError(execution.blockType));\n }\n\n // core#assert fails the step when its value is blank or is one of the\n // rejected values. Model output is the motivating case: an empty\n // completion, or a classifier answering the wrong question, must not flow\n // on to a step with a side effect.\n private assert(execution: BlockExecution): Promise<BlockResult> {\n const { value, rejectValues, allowValues, allowEmpty, message } =\n execution.config as {\n value?: unknown;\n rejectValues?: unknown;\n allowValues?: unknown;\n allowEmpty?: unknown;\n message?: unknown;\n };\n const text =\n typeof value === \"string\"\n ? value\n : value === undefined || value === null\n ? \"\"\n : JSON.stringify(value);\n const trimmed = text.trim();\n const fail = (reason: string) =>\n Promise.reject(\n new Error(\n typeof message === \"string\" && message\n ? message\n : `core#assert: ${reason}`,\n ),\n );\n\n if (!trimmed && allowEmpty !== true) {\n return fail(\"value is empty\");\n }\n const normalizeList = (entries: unknown) =>\n (typeof entries === \"string\"\n ? [entries]\n : Array.isArray(entries)\n ? entries\n : []\n )\n .map((entry) => String(entry).trim().toLowerCase())\n .filter(Boolean);\n\n if (normalizeList(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 = normalizeList(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({ output: { value }, port: \"next\" });\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 = ReactorService;\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\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_CREATE]: (payload) => {\n const input = reactorInput(payload);\n return port.create({\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_EXECUTE]: (payload) => {\n const input = reactorInput(payload);\n return port.execute({\n documentId: requiredString(input, \"documentId\"),\n ...(optionalString(input, \"branch\")\n ? { branch: optionalString(input, \"branch\") }\n : {}),\n actions: reactorActions(input),\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 // Piece package name -> pinned version; the connector registry for this run.\n // A blockType may instead pin inline: \"@scope/pkg@1.2.3#action\".\n\n // A function is awaited per step, so a host whose registry loads lazily —\n // package pieces are pinned by what is installed, not by the block type —\n // answers with what it has by the time a step actually runs.\n packages?:\n | Record<string, string>\n | (() => Record<string, string> | Promise<Record<string, string>>);\n // Asked only for a block type the registry above could not resolve, so a\n // host that can still find the piece some other way answers for it here.\n\n // A map cannot: resolving an unpinned name means looking that one name up,\n // which the registry, being what this host installed, has nothing to say to.\n resolveBlockType?: (\n blockType: string,\n ) => Promise<ParsedBlockType | undefined>;\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 type'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}\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\nexport type BlockKind = \"action\" | \"trigger\";\n\nexport interface ParsedBlockType {\n packageName: string;\n version: string;\n kind: BlockKind;\n // Action or trigger name within the piece.\n name: string;\n}\n\n// Everything a block type says about itself, the version excepted: it is\n// absent when the block type pins none, and a caller resolves it from there.\nexport interface BlockTypeParts {\n packageName: string;\n version?: string;\n kind: BlockKind;\n name: string;\n}\n\nconst TRIGGER_FRAGMENT = \"trigger:\";\n\n// The block type's own halves, before any registry is consulted: a caller with\n// another source of versions still learns which piece an unresolved one names.\nexport function blockTypeParts(blockType: string): BlockTypeParts | undefined {\n const separator = blockType.lastIndexOf(\"#\");\n if (separator <= 0) return undefined;\n const packageSpec = blockType.slice(0, separator);\n const fragment = blockType.slice(separator + 1);\n const isTrigger = fragment.startsWith(TRIGGER_FRAGMENT);\n const name = isTrigger ? fragment.slice(TRIGGER_FRAGMENT.length) : fragment;\n if (!name) return undefined;\n const kind: BlockKind = isTrigger ? \"trigger\" : \"action\";\n const versionAt = packageSpec.indexOf(\"@\", 1);\n if (versionAt > 0) {\n return {\n packageName: packageSpec.slice(0, versionAt),\n version: packageSpec.slice(versionAt + 1),\n kind,\n name,\n };\n }\n return { packageName: packageSpec, kind, name };\n}\n\n// \"<pkg>[@<version>]#<action>\" or \"<pkg>[@<version>]#trigger:<trigger>\" —\n// the version after the scope-less \"@\" wins over the registry.\n\n// Undefined means \"no version anywhere\", not \"not a block type\": treating the\n// two alike is how an unversioned name the reactor holds nothing for vanishes.\nexport function parseBlockType(\n blockType: string,\n packages: Record<string, string> = {},\n): ParsedBlockType | undefined {\n const parts = blockTypeParts(blockType);\n if (!parts) return undefined;\n const { packageName, kind, name } = parts;\n if (parts.version !== undefined) {\n return { packageName, version: parts.version, kind, name };\n }\n const version = packages[packageName] as string | undefined;\n if (!version) return undefined;\n return { packageName, version, kind, name };\n}\n\n// Executes \"<packageName>#<actionName>\" block types through the 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 private packages(): Promise<Record<string, string>> {\n const supplied = this.options.packages;\n return Promise.resolve(\n typeof supplied === \"function\" ? supplied() : (supplied ?? {}),\n );\n }\n\n async execute(execution: BlockExecution): Promise<BlockResult> {\n const parsed =\n parseBlockType(execution.blockType, await this.packages()) ??\n (await this.options.resolveBlockType?.(execution.blockType));\n if (!parsed) {\n throw new UnknownBlockTypeError(execution.blockType);\n }\n if (parsed.kind !== \"action\") {\n throw new TriggerBlockAsStepError(execution.blockType);\n }\n\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 let redactValues: string[] = [];\n try {\n const piece = await this.resolver.resolve(\n parsed.packageName,\n parsed.version,\n );\n const connection = await this.resolveConnection(execution.connectionId, {\n blockType: execution.blockType,\n piecePackage: parsed.packageName,\n stepId: execution.step.id,\n stepKey: execution.step.key,\n });\n const auth = connection?.auth;\n redactValues = 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 ...(redactValues.length > 0 ? { redactValues } : {}),\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 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 core#*, then the piece executor.\n// Handlers let a host add block types of its own, served in its process.\nexport class CompositeBlockExecutor implements BlockExecutor {\n private readonly core = new CoreBlockExecutor();\n\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[execution.blockType] as\n | BlockExecutor\n | undefined;\n if (handler) return handler.execute(execution);\n if (CoreBlockExecutor.handles(execution.blockType)) {\n return this.core.execute(execution);\n }\n return this.pieces.execute(execution);\n }\n}\n","import {\n containsRedactedMarker,\n redact,\n redactMessage,\n secretsFor,\n} from \"../activepieces/worker/redact.js\";\nimport {\n evaluateCondition,\n resolveExpressions,\n type ExpressionScope,\n} from \"./expressions.js\";\nimport type {\n BlockExecutor,\n StepExecutionRecord,\n WorkflowDefinition,\n WorkflowRunResult,\n 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}\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 scope: ExpressionScope = {\n trigger: { payload: options.triggerPayload },\n steps: {},\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 const taken =\n portMatches &&\n (!edge.condition || evaluateCondition(edge.condition, scope));\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 blockType: step.blockType,\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 blockType: step.blockType,\n status: \"FAILED\",\n error,\n });\n runFailed = error;\n };\n\n const executeStep = async (step: WorkflowStepDef) => {\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 blockType: step.blockType,\n status: \"REPLAYED\",\n output: replay.output,\n port,\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 input = resolveExpressions(step.config, scope);\n try {\n const result = await executor.execute({\n blockType: step.blockType,\n config: input,\n connectionId: step.connectionId,\n step,\n });\n const port = result.port ?? \"next\";\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n blockType: step.blockType,\n status: \"SUCCEEDED\",\n input: journaled(input, result.redactValues),\n output: journaled(result.output, result.redactValues),\n port,\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 = secretsFor(error);\n const detail = redactMessage(errorMessage(error), { values });\n const record: StepExecutionRecord = {\n stepId: step.id,\n key: step.key,\n blockType: step.blockType,\n status: \"FAILED\",\n input: journaled(input, values),\n error: detail,\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 return runFailed\n ? { status: \"FAILED\", steps, error: runFailed }\n : { status: \"SUCCEEDED\", steps };\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 type { LocalPiece } from \"../pieces/index.js\";\n\nconst logger = childLogger([\"workflow\", \"piece-registry\"]);\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 to claim a name keeps it, so a project can override a piece\n // one of its dependencies ships.\n if (!found.has(piece.name)) found.set(piece.name, piece);\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, the registry parseBlockType resolves an\n // unversioned block type against.\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"],"mappings":";;;;;;;;;;;;AAYA,MAAMA,WAAS,YAAY,CAAC,YAAY,iBAAiB,CAAC;AAa1D,SAAS,OAAO,SAAsC;AACpD,QAAO;EACL;EACA,aAAa,gBACX,cACI,GAAG,QAAQ,6CACX,GAAG,QAAQ;EAGjB,WAAW,SAAS,GAAG,QAAQ,UAAU,mBAAmB,KAAK;EACjE,aAAa,MAAM,YACjB,GAAG,QAAQ,oBAAoB,KAAK,QAAQ,KAAK,IAAI,CAAC,GAAG,QAAQ;EACpE;;AAMH,IAAI;AAEJ,SAAgB,oBAAoB,KAA+B;CACjE,MAAM,UAAU,KAAK,MAAM,CAAC,QAAQ,QAAQ,GAAG,IAAI;AACnD,KAAI,YAAY,IAAI;AAClB,eAAa,KAAA;AACb;;AAEF,KAAI,YAAY,YAAY,QAAS;AACrC,cAAa,OAAO,QAAQ;AAC5B,UAAO,KAAK,8BAA8B,WAAW,UAAU;;AAGjE,SAAgB,sBAA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pieces/activepieces/types.ts","../src/pieces/activepieces/context/stubs.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/worker/json-safe.ts","../src/pieces/activepieces/context/store-scope.ts","../src/pieces/activepieces/context/action.ts","../src/pieces/activepieces/context/limits.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/trigger.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/redact.ts"],"sourcesContent":["// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<DropdownOption<unknown>, \"label\" | \"value\">;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<BasePropertySchema, \"displayName\" | \"description\" | \"placeholder\">\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n };\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n run: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n props?: Record<string, ApProperty>;\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n auth?: ApProperty;\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","export class UnsupportedContextMemberError extends Error {\n readonly member: string;\n\n constructor(member: string) {\n super(\n `Piece used unimplemented context member \"${member}\". ` +\n `Implement it in the adapter or reject the piece at conformance time.`,\n );\n this.name = \"UnsupportedContextMemberError\";\n this.member = member;\n }\n}\n\n// Traps calls and member reads so both `ctx.files.write(...)` and\n// `ctx.server.apiUrl` throw with the full member path.\nexport function throwingStub(memberPath: string): unknown {\n return new Proxy(function stub() {}, {\n get(_target, prop) {\n // `then` and symbols stay inert so `await`/inspection don't false-trip.\n if (typeof prop !== \"string\" || prop === \"then\") return undefined;\n throw new UnsupportedContextMemberError(`${memberPath}.${prop}`);\n },\n apply() {\n throw new UnsupportedContextMemberError(memberPath);\n },\n });\n}\n\n// Wraps a context object so every top-level read is recorded; reads of\n// members outside the documented surface are flagged as UNDOCUMENTED.\nexport function withTouchTracking<T extends object>(\n base: T,\n touched: Set<string>,\n onTouch?: (member: string) => void,\n): T {\n return new Proxy(base, {\n get(target, prop, receiver) {\n if (typeof prop === \"string\" && prop !== \"then\") {\n const member = prop in target ? prop : `UNDOCUMENTED:${prop}`;\n touched.add(member);\n onTouch?.(member);\n }\n return Reflect.get(target, prop, receiver) as unknown;\n },\n });\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest extends HostScopedRequest, PieceModuleRef {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n // Serve `ctx.reactor` over the call channel. Set only for a piece the host\n // loaded from an installed reactor package; a fetched bundle never gets it.\n reactorAccess?: boolean;\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // As on a run: an options() resolver of a package piece may read the reactor\n // it is offering choices from.\n reactorAccess?: boolean;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest extends HostScopedRequest, PieceModuleRef {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece declares neither app.checkConnection nor auth.validate.\n declared: boolean;\n // Its return value: void | boolean | { name | username | email | sub }.\n result?: unknown;\n // Why the check failed, when the hook said so. auth.validate carries a\n // message; app.checkConnection only ever returns false.\n detail?: string;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n}\n\nexport interface ErrorResponse {\n id: number;\n type: \"error\";\n error: SerializedPieceError;\n tlsPoisoned: boolean;\n}\n\nexport type WorkerResponse = ResultResponse | ErrorResponse;\n\n// A request the child makes of its host while a step is running: the reverse\n// direction of everything above, and the only way a piece reaches durable state.\n\n// Ids are the child's own counter, a separate space from the host's, which is\n// why every handler dispatches on `type` before comparing an id.\nexport interface HostCallMessage {\n id: number;\n type: \"host-call\";\n method: string;\n payload: unknown;\n}\n\n// `error` carries the failure as data: a rejected promise cannot cross IPC,\n// so the reply always arrives and the child rethrows.\nexport interface HostCallResponse {\n id: number;\n type: \"host-result\";\n value?: unknown;\n error?: string;\n}\n\n// What the host will answer for the request in flight. Registered per request,\n// so a call arriving after the step returned finds nothing and is refused.\nexport type HostCallHandlers = Record<\n string,\n (payload: unknown) => Promise<unknown>\n>;\n\n// The one-way half of the channel: a report the host may act on, with no\n// answer to wait for. Their engine splits the same way (rpc vs rpc-notify).\n\n// A tap must never stall the step, so these carry no id and no reply. Node's\n// IPC preserves order, which is what drains them before the result lands.\nexport interface HostNotifyMessage {\n type: \"host-notify\";\n method: string;\n payload: unknown;\n}\n\n// Handlers registered per request, like HostCallHandlers. A throw here is\n// swallowed: a failed tap must not fail the step it was reporting on.\nexport type HostNotifyHandlers = Record<string, (payload: unknown) => void>;\n\n// One console call the piece made, already flattened to a string in the child.\nexport interface PieceLogEntry {\n level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n at: number;\n}\n\nexport const LOG_WRITE = \"log.write\";\nexport const OUTPUT_UPDATE = \"output.update\";\n\n// A store call carries `{ key, value?, scope }`. The scope is a name the host\n// partitions on, never a prefix the child bakes into the key.\nexport const STORE_GET = \"store.get\";\nexport const STORE_PUT = \"store.put\";\nexport const STORE_DELETE = \"store.delete\";\n\n// A reactor call carries the operation's own input object; the host answers\n// with documents already projected to summaries (see context/reactor.ts).\nexport const REACTOR_MODELS = \"reactor.models\";\nexport const REACTOR_MODEL = \"reactor.model\";\nexport const REACTOR_GET = \"reactor.get\";\nexport const REACTOR_FIND = \"reactor.find\";\nexport const REACTOR_CREATE = \"reactor.create\";\nexport const REACTOR_EXECUTE = \"reactor.execute\";\n","// Everything the child sends crosses a structured-clone boundary. A piece's\n// own objects routinely do not survive it, so they are flattened first.\nexport function jsonSafe(value: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(value)) as unknown;\n } catch {\n return String(value);\n }\n}\n","// Their StoreScope, as a name the host can partition on.\nimport { StoreScope } from \"@powerhousedao/pieces-framework\";\n\n// The enum's PROJECT member carries the legacy value \"COLLECTION\", and an\n// omitted scope means FLOW, so both are folded to one name here.\nexport type StoreScopeName = keyof typeof StoreScope;\n\n// Compared by value, never by enum identity: a piece bundle inlines its own\n// copy of StoreScope, and some pass the member name instead of its value.\nexport function normalizeStoreScope(scope?: unknown): StoreScopeName {\n return scope === StoreScope.PROJECT || scope === \"PROJECT\"\n ? \"PROJECT\"\n : \"FLOW\";\n}\n","// Our ActionContext → their ActionContext (doc 06 §2.8). Implements the top usage\n// tier (propsValue, auth, store, connections); the rest throws loudly, named.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type { ConnectionsProvider } from \"./props.js\";\nimport type {\n BaseContext,\n ConnectionsManager,\n ExecutionType,\n FilesService,\n FlowsContext,\n InputPropertyMap,\n OutputContext,\n ReactorService,\n RunContext,\n ServerContext,\n StepContext,\n Store,\n TagsManager,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { UnsupportedContextMemberError } from \"./stubs.js\";\n\n// The scope travels beside the key rather than inside it: which partition a\n// key belongs to is the host's decision, not a naming convention.\n\n// The host's half of the framework's Store, with its generics dropped: a\n// durable store round-trips through JSON, so nothing comes back as the T put in.\nexport interface KeyValueStore {\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown>;\n get(key: string, scope?: StoreScopeName): Promise<unknown>;\n delete(key: string, scope?: StoreScopeName): Promise<void>;\n}\n\n// In-memory connection registry: key → resolved connection value.\nexport class InMemoryConnectionsProvider implements ConnectionsProvider {\n private readonly values: Map<string, unknown>;\n\n constructor(values: Record<string, unknown> = {}) {\n this.values = new Map(Object.entries(values));\n }\n\n set(key: string, value: unknown): void {\n this.values.set(key, value);\n }\n\n get(key: string): Promise<unknown> {\n return Promise.resolve(this.values.get(key) ?? null);\n }\n}\n\nexport class InMemoryKeyValueStore implements KeyValueStore {\n private readonly entries: Map<string, unknown>;\n\n constructor(seed: Record<string, unknown> = {}) {\n this.entries = new Map(Object.entries(seed));\n }\n\n snapshot(): Record<string, unknown> {\n return Object.fromEntries(this.entries);\n }\n\n // Flattened like the durable store, so the heap fallback is not the one\n // place a Date survives a put.\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown> {\n const stored = jsonSafe(value);\n this.entries.set(this.scoped(key, scope), stored);\n return Promise.resolve(stored);\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return Promise.resolve(this.entries.get(this.scoped(key, scope)) ?? null);\n }\n\n delete(key: string, scope?: StoreScopeName): Promise<void> {\n this.entries.delete(this.scoped(key, scope));\n return Promise.resolve();\n }\n\n // One heap, so the scopes share it and are kept apart by name.\n private scoped(key: string, scope?: StoreScopeName): string {\n return scope === \"PROJECT\" ? `PROJECT:${key}` : key;\n }\n}\n\nexport interface ActionContextIdentity {\n runId?: string;\n projectId?: string;\n flowId?: string;\n flowVersionId?: string;\n stepName?: string;\n}\n\nexport interface ActionContextOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // ctx.files for actions. Mirrors the option triggers already accept; when\n // omitted the member keeps throwing, so a piece that needs files fails\n // loudly rather than silently dropping them.\n files?: ApFilesService;\n connections?: ConnectionsProvider;\n // ctx.output.update, the piece's own progress report. Omitted, the member\n // throws, so a piece that depends on it fails by name rather than silently.\n output?: { update(output: unknown): Promise<void> };\n // ctx.reactor. Served only to a piece the host loaded from an installed\n // reactor package; for every other piece the member throws by name.\n reactor?: ReactorService;\n executionType?: `${ExecutionType}`;\n identity?: ActionContextIdentity;\n onTouch?: (member: string) => void;\n}\n\n// Shape of the context we hand to `action.run()`: the framework's ActionContext\n// member for member. Those beyond the implemented tier throw, named.\nexport interface BuiltApActionContext {\n executionType: `${ExecutionType}`;\n auth: unknown;\n propsValue: Record<string, unknown>;\n store: Store;\n connections: ConnectionsManager;\n tags: TagsManager;\n server: ServerContext;\n files: FilesService;\n output: OutputContext;\n reactor: ReactorService;\n // Carried by the framework's own test double but absent from its types.\n agent: { tools: unknown[] };\n run: RunContext;\n project: BaseContext<undefined, InputPropertyMap>[\"project\"];\n flows: FlowsContext;\n step: StepContext;\n generateResumeUrl(params: {\n queryParams: Record<string, string>;\n sync?: boolean;\n }): string;\n}\n\nexport interface ActionContextHandle {\n context: BuiltApActionContext;\n // Top-level members the piece read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildActionContext(\n options: ActionContextOptions,\n): ActionContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n\n const base: Record<string, unknown> = {\n executionType: options.executionType ?? \"BEGIN\",\n auth: options.auth,\n propsValue: options.propsValue,\n store: {\n put: (key: string, value: unknown, scope?: unknown) =>\n store.put(key, value, normalizeStoreScope(scope)),\n get: (key: string, scope?: unknown) =>\n store.get(key, normalizeStoreScope(scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(key, normalizeStoreScope(scope)),\n },\n connections: options.connections ?? throwingStub(\"connections\"),\n tags: throwingStub(\"tags\"),\n server: throwingStub(\"server\"),\n files: options.files ?? throwingStub(\"files\"),\n output: options.output ?? throwingStub(\"output\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n agent: throwingStub(\"agent\"),\n run: {\n id: identity.runId ?? \"run\",\n stop: throwingStub(\"run.stop\"),\n pause: throwingStub(\"run.pause\"),\n respond: throwingStub(\"run.respond\"),\n createWaitpoint: throwingStub(\"run.createWaitpoint\"),\n waitForWaitpoint: throwingStub(\"run.waitForWaitpoint\"),\n },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n flows: {\n list: throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"step\" },\n generateResumeUrl: throwingStub(\"generateResumeUrl\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApActionContext, touched };\n}\n","// One file-size ceiling for both directions. Inbound hydration (a FILE prop\n// that arrives as a URL, a data URI or an attachment ref) and outbound\n// ctx.files.write share it, because a piece that can emit a file the next step\n// cannot ingest is worse than a piece that refuses both.\nexport const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n// What the environment asks for, or undefined when it asks for nothing usable.\n// Read per call: a host may set it after this module is loaded.\nexport function configuredMaxFileBytes(): number | undefined {\n const raw = process.env.PH_WORKFLOWS_PIECE_MAX_FILE_BYTES;\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : undefined;\n}\n\n// The worker child is forked without an environment, so its limit arrives on\n// the wire instead. Requests are serialized per worker: one value at a time.\nlet fromWire: number | undefined;\n\nexport function setMaxFileBytes(limit: number | undefined): void {\n fromWire = limit;\n}\n\nexport function maxFileBytes(): number {\n return fromWire ?? configuredMaxFileBytes() ?? DEFAULT_MAX_FILE_BYTES;\n}\n\nexport class FileTooLargeError extends Error {\n readonly size: number;\n readonly limit: number;\n\n constructor(size: number, limit: number = maxFileBytes()) {\n super(\n `File of ${size} bytes exceeds the ${limit} byte limit ` +\n `(raise PH_WORKFLOWS_PIECE_MAX_FILE_BYTES to allow more)`,\n );\n this.name = \"FileTooLargeError\";\n this.size = size;\n this.limit = limit;\n }\n}\n\nexport function assertWithinLimit(size: number): void {\n const limit = maxFileBytes();\n if (size > limit) throw new FileTooLargeError(size, limit);\n}\n","// Two FilesService implementations plus the staged-file contract that carries\n// bytes back to the host.\n//\n// `ctx.files.write()` is called *during* action.run(), inside the forked\n// worker, and the worker protocol has no worker-to-host request channel. So\n// this follows the pattern storeState already establishes — push in, return\n// whole — using the one thing a fork shares with its parent: the filesystem.\n// The worker writes bytes to a staging directory and returns a provisional\n// `apfile://<token>`; the host ingests each staged file after the step returns\n// and rewrites the tokens in the output before journalling it.\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n assertWithinLimit,\n FileTooLargeError,\n maxFileBytes,\n} from \"./limits.js\";\n\nexport { FileTooLargeError, maxFileBytes };\n\nexport const APFILE_SCHEME = \"apfile://\";\n\n// One file the piece wrote, as it crosses back on ResultResponse.files.\nexport interface StagedFile {\n // The provisional ref handed to the piece; the host rewrites it in place.\n token: string;\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n}\n\n// The framework's FilesService for both actions and triggers, narrowed to a\n// Buffer (the staging path cannot stream) with fileName optional.\nexport interface ApFilesService {\n write(file: { fileName?: string; data: Buffer }): Promise<string>;\n}\n\n// Default for both actions and triggers when the host injects nothing: inline\n// the bytes as a data URI so the payload stays self-contained. Bounded by the\n// shared cap, since a data URI lands in the run journal.\nexport class DataUriFilesService implements ApFilesService {\n write(file: { fileName?: string; data: Buffer }): Promise<string> {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n if (data.byteLength > maxFileBytes()) {\n return Promise.reject(new FileTooLargeError(data.byteLength));\n }\n return Promise.resolve(\n `data:application/octet-stream;base64,${data.toString(\"base64\")}`,\n );\n }\n}\n\nconst EXTENSION_TYPES: Record<string, string> = {\n pdf: \"application/pdf\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n tif: \"image/tiff\",\n tiff: \"image/tiff\",\n txt: \"text/plain\",\n json: \"application/json\",\n csv: \"text/csv\",\n};\n\nfunction contentTypeFor(fileName: string): string | undefined {\n const extension = fileName.split(\".\").pop()?.toLowerCase();\n return extension ? EXTENSION_TYPES[extension] : undefined;\n}\n\n// Worker-side service: writes into `<stagingDir>/<uuid>` and remembers what it\n// wrote so the worker can report it on the response.\nexport class StagedFilesService implements ApFilesService {\n private readonly files: StagedFile[] = [];\n\n constructor(private readonly stagingDir: string) {}\n\n staged(): StagedFile[] {\n return [...this.files];\n }\n\n async write(file: { fileName?: string; data: Buffer }): Promise<string> {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n // Checked before the write: a piece must not be able to fill the disk by\n // handing over a file the host would refuse anyway.\n assertWithinLimit(data.byteLength);\n const token = randomUUID();\n const fileName =\n file.fileName && file.fileName !== \"\" ? file.fileName : token;\n const target = path.join(this.stagingDir, token);\n await mkdir(this.stagingDir, { recursive: true });\n await writeFile(target, data);\n this.files.push({\n token: `${APFILE_SCHEME}${token}`,\n path: target,\n fileName,\n size: data.byteLength,\n contentType: contentTypeFor(fileName),\n });\n return `${APFILE_SCHEME}${token}`;\n }\n}\n\n// Replaces every provisional token in a step output with the real ref the host\n// got back from its attachment store. Walks the whole value: a piece may nest\n// the ref anywhere, and a plain string replace over the serialized JSON would\n// corrupt any base64 that happens to contain the token.\nexport function rewriteFileRefs(\n value: unknown,\n refs: Map<string, string>,\n): unknown {\n if (refs.size === 0) return value;\n if (typeof value === \"string\") return refs.get(value) ?? value;\n if (Array.isArray(value)) {\n return value.map((entry) => rewriteFileRefs(entry, refs));\n }\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = rewriteFileRefs(entry, refs);\n }\n return out;\n }\n return value;\n}\n","// Our TriggerHookContext → theirs (doc 06 §2.8): one builder covering the\n// strategy variants; identity/payload as data, capabilities injected or stubbed.\nimport { Cron } from \"croner\";\nimport { DEDUPE_KEY_PROPERTY, type ApTrigger } from \"../types.js\";\nimport {\n InMemoryKeyValueStore,\n type ActionContextIdentity,\n type KeyValueStore,\n} from \"./action.js\";\nimport type { ConnectionsProvider, FlowsProvider } from \"./props.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport interface TriggerContextOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\nconst TEXT_FIELD = new RegExp(\n String.raw`\\b(authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token|(?:[a-z0-9]+[-_])*signature(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\4`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\nconst URL_USERINFO = /([a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, scheme: string, user: string) =>\n `${scheme}${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(name)}${quote}`,\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") return value.includes(REDACTED_PREFIX);\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n"],"mappings":";;;;;;;;;;;AAgHA,SAAgB,WAAW,OAA0C;AAGnE,SADE,OAAO,MAAM,YAAY,aAAa,MAAM,SAAS,GAAG,MAAM,YAC9C,EAAE;;AAItB,SAAgB,YAAY,OAA2C;AAGrE,SADE,OAAO,MAAM,aAAa,aAAa,MAAM,UAAU,GAAG,MAAM,aAC/C,EAAE;;;;AC1HvB,IAAa,gCAAb,cAAmD,MAAM;CACvD;CAEA,YAAY,QAAgB;AAC1B,QACE,4CAA4C,OAAO,yEAEpD;AACD,OAAK,OAAO;AACZ,OAAK,SAAS;;;AAMlB,SAAgB,aAAa,YAA6B;AACxD,QAAO,IAAI,MAAM,SAAS,OAAO,IAAI;EACnC,IAAI,SAAS,MAAM;AAEjB,OAAI,OAAO,SAAS,YAAY,SAAS,OAAQ,QAAO,KAAA;AACxD,SAAM,IAAI,8BAA8B,GAAG,WAAW,GAAG,OAAO;;EAElE,QAAQ;AACN,SAAM,IAAI,8BAA8B,WAAW;;EAEtD,CAAC;;AAKJ,SAAgB,kBACd,MACA,SACA,SACG;AACH,QAAO,IAAI,MAAM,MAAM,EACrB,IAAI,QAAQ,MAAM,UAAU;AAC1B,MAAI,OAAO,SAAS,YAAY,SAAS,QAAQ;GAC/C,MAAM,SAAS,QAAQ,SAAS,OAAO,gBAAgB;AACvD,WAAQ,IAAI,OAAO;AACnB,aAAU,OAAO;;AAEnB,SAAO,QAAQ,IAAI,QAAQ,MAAM,SAAS;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