@powerhousedao/reactor-workflow 6.2.3-dev.49 → 6.2.3-dev.50
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 +274 -8
- package/dist/index.d.ts +263 -32
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1293 -107
- package/dist/index.js.map +1 -1
- package/dist/{piece-registry-CpiVMWNv.js → piece-registry-BKRLK7Kv.js} +1192 -90
- package/dist/piece-registry-BKRLK7Kv.js.map +1 -0
- package/dist/{piece-registry-wQBhKJUl.d.ts → piece-registry-Ds8WkewF.d.ts} +232 -99
- package/dist/piece-registry-Ds8WkewF.d.ts.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +91 -3
- package/dist/testing.js.map +1 -0
- package/dist/worker-entry.js +5685 -285
- package/dist/worker-entry.js.map +1 -1
- package/package.json +16 -8
- package/dist/loader-Gkx6I_Bo.js +0 -91
- package/dist/loader-Gkx6I_Bo.js.map +0 -1
- package/dist/piece-registry-CpiVMWNv.js.map +0 -1
- package/dist/piece-registry-wQBhKJUl.d.ts.map +0 -1
- package/dist/reactor-rpc-BqAjCK1p.js +0 -1134
- package/dist/reactor-rpc-BqAjCK1p.js.map +0 -1
- package/dist/worker-entry.d.ts +0 -2
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"reactor-rpc-BqAjCK1p.js","names":[],"sources":["../src/pieces/activepieces/types.ts","../src/pieces/activepieces/context/stubs.ts","../src/pieces/activepieces/unsupported.ts","../src/pieces/activepieces/descriptor.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/protocol.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/redact.ts","../src/pieces/activepieces/worker/reactor-rpc.ts"],"sourcesContent":["// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<\n DropdownOption<unknown>,\n \"label\" | \"value\"\n> &\n Partial<Pick<DropdownOption<unknown>, \"description\" | \"icon\">>;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<\n BasePropertySchema,\n \"displayName\" | \"description\" | \"placeholder\" | \"advanced\"\n >\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n // Layout and control hints, each read off only the types that declare it.\n width?: string;\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // The core piece's form hints; see PiecePropDescriptor.\n showWhen?: unknown;\n emptyChoice?: unknown;\n };\n\n// Widened from PropertyGroupDisplay: tabs | section | summary | builder | footer.\nexport interface ApPropertyGroup {\n key?: string;\n display?: string;\n label?: string;\n description?: string;\n icon?: string;\n props?: string[];\n}\n\nexport interface ApErrorHandlingOption {\n defaultValue?: boolean;\n hide?: boolean;\n}\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n propertyGroups?: ApPropertyGroup[];\n // READ | SEARCH | WRITE | DESTRUCTIVE, widened for the cross-bundle reason.\n classification?: string;\n errorHandlingOptions?: {\n retryOnFailure?: ApErrorHandlingOption;\n continueOnFailure?: ApErrorHandlingOption;\n };\n // Output ports, read only off a piece the host runs in process.\n ports?: unknown;\n // \"read\" | \"write\"; anything else reads as undeclared.\n requireReactor?: unknown;\n run: (ctx: unknown) => Promise<unknown>;\n // Called instead of run by a single-step test.\n test?: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: unknown;\n requireReactor?: unknown;\n props?: Record<string, ApProperty>;\n propertyGroups?: ApPropertyGroup[];\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n // Widened from WebhookRenewConfiguration: CRON | NONE.\n renewConfiguration?: { strategy?: string; cronExpression?: string };\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n deprecated?: boolean;\n // An array when the piece offers several auth methods.\n auth?: ApProperty | ApProperty[];\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","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 { checkTriggerStrategy } from \"@powerhousedao/pieces-framework/workflow\";\nimport { Cron } from \"croner\";\n\n// Piece features this engine cannot run. Read off a loaded piece or off its\n// published listing alike, since both carry auth and triggers as data.\nconst ISSUES_URL = \"https://github.com/powerhouse-inc/powerhouse/issues/\";\n\nexport interface UnsupportedFeature {\n feature: string;\n issue: number;\n // \"<feature> is not supported yet (<issue url>)\", what a listing shows.\n reason: string;\n}\n\nfunction unsupported(feature: string, issue: number): UnsupportedFeature {\n return {\n feature,\n issue,\n reason: `${feature} is not supported yet (${ISSUES_URL}${issue})`,\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n// A piece's auth, from the bundle or the listing. With several methods the\n// piece runs if any one does; the connection picks which.\nexport function unsupportedAuth(auth: unknown): UnsupportedFeature | undefined {\n if (Array.isArray(auth)) {\n const reasons = auth.map(unsupportedMethod);\n return reasons.some((reason) => reason === undefined)\n ? undefined\n : reasons[0];\n }\n return unsupportedMethod(auth);\n}\n\n// The method a connection of `type` signs in with: the piece's only auth,\n// or the entry of that type among several (upstream's getAuthPropertyForValue).\nexport function authMethodFor(auth: unknown, type: unknown): unknown {\n if (!Array.isArray(auth)) return auth;\n return auth.find((entry) => isRecord(entry) && entry.type === type);\n}\n\nfunction unsupportedMethod(auth: unknown): UnsupportedFeature | undefined {\n if (!isRecord(auth)) return undefined;\n if (auth.type === \"OAUTH2\" && auth.grantType === \"client_credentials\") {\n return unsupported(\"OAuth2 client credentials\", 3091);\n }\n if (auth.type === \"OIDC\") return unsupported(\"OIDC auth\", 3091);\n if (auth.type === \"CUSTOM_AUTH\" && auth.refresh != null) {\n return unsupported(\"CustomAuth refresh\", 3091);\n }\n return undefined;\n}\n\n// A piece trigger; the core piece's triggers are fed by the host and never pass here.\nexport function unsupportedTrigger(trigger: {\n type?: unknown;\n renewConfiguration?: unknown;\n}): UnsupportedFeature | undefined {\n if (trigger.type === \"MANUAL\") {\n return unsupported(\"TriggerStrategy.MANUAL\", 3091);\n }\n const strategy = checkTriggerStrategy(trigger.type);\n if (\"issue\" in strategy) {\n const issue = trigger.type === \"APP_WEBHOOK\" ? 3081 : 3091;\n return {\n feature: `TriggerStrategy ${String(trigger.type)}`,\n issue,\n reason: `${strategy.issue} (${ISSUES_URL}${issue})`,\n };\n }\n const problem = renewProblem(trigger.renewConfiguration);\n if (problem) {\n return {\n feature: \"renewConfiguration\",\n issue: 3090,\n reason: `renewConfiguration ${problem} (${ISSUES_URL}3090)`,\n };\n }\n return undefined;\n}\n\n// A subscription the supervisor renews on a UTC cron by calling onRenew.\nexport interface TriggerRenew {\n strategy: \"CRON\";\n cronExpression: string;\n}\n\nfunction cronFires(cron: string): boolean {\n try {\n return (\n new Cron(cron, { timezone: \"UTC\", legacyMode: false }).nextRun() !== null\n );\n } catch {\n return false;\n }\n}\n\n// createTrigger fills in { strategy: \"NONE\" } for every trigger.\nfunction renewProblem(renew: unknown): string | undefined {\n if (renew === undefined || renew === null) return undefined;\n if (!isRecord(renew)) return \"is not an object\";\n if (renew.strategy === \"NONE\") return undefined;\n if (renew.strategy !== \"CRON\") {\n return `strategy ${String(renew.strategy)} is not supported`;\n }\n const cron = renew.cronExpression;\n if (typeof cron !== \"string\" || !cronFires(cron)) {\n return `cron ${JSON.stringify(cron)} is invalid`;\n }\n return undefined;\n}\n\n// The trigger's renewal, when it declares a valid CRON one.\nexport function triggerRenew(trigger: {\n renewConfiguration?: unknown;\n}): TriggerRenew | undefined {\n const renew = trigger.renewConfiguration;\n if (!isRecord(renew) || renew.strategy !== \"CRON\") return undefined;\n if (renewProblem(renew)) return undefined;\n return { strategy: \"CRON\", cronExpression: renew.cronExpression as string };\n}\n\nexport class UnsupportedPieceFeatureError extends Error {\n readonly feature: string;\n readonly issue: number;\n\n constructor(subject: string, unsupportedFeature: UnsupportedFeature) {\n super(`${subject}: ${unsupportedFeature.reason}`);\n this.name = \"UnsupportedPieceFeatureError\";\n this.feature = unsupportedFeature.feature;\n this.issue = unsupportedFeature.issue;\n }\n}\n","import type { RequireReactor } from \"@powerhousedao/pieces-framework\";\nimport {\n PIECE_ACTION_PORTS,\n TRIGGER_PORTS,\n} from \"@powerhousedao/pieces-framework/workflow\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApPropertyType,\n type ApDropdownOption,\n type ApPropertyGroup,\n type ApTrigger,\n type ApTriggerStrategy,\n} from \"./types.js\";\nimport {\n triggerRenew,\n unsupportedAuth,\n unsupportedTrigger,\n type TriggerRenew,\n type UnsupportedFeature,\n} from \"./unsupported.js\";\n\nexport interface PiecePropDescriptor {\n name: string;\n displayName: string;\n description?: string;\n placeholder?: string;\n type: ApPropertyType;\n required: boolean;\n defaultValue?: unknown;\n // STATIC_DROPDOWN choices, extracted so the editor needs no runtime call.\n staticOptions?: ApDropdownOption[];\n // True when the prop carries a design-time resolver (DROPDOWN options() / DYNAMIC props()).\n hasDynamicResolver: boolean;\n // Synthesised domain-provider id: activepieces:<pkg>#<action>.<prop> (doc 08 §6.3).\n // Only top-level props get one; nested resolvers are not addressable yet.\n dynamicResolverId?: string;\n // Sibling prop names whose values feed the resolver; the editor re-runs\n // it when any of them changes.\n refreshers?: string[];\n // Nested shape: an ARRAY item's fields, or the props a DYNAMIC resolver\n // produced (see describeProperties). OBJECT props are free-form and carry none.\n properties?: PiecePropDescriptor[];\n // Activepieces' layout hint: rendered in the collapsed advanced section.\n advanced?: boolean;\n // Layout and control hints (see describeHints); absent when not declared.\n width?: \"half\" | \"full\";\n icon?: string;\n reveals?: string[];\n variant?: string;\n display?: string;\n min?: number;\n max?: number;\n step?: number;\n refreshOnSearch?: boolean;\n formatProperty?: string;\n // A STATIC_DROPDOWN's own state, beside its options.\n staticDisabled?: boolean;\n staticPlaceholder?: string;\n // Shown while a sibling holds one of `oneOf`.\n showWhen?: { prop: string; oneOf: unknown[] };\n // A checkbox with this label that stores \"\" on purpose.\n emptyChoice?: string;\n}\n\nexport interface PiecePropertyGroupDescriptor {\n key: string;\n display: string;\n label?: string;\n description?: string;\n icon?: string;\n props: string[];\n}\n\nexport interface PieceErrorHandlingDescriptor {\n retryOnFailure?: { defaultValue?: boolean; hide?: boolean };\n continueOnFailure?: { defaultValue?: boolean; hide?: boolean };\n}\n\nexport interface PieceActionDescriptor {\n name: string;\n displayName: string;\n description?: string;\n // UI metadata only — not a credential contract (spike finding).\n requireAuth: boolean;\n // The reactor access the step asks for; absent when it asks for none.\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n // Output ports the step can leave on; the editor draws only these.\n ports: readonly string[];\n // Carried verbatim: it is what the expression picker builds a later step's\n // field list from, and a package piece has no published listing to read.\n outputSchema?: unknown;\n // Orders the action picker, so a package piece that declares it must be\n // ordered by it too rather than counting as unset.\n audience?: string;\n propertyGroups?: PiecePropertyGroupDescriptor[];\n classification?: string;\n errorHandlingOptions?: PieceErrorHandlingDescriptor;\n}\n\nexport interface PieceTriggerDescriptor {\n name: string;\n displayName: string;\n description?: string;\n strategy: ApTriggerStrategy;\n testStrategy?: string;\n // A form the editor draws instead of the props, e.g. \"schedule\".\n display?: string;\n requireAuth: boolean;\n requireReactor?: RequireReactor;\n props: PiecePropDescriptor[];\n ports: readonly string[];\n propertyGroups?: PiecePropertyGroupDescriptor[];\n outputSchema?: unknown;\n hasSampleData: boolean;\n // The sample itself, not just whether there is one: a trigger that declares\n // no outputSchema is read for its shape instead.\n sampleData?: unknown;\n // How the sender proves the endpoint exists before it will register it.\n // Absent when the trigger declares no handshake, or declares NONE.\n handshake?: { strategy: string; paramName?: string };\n // When the provider's subscription must be renewed; absent for NONE.\n renew?: TriggerRenew;\n // A trigger feature the engine cannot run; the piece's own is on the piece.\n unsupported?: UnsupportedFeature;\n}\n\nexport interface PieceAuthDescriptor {\n type: ApPropertyType;\n displayName?: string;\n description?: string;\n required?: boolean;\n // CUSTOM_AUTH's own fields. Without them a connection form has nothing to\n // ask for, which is what a piece read from a package rather than a published\n // listing would otherwise leave the editor with.\n props?: PiecePropDescriptor[];\n // OAUTH2 only: where and how the provider signs a user in.\n oauth2?: OAuth2MethodDescriptor;\n // Set when this engine can't sign in this way (OIDC, for one).\n unsupported?: UnsupportedFeature;\n}\n\nexport interface OAuth2MethodDescriptor {\n // May hold `{prop}` placeholders, filled from the connection's props.\n authUrl: string;\n tokenUrl: string;\n scope: string[];\n prompt?: \"none\" | \"consent\" | \"login\" | \"omit\";\n pkce?: boolean;\n pkceMethod?: \"plain\" | \"S256\";\n authorizationMethod?: \"HEADER\" | \"BODY\";\n grantType?: string;\n // Extra authorize-URL parameters, e.g. access_type=offline.\n extra?: Record<string, string>;\n}\n\nfunction describeOAuth2(\n raw: Record<string, unknown>,\n): OAuth2MethodDescriptor | undefined {\n if (typeof raw.authUrl !== \"string\" || typeof raw.tokenUrl !== \"string\") {\n return undefined;\n }\n const strings = (value: unknown) =>\n Array.isArray(value)\n ? value.filter((entry): entry is string => typeof entry === \"string\")\n : [];\n const extra =\n raw.extra && typeof raw.extra === \"object\"\n ? Object.fromEntries(\n Object.entries(raw.extra).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n ),\n )\n : undefined;\n return {\n authUrl: raw.authUrl,\n tokenUrl: raw.tokenUrl,\n scope: strings(raw.scope),\n ...(typeof raw.prompt === \"string\"\n ? { prompt: raw.prompt as OAuth2MethodDescriptor[\"prompt\"] }\n : {}),\n ...(typeof raw.pkce === \"boolean\" ? { pkce: raw.pkce } : {}),\n ...(raw.pkceMethod === \"plain\" || raw.pkceMethod === \"S256\"\n ? { pkceMethod: raw.pkceMethod }\n : {}),\n ...(raw.authorizationMethod === \"HEADER\" ||\n raw.authorizationMethod === \"BODY\"\n ? { authorizationMethod: raw.authorizationMethod }\n : {}),\n ...(typeof raw.grantType === \"string\" ? { grantType: raw.grantType } : {}),\n ...(extra && Object.keys(extra).length > 0 ? { extra } : {}),\n };\n}\n\n// NONE is how the framework spells \"no handshake\", so it is not carried:\n// a caller checking the field would otherwise have to know that too.\nfunction describeHandshake(\n trigger: ApTrigger,\n): { strategy: string; paramName?: string } | undefined {\n const strategy = trigger.handshakeConfiguration?.strategy;\n if (!strategy || strategy === \"NONE\") return undefined;\n return { strategy, paramName: trigger.handshakeConfiguration?.paramName };\n}\n\nexport interface PieceSource {\n packageName: string;\n version: string;\n}\n\n// Serializable descriptor of an adapted piece; the engine never learns\n// Activepieces exists (doc 08 §6.2).\nexport interface PieceDescriptor {\n id: string;\n source: PieceSource;\n displayName: string;\n description?: string;\n logoUrl?: string;\n categories?: string[];\n deprecated?: boolean;\n // A list when the piece offers several sign-in methods.\n auth?: PieceAuthDescriptor | PieceAuthDescriptor[];\n minimumSupportedRelease?: string;\n maximumSupportedRelease?: string;\n actions: PieceActionDescriptor[];\n triggers: PieceTriggerDescriptor[];\n // Set when no block of the piece can run here, e.g. an OAuth2 piece.\n unsupported?: UnsupportedFeature;\n}\n\nfunction optional<K extends string, V>(\n key: K,\n value: V | undefined,\n): Partial<Record<K, V>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, V>);\n}\n\nexport function describeOption(option: ApDropdownOption): ApDropdownOption {\n return {\n label: option.label,\n value: option.value,\n ...(typeof option.description === \"string\" && option.description\n ? { description: option.description }\n : {}),\n ...(typeof option.icon === \"string\" && option.icon\n ? { icon: option.icon }\n : {}),\n };\n}\n\n// Copied only when well-formed: a foreign bundle may carry anything here.\nfunction describeHints(prop: ApProperty): Partial<PiecePropDescriptor> {\n const hints: Partial<PiecePropDescriptor> = {};\n if (prop.width === \"half\" || prop.width === \"full\") hints.width = prop.width;\n const strings = [\"icon\", \"variant\", \"display\", \"formatProperty\"] as const;\n for (const key of strings) {\n const value = prop[key];\n if (typeof value === \"string\" && value !== \"\") hints[key] = value;\n }\n const numbers = [\"min\", \"max\", \"step\"] as const;\n for (const key of numbers) {\n const value = prop[key];\n if (typeof value === \"number\" && Number.isFinite(value)) hints[key] = value;\n }\n if (Array.isArray(prop.reveals)) {\n const reveals = prop.reveals.filter(\n (name): name is string => typeof name === \"string\",\n );\n if (reveals.length > 0) hints.reveals = reveals;\n }\n if (prop.refreshOnSearch === true) hints.refreshOnSearch = true;\n const showWhen = prop.showWhen as { prop?: unknown; oneOf?: unknown } | null;\n if (typeof showWhen?.prop === \"string\" && Array.isArray(showWhen.oneOf)) {\n const oneOf: unknown[] = showWhen.oneOf;\n hints.showWhen = { prop: showWhen.prop, oneOf: [...oneOf] };\n }\n if (typeof prop.emptyChoice === \"string\" && prop.emptyChoice !== \"\") {\n hints.emptyChoice = prop.emptyChoice;\n }\n return hints;\n}\n\nfunction describeGroups(\n groups: ApPropertyGroup[] | undefined,\n): PiecePropertyGroupDescriptor[] | undefined {\n if (!Array.isArray(groups)) return undefined;\n const described = groups\n .filter(\n (group) =>\n typeof group.key === \"string\" &&\n typeof group.display === \"string\" &&\n Array.isArray(group.props),\n )\n .map((group) => ({\n key: group.key!,\n display: group.display!,\n ...(group.label ? { label: group.label } : {}),\n ...(group.description ? { description: group.description } : {}),\n ...(group.icon ? { icon: group.icon } : {}),\n props: group.props!.filter(\n (name): name is string => typeof name === \"string\",\n ),\n }));\n return described.length > 0 ? described : undefined;\n}\n\nfunction hasResolver(prop: ApProperty): boolean {\n return typeof prop.options === \"function\" || typeof prop.props === \"function\";\n}\n\nfunction toPropDescriptor(\n name: string,\n prop: ApProperty,\n resolverId?: string,\n): PiecePropDescriptor {\n const dynamic = hasResolver(prop);\n const descriptor: PiecePropDescriptor = {\n name,\n displayName: prop.displayName ?? name,\n type: prop.type ?? \"UNKNOWN\",\n required: prop.required ?? false,\n hasDynamicResolver: dynamic,\n };\n if (typeof prop.description === \"string\" && prop.description !== \"\") {\n descriptor.description = prop.description;\n }\n if (typeof prop.placeholder === \"string\" && prop.placeholder !== \"\") {\n descriptor.placeholder = prop.placeholder;\n }\n if (prop.defaultValue !== undefined) {\n descriptor.defaultValue = prop.defaultValue;\n }\n if (prop.advanced === true) descriptor.advanced = true;\n if (dynamic && resolverId) {\n descriptor.dynamicResolverId = resolverId;\n }\n if (dynamic && Array.isArray(prop.refreshers)) {\n descriptor.refreshers = prop.refreshers.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n }\n if (typeof prop.options === \"object\" && Array.isArray(prop.options.options)) {\n descriptor.staticOptions = prop.options.options.map(describeOption);\n if (prop.options.disabled === true) descriptor.staticDisabled = true;\n if (typeof prop.options.placeholder === \"string\") {\n descriptor.staticPlaceholder = prop.options.placeholder;\n }\n }\n Object.assign(descriptor, describeHints(prop));\n if (prop.properties && typeof prop.properties === \"object\") {\n const nested = describeProperties(prop.properties);\n if (nested.length > 0) descriptor.properties = nested;\n }\n return descriptor;\n}\n\n// Descriptor list for a props map: nested ARRAY items and what a DYNAMIC\n// resolver returns, so the editor never sees raw piece properties.\nexport function describeProperties(\n props: Record<string, ApProperty> | null | undefined,\n resolverIdFor?: (propName: string) => string,\n): PiecePropDescriptor[] {\n if (!props || typeof props !== \"object\") return [];\n return Object.entries(props)\n .filter((entry): entry is [string, ApProperty] =>\n isPropertyObject(entry[1]),\n )\n .map(([propName, prop]) =>\n toPropDescriptor(propName, prop, resolverIdFor?.(propName)),\n );\n}\n\n// Bundles are duck-typed; a props map may carry non-object junk.\nfunction isPropertyObject(value: unknown): value is ApProperty {\n return value !== null && typeof value === \"object\";\n}\n\nfunction withUnsupported(feature: UnsupportedFeature | undefined): {\n unsupported?: UnsupportedFeature;\n} {\n return feature ? { unsupported: feature } : {};\n}\n\n// Pure translation over a loaded piece; performs no I/O and never executes\n// piece code beyond the actions()/triggers() accessors.\nfunction describeAuthMethod(auth: unknown): PieceAuthDescriptor | undefined {\n if (!auth || typeof auth !== \"object\") return undefined;\n const method = auth as ApProperty;\n // CUSTOM_AUTH carries a record here; a DYNAMIC prop would carry a\n // resolver function, which is not an auth shape at all.\n const props =\n method.props && typeof method.props === \"object\"\n ? describeProperties(method.props)\n : [];\n const oauth2 =\n method.type === \"OAUTH2\"\n ? describeOAuth2(auth as Record<string, unknown>)\n : undefined;\n return {\n type: method.type ?? \"UNKNOWN\",\n displayName: method.displayName,\n description: method.description,\n required: method.required,\n ...(props.length > 0 ? { props } : {}),\n ...(oauth2 ? { oauth2 } : {}),\n ...withUnsupported(unsupportedAuth(method)),\n };\n}\n\nfunction declaredPorts(ports: unknown): readonly string[] | undefined {\n if (!Array.isArray(ports) || ports.length === 0) return undefined;\n return ports.every((port) => typeof port === \"string\")\n ? (ports as string[])\n : undefined;\n}\n\n// Only a well-formed declaration is carried: a foreign bundle may hold anything.\nfunction declaredReactor(value: unknown): RequireReactor | undefined {\n return value === \"read\" || value === \"write\" ? value : undefined;\n}\n\nexport interface BuildDescriptorOptions {\n // Read each action's own `ports`: only a piece whose results the host routes.\n routed?: boolean;\n // The host feeds the triggers itself, so no trigger strategy is refused.\n hostFed?: boolean;\n}\n\nexport function buildDescriptor(\n piece: ApPiece,\n source: PieceSource,\n options: BuildDescriptorOptions = {},\n): PieceDescriptor {\n const actions = Object.entries(getActions(piece)).map(\n ([actionName, action]): PieceActionDescriptor => ({\n name: action.name ?? actionName,\n displayName: action.displayName ?? actionName,\n description: action.description,\n requireAuth: action.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(action.requireReactor)),\n ports:\n (options.routed ? declaredPorts(action.ports) : undefined) ??\n PIECE_ACTION_PORTS,\n props: describeProperties(\n action.props,\n (propName) =>\n `activepieces:${source.packageName}#${actionName}.${propName}`,\n ),\n ...(action.outputSchema !== undefined\n ? { outputSchema: action.outputSchema }\n : {}),\n ...(action.audience !== undefined ? { audience: action.audience } : {}),\n ...optional(\"propertyGroups\", describeGroups(action.propertyGroups)),\n ...optional(\n \"classification\",\n typeof action.classification === \"string\"\n ? action.classification\n : undefined,\n ),\n ...optional(\"errorHandlingOptions\", action.errorHandlingOptions),\n }),\n );\n\n const triggers = Object.entries(getTriggers(piece)).map(\n ([triggerName, trigger]): PieceTriggerDescriptor => ({\n name: trigger.name ?? triggerName,\n displayName: trigger.displayName ?? triggerName,\n description: trigger.description,\n strategy: trigger.type ?? \"UNKNOWN\",\n testStrategy: trigger.testStrategy,\n ...(typeof trigger.display === \"string\" && trigger.display !== \"\"\n ? { display: trigger.display }\n : {}),\n requireAuth: trigger.requireAuth ?? false,\n ...optional(\"requireReactor\", declaredReactor(trigger.requireReactor)),\n ports: TRIGGER_PORTS,\n props: describeProperties(\n trigger.props,\n (propName) =>\n `activepieces:${source.packageName}#${triggerName}.${propName}`,\n ),\n ...(trigger.outputSchema !== undefined\n ? { outputSchema: trigger.outputSchema }\n : {}),\n hasSampleData:\n trigger.sampleData !== undefined && trigger.sampleData !== null,\n ...(trigger.sampleData !== undefined && trigger.sampleData !== null\n ? { sampleData: trigger.sampleData }\n : {}),\n handshake: describeHandshake(trigger),\n ...optional(\"renew\", triggerRenew(trigger)),\n ...optional(\"propertyGroups\", describeGroups(trigger.propertyGroups)),\n ...(options.hostFed ? {} : withUnsupported(unsupportedTrigger(trigger))),\n }),\n );\n\n const descriptor: PieceDescriptor = {\n id: `activepieces:${source.packageName}`,\n source,\n displayName: piece.displayName,\n description: piece.description,\n logoUrl: piece.logoUrl,\n categories: piece.categories,\n ...(piece.deprecated === true ? { deprecated: true } : {}),\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n actions,\n triggers,\n ...withUnsupported(unsupportedAuth(piece.auth)),\n };\n // Several methods stay a list, in the piece's order; each says whether this\n // engine can run it.\n if (Array.isArray(piece.auth)) {\n const methods = piece.auth\n .map(describeAuthMethod)\n .filter((method) => method !== undefined);\n if (methods.length > 0) descriptor.auth = methods;\n } else {\n const method = describeAuthMethod(piece.auth);\n if (method) descriptor.auth = method;\n }\n return descriptor;\n}\n","// 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 { ReactorOption } from \"./reactor-option.js\";\nimport type {\n BaseContext,\n ConnectionsManager,\n ExecutionType,\n FilesService,\n FlowsContext,\n InputPropertyMap,\n OutputContext,\n ReactorClient,\n ReactorReadClient,\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 type ActionContextOptions = ActionContextBaseOptions & ReactorOption;\n\ninterface ActionContextBaseOptions {\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.resumePayload, the delivery that woke a RESUME run. This engine never\n // suspends a run, so no request carries one yet; omitted, the member throws\n // by name instead of reading as undefined.\n resumePayload?: unknown;\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: ReactorClient | ReactorReadClient;\n // The RESUME branch of the framework's ActionContext promises this\n // (ResumePayload there, a type its entry does not export). Always present,\n // real or throwing, like `reactor`.\n resumePayload: unknown;\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 resumePayload: options.resumePayload ?? throwingStub(\"resumePayload\"),\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 type { ReactorOption } from \"./reactor-option.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport type TriggerContextOptions = TriggerContextBaseOptions & ReactorOption;\n\ninterface TriggerContextBaseOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type { PropsValidationErrors } from \"../context/normalize.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n // Epoch ms at which the host kills the worker for this request.\n deadline?: number;\n // Cap on each host call. Absent leaves the built-in default.\n hostCallTimeoutMs?: number;\n}\n\n// `ctx.reactor` for one request: its RPC messages carry `requestId`, and the\n// host serves them only while the request is in flight.\nexport interface ReactorRequestBinding {\n requestId: string;\n requireReactor: \"read\" | \"write\";\n}\n\nexport interface ReactorScopedRequest {\n // Stamped by PieceWorker when the caller serves the reactor.\n reactor?: ReactorRequestBinding;\n}\n\nexport const REACTOR_RPC = \"reactor-rpc\";\nexport const MODEL_MANIFEST = \"model-manifest\";\n// Host call: a type's entries, or every entry the host knows without one.\nexport const MODEL_ENTRIES = \"model-entries\";\n\n// One reactor RPC message (`@powerhousedao/reactor/rpc`), either direction.\nexport interface ReactorRpcEnvelope {\n type: typeof REACTOR_RPC;\n requestId: string;\n message: unknown;\n}\n\n// Importable document models (the reactor's ModelManifestEntry), host to child\n// on fork. A type loaded later is looked up through MODEL_ENTRIES.\nexport interface ModelEntriesPayload {\n documentType?: string;\n}\n\nexport interface ModelManifestMessage {\n type: typeof MODEL_MANIFEST;\n entries: unknown[];\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n // The delivery that woke a RESUME run, served as ctx.resumePayload. This\n // engine never suspends a run, so nothing sets it yet; absent, the context\n // member keeps throwing by name.\n resumePayload?: unknown;\n // Call the action's test method instead of run, as a single-step test does.\n stepTest?: boolean;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // ctx.project.id, the same one a run of the piece is handed.\n projectId?: string;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest\n extends HostScopedRequest, PieceModuleRef, ReactorScopedRequest {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\" | \"onRenew\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece's auth declares no validate.\n declared: boolean;\n // validate's verdict; true when none is declared.\n valid: boolean;\n // Why validate failed, when it said so.\n detail?: string;\n // getConnectionIdentifier's label; it runs only once the check passes.\n accountLabel?: string;\n // Why getConnectionIdentifier threw. The check still passes.\n identifierError?: string;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n // Set when the piece or trigger uses a feature this engine does not run.\n unsupportedFeature?: string;\n // Set when the props failed validation, before piece code ran.\n invalidProps?: PropsValidationErrors;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n}\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","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\n\n// The affixed form is anchored on the literal \"signature\", with the prefix\n// matched by a lookbehind placed after it. A leading prefix pattern\n// ((?:[a-z0-9]+[-_])*signature) retries from every segment of a long\n// hyphen-separated run that never ends in \"signature\", which is quadratic:\n// whole seconds over a few hundred kilobytes of journaled text. The\n// lookbehind runs once per occurrence of the literal instead, and captures\n// the prefix so the marker still names the whole header.\nconst TEXT_FIELD = new RegExp(\n String.raw`(\\b(?:authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token)|signature(?<=\\b((?:[a-z0-9]+[-_])*)signature)(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\5`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\n\n// Anchored on \"://\" with the scheme checked by the lookbehind behind it: a\n// leading scheme pattern ([a-z][a-z0-9+.-]*) rescans a long unbroken\n// alphanumeric run from every offset, which is quadratic — tens of seconds\n// over a 256 KiB run. The scheme is not consumed, and not rewritten either\n// way; only the password half is replaced.\nconst URL_USERINFO =\n /:\\/\\/(?<=[a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, user: string) => `://${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n\n // signaturePrefix is the lookbehind's capture: the affixes before\n // \"signature\" sit outside the match, so they are stitched back onto the\n // name only for the marker — the text keeps them where they were.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n signaturePrefix: string | undefined,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(`${signaturePrefix ?? \"\"}${name}`)}${quote}`,\n );\n}\n\n// A document header's or reference's operation counts per scope. Scope names\n// such as \"auth\" are not credentials, and the counts are numbers.\nfunction isScopeRevision(\n parent: Record<string, unknown>,\n key: string,\n entry: unknown,\n): boolean {\n return (\n key === \"revision\" &&\n typeof parent.documentType === \"string\" &&\n typeof entry === \"object\" &&\n entry !== null &&\n !Array.isArray(entry) &&\n Object.values(entry).every(\n (count) => typeof count === \"number\" && Number.isFinite(count),\n )\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n const record = value as Record<string, unknown>;\n for (const [key, entry] of Object.entries(record)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : isScopeRevision(record, key, entry)\n ? { ...(entry as Record<string, number>) }\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\n\n// TRUNCATED_MARKER is matched whole, not as a substring: walk() only ever\n// writes it in place of an entire capped node, so prose that merely mentions\n// the word keeps replaying.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") {\n return value.includes(REDACTED_PREFIX) || value === TRUNCATED_MARKER;\n }\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n","// The reactor RPC on a piece child's IPC channel, bound to one request. It owns\n// only `reactor-rpc` envelopes carrying that request's id.\nimport {\n REACTOR_RPC,\n type ReactorRpcEnvelope,\n type ReactorRequestBinding,\n} from \"./protocol.js\";\nimport type { IPieceWorkerTransport } from \"./transport.js\";\n\n// Structurally `IRpcTransport` from `@powerhousedao/reactor/rpc`.\nexport interface ReactorRpcTransport {\n post(message: never): void;\n onMessage(listener: (message: never) => void): () => void;\n close(): void;\n}\n\n// Serves ctx.reactor for one request; `open` returns the stop run when it settles.\nexport interface ReactorTap {\n requireReactor: ReactorRequestBinding[\"requireReactor\"];\n open(\n transport: ReactorRpcTransport,\n request: { requestId: string; deadline: number },\n ): () => void;\n}\n\nexport function isReactorRpcEnvelope(\n value: unknown,\n requestId: string,\n): value is ReactorRpcEnvelope {\n if (typeof value !== \"object\" || value === null) return false;\n const envelope = value as Partial<ReactorRpcEnvelope>;\n return envelope.type === REACTOR_RPC && envelope.requestId === requestId;\n}\n\nfunction isRpcMessage(value: unknown): boolean {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { k?: unknown }).k === \"string\"\n );\n}\n\n// The host's end. The child runs piece code: another request's id, or a\n// message without a kind, is dropped.\nexport function createIpcTransport(\n worker: IPieceWorkerTransport,\n requestId: string,\n): ReactorRpcTransport {\n let closed = false;\n const detachers = new Set<() => void>();\n return {\n post(message: unknown) {\n if (closed || !worker.connected) return;\n worker.send({ type: REACTOR_RPC, requestId, message });\n },\n onMessage(listener: (message: never) => void) {\n const handler = (value: unknown) => {\n if (closed || !isReactorRpcEnvelope(value, requestId)) return;\n if (!isRpcMessage(value.message)) return;\n listener(value.message as never);\n };\n worker.on(\"message\", handler);\n const detach = () => {\n worker.off(\"message\", handler);\n detachers.delete(detach);\n };\n detachers.add(detach);\n return detach;\n },\n close() {\n closed = true;\n for (const detach of [...detachers]) detach();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAyKA,SAAgB,WAAW,OAA0C;CAGnE,QADE,OAAO,MAAM,YAAY,aAAa,MAAM,QAAQ,IAAI,MAAM,YAC9C,CAAC;AACrB;AAGA,SAAgB,YAAY,OAA2C;CAGrE,QADE,OAAO,MAAM,aAAa,aAAa,MAAM,SAAS,IAAI,MAAM,aAC/C,CAAC;AACtB;;;ACpLA,IAAa,gCAAb,cAAmD,MAAM;CACvD;CAEA,YAAY,QAAgB;EAC1B,MACE,4CAA4C,OAAO,wEAErD;EACA,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAIA,SAAgB,aAAa,YAA6B;CACxD,OAAO,IAAI,MAAM,SAAS,OAAO,CAAC,GAAG;EACnC,IAAI,SAAS,MAAM;GAEjB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,OAAO,KAAA;GACxD,MAAM,IAAI,8BAA8B,GAAG,WAAW,GAAG,MAAM;EACjE;EACA,QAAQ;GACN,MAAM,IAAI,8BAA8B,UAAU;EACpD;CACF,CAAC;AACH;AAIA,SAAgB,kBACd,MACA,SACA,SACG;CACH,OAAO,IAAI,MAAM,MAAM,EACrB,IAAI,QAAQ,MAAM,UAAU;EAC1B,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ;GAC/C,MAAM,SAAS,QAAQ,SAAS,OAAO,gBAAgB;GACvD,QAAQ,IAAI,MAAM;GAClB,UAAU,MAAM;EAClB;EACA,OAAO,Q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