@powerhousedao/reactor-workflow 6.2.3-dev.20 → 6.2.3-dev.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as FileTooLargeError, a as redactMessage, c as DEFAULT_EGRESS_POLICY, f as extractDedupeKey, n as containsRedactedMarker, o as rememberSecrets, r as redact, s as secretsFor, y as maxFileBytes } from "./redact-DCEJ-Imb.js";
2
- import { C as pieceModuleRef, D as setPieceRegistryUrl, E as pieceRegistrySource, S as localFirstResolver, _ as secretRefFromId, a as CompositeBlockExecutor, b as PieceWorkerError, c as storeHandlers, d as declaredConnectionIds, f as shapeConnection, g as parseSecretRef, h as SecretNotFoundError, i as ActivepiecesBlockExecutor, l as BoundConnectionResolver, m as SecretDeletedError, n as packagePieces, o as parseBlockType, r as runWorkflow, s as reactorHandlers, t as PieceRegistry, v as PieceWorkerPool, w as ensurePieceBundle, x as PieceWorkerTimeoutError, y as PieceWorker } from "./piece-registry-BU168FQf.js";
1
+ import { _ as FileTooLargeError, a as redactMessage, b as maxFileBytes, c as DEFAULT_EGRESS_POLICY, f as extractDedupeKey, n as containsRedactedMarker, o as rememberSecrets, r as redact, s as secretsFor } from "./redact-ChAU8USo.js";
2
+ import { A as setPieceRegistryUrl, C as PieceWorkerError, D as ensurePieceBundle, E as pieceModuleRef, S as PieceWorker, T as localFirstResolver, _ as SecretDeletedError, a as CompositeBlockExecutor, b as secretRefFromId, c as parseBlockType, d as storeHandlers, f as BoundConnectionResolver, h as shapeConnection, i as ActivepiecesBlockExecutor, k as pieceRegistrySource, l as reactorHandlers, m as declaredConnectionIds, n as packagePieces, o as REACTOR_PORT_PIECE, r as runWorkflow, s as blockTypeParts, t as PieceRegistry, u as servesReactorPort, v as SecretNotFoundError, w as PieceWorkerTimeoutError, x as PieceWorkerPool, y as parseSecretRef } from "./piece-registry-lsGsY9fT.js";
3
3
  import { WebhookHandshakeStrategy } from "@powerhousedao/pieces-framework";
4
4
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { open, readFile, rm } from "node:fs/promises";
@@ -81,7 +81,7 @@ function createAttachmentPort(client, documentIdFor, canReadRef) {
81
81
  const WORKFLOW_PACKAGE_NAME = "@powerhousedao/workflow";
82
82
  //#endregion
83
83
  //#region src/reactor/reactor-piece.ts
84
- const REACTOR_PIECE = "@powerhousedao/piece-reactor";
84
+ const REACTOR_PIECE = REACTOR_PORT_PIECE;
85
85
  function action(name) {
86
86
  return `${REACTOR_PIECE}#${name}`;
87
87
  }
@@ -353,9 +353,16 @@ function aiLast(audience) {
353
353
  function pieceUrl(packageName) {
354
354
  return `${CATALOG_URL}/${packageName}?audience=all`;
355
355
  }
356
+ var CatalogStatusError = class extends Error {
357
+ constructor(url, status) {
358
+ super(`${url} responded ${status}`);
359
+ this.status = status;
360
+ this.name = "CatalogStatusError";
361
+ }
362
+ };
356
363
  async function fetchJson(url, timeoutMs = 3e4) {
357
364
  const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
358
- if (!response.ok) throw new Error(`${url} responded ${response.status}`);
365
+ if (!response.ok) throw new CatalogStatusError(url, response.status);
359
366
  return response.json();
360
367
  }
361
368
  function asList(value) {
@@ -415,11 +422,15 @@ async function fetchPieceCatalog() {
415
422
  };
416
423
  return value;
417
424
  }
425
+ function registrySilentOn(error) {
426
+ return error instanceof CatalogStatusError && error.status === 404;
427
+ }
418
428
  async function fetchPieceJson(packageName) {
419
429
  const source = pieceRegistrySource();
420
430
  if (source) try {
421
431
  return await fetchJson(source.pieceUrl(packageName));
422
432
  } catch (error) {
433
+ if (!registrySilentOn(error)) throw error;
423
434
  logger$4.debug(`${source.baseUrl} does not serve "${packageName}": ${String(error)}`);
424
435
  }
425
436
  return fetchJson(pieceUrl(packageName));
@@ -517,8 +528,8 @@ function actionsResult(descriptor, pieceName, version) {
517
528
  displayName: action.displayName,
518
529
  description: action.description ?? "",
519
530
  blockType: localBlockType(pieceName, action.name, "action"),
520
- audience: null
521
- })),
531
+ audience: action.audience ?? null
532
+ })).sort((a, b) => aiLast(a.audience) - aiLast(b.audience)),
522
533
  auth: descriptor.auth ?? null
523
534
  };
524
535
  }
@@ -574,7 +585,9 @@ function detailResult(descriptor, pieceName, version) {
574
585
  displayName: action.displayName,
575
586
  description: action.description ?? "",
576
587
  props: action.props,
577
- requireAuth: action.requireAuth
588
+ requireAuth: action.requireAuth,
589
+ outputSchema: action.outputSchema,
590
+ audience: action.audience
578
591
  }])),
579
592
  triggers: Object.fromEntries(descriptor.triggers.map((trigger) => [trigger.name, {
580
593
  name: trigger.name,
@@ -582,7 +595,11 @@ function detailResult(descriptor, pieceName, version) {
582
595
  description: trigger.description ?? "",
583
596
  type: trigger.strategy,
584
597
  props: trigger.props,
585
- requireAuth: trigger.requireAuth
598
+ requireAuth: trigger.requireAuth,
599
+ outputSchema: trigger.outputSchema,
600
+ sampleData: trigger.sampleData,
601
+ testStrategy: trigger.testStrategy,
602
+ handshakeConfiguration: trigger.handshake
586
603
  }]))
587
604
  };
588
605
  }
@@ -748,9 +765,15 @@ function documentSummary(document, withState) {
748
765
  ...withState ? { state: globalState } : {}
749
766
  };
750
767
  }
751
- function assertOperationsApplied(document, count) {
752
- const failed = Object.values(document.operations).flat().sort((a, b) => a.index - b.index).slice(-Math.max(count, 1)).find((operation) => operation.error !== void 0);
753
- if (failed) throw new Error(`Action ${failed.action.type} failed: ${failed.error ?? "unknown error"}`);
768
+ function assertOperationsApplied(document, dispatched) {
769
+ const perScope = /* @__PURE__ */ new Map();
770
+ for (const action of dispatched) {
771
+ const scope = action.scope ?? "global";
772
+ perScope.set(scope, (perScope.get(scope) ?? 0) + 1);
773
+ }
774
+ const failed = [...perScope].flatMap(([scope, count]) => [...document.operations[scope] ?? []].sort((a, b) => a.index - b.index).slice(-count).filter((operation) => operation.error !== void 0));
775
+ if (failed.length === 0) return;
776
+ throw new Error(failed.map((operation) => `Action ${operation.action.type} failed: ${operation.error ?? "unknown error"}`).join("; "));
754
777
  }
755
778
  var SubgraphReactorPort = class {
756
779
  constructor(host) {
@@ -806,8 +829,9 @@ var SubgraphReactorPort = class {
806
829
  if (!target) {
807
830
  const created = await this.client.createEmpty(input.documentType, { parentIdentifier: input.parentId });
808
831
  if (!input.name) return documentSummary(created, true);
809
- const named = await this.client.execute(created.header.id, "main", [createAction("SET_NAME", { name: input.name })]);
810
- assertOperationsApplied(named, 1);
832
+ const naming = createAction("SET_NAME", { name: input.name });
833
+ const named = await this.client.execute(created.header.id, "main", [naming]);
834
+ assertOperationsApplied(named, [naming]);
811
835
  return documentSummary(named, true);
812
836
  }
813
837
  const empty = (await this.client.getDocumentModelModule(input.documentType)).utils.createDocument();
@@ -817,7 +841,7 @@ var SubgraphReactorPort = class {
817
841
  async execute(input) {
818
842
  const actions = input.actions.map((entry) => createAction(entry.type, entry.input, void 0, void 0, entry.scope ?? "global"));
819
843
  const document = await this.client.execute(input.documentId, input.branch ?? "main", actions);
820
- assertOperationsApplied(document, actions.length);
844
+ assertOperationsApplied(document, input.actions);
821
845
  return documentSummary(document, true);
822
846
  }
823
847
  async findByType(type, limit, parentId) {
@@ -948,7 +972,7 @@ async function resolveConnectionWithSecrets(document, secrets, request) {
948
972
  secretRefs: state.secretRefs
949
973
  }, secrets);
950
974
  }
951
- const EGRESS_ALLOW_ENV = "WORKFLOW_EGRESS_ALLOW_ADDRESSES";
975
+ const EGRESS_ALLOW_ENV = "PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES";
952
976
  function asCidr(entry) {
953
977
  if (entry.includes("/")) return entry;
954
978
  return entry.includes(":") ? `${entry}/128` : `${entry}/32`;
@@ -986,13 +1010,14 @@ function boundConnections(inner) {
986
1010
  connectionLogger.warn(`Step "${request?.stepKey ?? "?"}" of workflow "${currentWorkflowId() ?? "?"}" asked for connection "${connectionId}", which its definition does not declare`);
987
1011
  });
988
1012
  }
989
- function createBlockExecutor(host, secrets, attachments, pieceStore) {
1013
+ function createBlockExecutor(host, secrets, attachments, pieceStore, resolveBlockType) {
990
1014
  return new CompositeBlockExecutor(new ActivepiecesBlockExecutor({
991
1015
  cacheDir: BUNDLE_CACHE_DIR,
992
1016
  egress: configuredEgress(),
993
1017
  worker: currentPieceWorker,
994
1018
  resolver: pieceResolver(),
995
1019
  packages: () => Promise.resolve(packagePieces.versions()),
1020
+ ...resolveBlockType ? { resolveBlockType } : {},
996
1021
  reactor: new SubgraphReactorPort(host),
997
1022
  connections: boundConnections(new DocumentConnectionResolver(host, secrets)),
998
1023
  ...pieceStore ? { pieceStore } : {},
@@ -1202,6 +1227,105 @@ function createPieceStorePort(store, workflowIdFor, sample = false, clock = Date
1202
1227
  };
1203
1228
  }
1204
1229
  //#endregion
1230
+ //#region src/reactor/core-catalog.ts
1231
+ const CORE_PIECE_NAME = "core";
1232
+ function prop(name, displayName, description, options = {}) {
1233
+ return {
1234
+ name,
1235
+ displayName,
1236
+ description,
1237
+ type: options.type ?? "SHORT_TEXT",
1238
+ required: options.required ?? false,
1239
+ hasDynamicResolver: false
1240
+ };
1241
+ }
1242
+ const BRANCH = {
1243
+ name: "branch",
1244
+ displayName: "Branch",
1245
+ description: "Routes to the true or false port. With `equals` set it compares the two values, trimmed and case-insensitively; without it, any non-empty condition other than \"false\" or \"0\" is true. It resolves values — it does not evaluate expressions, so a condition of \"{{a}} == 'x'\" is a non-empty string and always takes the true port.",
1246
+ requireAuth: false,
1247
+ props: [prop("condition", "Condition", "The value to route on, usually an expression like {{trigger.payload.status}}.", { required: true }), prop("equals", "Equals", "Take the true port when the condition matches this value. Omit to route on truthiness instead.")]
1248
+ };
1249
+ const ASSERT = {
1250
+ name: "assert",
1251
+ displayName: "Assert",
1252
+ description: "Fails the step when its value is blank or rejected, so a bad value stops the run instead of reaching a step with a side effect.",
1253
+ requireAuth: false,
1254
+ props: [
1255
+ prop("value", "Value", "The value to check.", { required: true }),
1256
+ prop("rejectValues", "Reject values", "Fail when the value is one of these.", { type: "ARRAY" }),
1257
+ prop("allowValues", "Allow values", "Fail unless the value is one of these.", { type: "ARRAY" }),
1258
+ prop("allowEmpty", "Allow empty", "Treat a blank value as acceptable.", { type: "CHECKBOX" }),
1259
+ prop("message", "Message", "Error message to fail with instead of the default.")
1260
+ ]
1261
+ };
1262
+ const SCHEDULE = {
1263
+ name: "schedule",
1264
+ displayName: "Schedule",
1265
+ description: "Fires on a cron expression or a fixed interval.",
1266
+ strategy: "POLLING",
1267
+ requireAuth: false,
1268
+ hasSampleData: true,
1269
+ props: [prop("cron", "Cron expression", "A cron expression, e.g. 0 * * * *."), prop("everyMs", "Every (ms)", "Fixed interval in milliseconds.", { type: "NUMBER" })]
1270
+ };
1271
+ const CORE_DESCRIPTOR = {
1272
+ id: CORE_PIECE_NAME,
1273
+ source: {
1274
+ packageName: CORE_PIECE_NAME,
1275
+ version: ""
1276
+ },
1277
+ displayName: "Core",
1278
+ description: "The engine's own blocks: branching, assertions, and the triggers that belong to no service.",
1279
+ logoUrl: "",
1280
+ categories: ["CORE"],
1281
+ actions: [BRANCH, ASSERT],
1282
+ triggers: [
1283
+ SCHEDULE,
1284
+ {
1285
+ name: "webhook",
1286
+ displayName: "Webhook",
1287
+ description: "Fires on an HTTP delivery to the workflow's endpoint. Ask for the URL with the webhookEndpoint query rather than constructing it.",
1288
+ strategy: "WEBHOOK",
1289
+ requireAuth: false,
1290
+ hasSampleData: true,
1291
+ props: []
1292
+ },
1293
+ {
1294
+ name: "manual",
1295
+ displayName: "Manual",
1296
+ description: "Fires only when something asks it to, with the fire mutation. The trigger to use for a workflow driven by a test or a script.",
1297
+ strategy: "MANUAL",
1298
+ requireAuth: false,
1299
+ hasSampleData: false,
1300
+ props: []
1301
+ }
1302
+ ]
1303
+ };
1304
+ function isCoreBlock(blockType) {
1305
+ return blockType.startsWith(`${CORE_PIECE_NAME}#`);
1306
+ }
1307
+ function coreBlockDescriptor(blockType) {
1308
+ const fragment = blockType.slice(5);
1309
+ const common = {
1310
+ displayName: CORE_DESCRIPTOR.displayName,
1311
+ logoUrl: CORE_DESCRIPTOR.logoUrl,
1312
+ auth: null
1313
+ };
1314
+ if (fragment.startsWith("trigger:")) {
1315
+ const name = fragment.slice(8);
1316
+ const trigger = CORE_DESCRIPTOR.triggers.find((entry) => entry.name === name);
1317
+ return trigger ? {
1318
+ ...common,
1319
+ trigger
1320
+ } : null;
1321
+ }
1322
+ const action = CORE_DESCRIPTOR.actions.find((entry) => entry.name === fragment);
1323
+ return action ? {
1324
+ ...common,
1325
+ action
1326
+ } : null;
1327
+ }
1328
+ //#endregion
1205
1329
  //#region src/reactor/secret-store.ts
1206
1330
  const IV_BYTES = 12;
1207
1331
  const TAG_BYTES = 16;
@@ -1210,7 +1334,7 @@ async function up$1(db) {
1210
1334
  await db.schema.createTable("secret").addColumn("id", "text", (col) => col.primaryKey()).addColumn("label", "text").addColumn("version", "integer", (col) => col.notNull()).addColumn("enc", "text").addColumn("status", "text", (col) => col.notNull()).addColumn("created_at", "text", (col) => col.notNull()).addColumn("updated_at", "text", (col) => col.notNull()).ifNotExists().execute();
1211
1335
  }
1212
1336
  function loadKey(options) {
1213
- const hex = options.masterKeyHex ?? process.env.PH_SECRETS_MASTER_KEY;
1337
+ const hex = options.masterKeyHex ?? process.env.PH_WORKFLOWS_SECRETS_MASTER_KEY;
1214
1338
  if (hex !== void 0) {
1215
1339
  if (!/^[0-9a-f]{64}$/i.test(hex)) throw new Error("Secrets master key must be 64 hex chars (32 bytes)");
1216
1340
  return Buffer.from(hex, "hex");
@@ -1874,6 +1998,37 @@ var TriggerSupervisor = class {
1874
1998
  this.enableRetries.delete(workflowId);
1875
1999
  return this.enqueue(() => this.disable(workflowId, binding));
1876
2000
  }
2001
+ reject(workflowId, blockType, config, message, retryAt) {
2002
+ this.bindings.delete(workflowId);
2003
+ this.enabledOk.delete(workflowId);
2004
+ this.enableRetries.delete(workflowId);
2005
+ return this.enqueue(() => this.recordRejection(workflowId, blockType, config, message, retryAt));
2006
+ }
2007
+ async recordRejection(workflowId, blockType, config, message, retryAt) {
2008
+ const store = await this.options.store();
2009
+ if (!store) return;
2010
+ const hash = configHash(blockType, config);
2011
+ const existing = await store.getTriggerState(workflowId);
2012
+ if (existing?.status === "ENABLED" && existing.config_hash === hash) {
2013
+ logger$1.warn(`Workflow ${workflowId} could not be resolved, and its trigger row is left as it stands: a registration from before this reactor started is presumed live, and releasing it needs the binding that would not resolve. ${message}`);
2014
+ return;
2015
+ }
2016
+ await store.upsertTriggerState({
2017
+ workflow_id: workflowId,
2018
+ block_type: blockType,
2019
+ config_hash: hash,
2020
+ status: "ERROR",
2021
+ store_state: VESTIGIAL_STORE_STATE,
2022
+ interval_ms: this.defaultIntervalMs,
2023
+ next_poll_at: retryAt?.toISOString() ?? null,
2024
+ last_poll_at: existing?.last_poll_at ?? null,
2025
+ last_error: message,
2026
+ consecutive_failures: (existing?.consecutive_failures ?? 0) + 1,
2027
+ lease_owner: null,
2028
+ lease_expires_at: null,
2029
+ updated_at: this.now().toISOString()
2030
+ });
2031
+ }
1877
2032
  test(binding) {
1878
2033
  return this.enqueue(async () => {
1879
2034
  const store = await this.options.store();
@@ -2517,9 +2672,22 @@ const SUPERVISED_KINDS = new Set([
2517
2672
  "schedule",
2518
2673
  PIECE_WEBHOOK_KIND
2519
2674
  ]);
2675
+ const CORE_PACKAGE = "core";
2676
+ function hasCredentials(state) {
2677
+ if ((state.secretRefs ?? []).length > 0) return true;
2678
+ const config = state.config;
2679
+ return typeof config === "object" && config !== null && Object.keys(config).length > 0;
2680
+ }
2681
+ function isAbsentFromCatalog(error) {
2682
+ return error instanceof CatalogStatusError && error.status === 404;
2683
+ }
2684
+ const PIECE_VERSION_MISS_TTL_MS = 5 * 6e4;
2685
+ const PIECE_VERSION_LOOKUP_TIMEOUT_MS = 2e3;
2686
+ const UNREACHABLE_RETRY_MS = 3e4;
2687
+ const UNREACHABLE_RETRY_CAP_MS = 15 * 6e4;
2520
2688
  const UNAUTHORIZED = { status: 401 };
2521
2689
  const JSON_CONTENT_TYPE = "application/json; charset=utf-8";
2522
- const DELIVERY_TIMEOUT_MS = Number(process.env.WORKFLOW_WEBHOOK_TIMEOUT_MS) || 3e4;
2690
+ const DELIVERY_TIMEOUT_MS = Number(process.env.PH_WORKFLOWS_WEBHOOK_TIMEOUT_MS) || 3e4;
2523
2691
  const TIMED_OUT = Symbol("webhook delivery timed out");
2524
2692
  /** Resolves to TIMED_OUT, and never keeps the process alive waiting to. */
2525
2693
  function timeout(ms) {
@@ -2568,6 +2736,9 @@ function configRecord(config) {
2568
2736
  } catch {}
2569
2737
  return {};
2570
2738
  }
2739
+ function runJournalName(stateName, documentName) {
2740
+ return stateName?.trim() ? stateName : documentName ?? "";
2741
+ }
2571
2742
  var WorkflowRuntimeService = class {
2572
2743
  host;
2573
2744
  logger;
@@ -2639,17 +2810,23 @@ var WorkflowRuntimeService = class {
2639
2810
  return await this.endpointCount() > 0;
2640
2811
  }
2641
2812
  async updateRegistration(workflowId, state) {
2813
+ if (this.unarmed.delete(workflowId)) this.dropSupervised(workflowId);
2814
+ this.cancelResolutionRetry(workflowId);
2642
2815
  const trigger = state.status === "ENABLED" ? state.trigger : void 0;
2643
2816
  if (trigger?.blockType === "core#webhook") {
2644
2817
  await this.registerWebhook(workflowId, trigger.config);
2645
2818
  return;
2646
2819
  }
2647
2820
  const kind = trigger ? TRIGGER_KIND_BY_BLOCK[trigger.blockType] : void 0;
2648
- const supervised = trigger && !kind ? this.supervisedBinding(workflowId, trigger) : void 0;
2821
+ const { binding: supervised, resolution } = trigger && !kind ? await this.supervisedBinding(workflowId, trigger) : {
2822
+ binding: void 0,
2823
+ resolution: void 0
2824
+ };
2649
2825
  if (!kind && !supervised) {
2650
2826
  const had = this.registry.get(workflowId);
2651
2827
  this.registry.delete(workflowId);
2652
2828
  if (had && SUPERVISED_KINDS.has(had.kind)) this.dropSupervised(workflowId);
2829
+ if (trigger) this.reportUnarmedTrigger(workflowId, trigger, resolution);
2653
2830
  return;
2654
2831
  }
2655
2832
  if (supervised) {
@@ -2730,29 +2907,94 @@ var WorkflowRuntimeService = class {
2730
2907
  });
2731
2908
  await (await this.endpoints())?.endpointFor(workflowId);
2732
2909
  }
2733
- supervisedBinding(workflowId, trigger) {
2734
- if (trigger.blockType === "core#schedule") return {
2910
+ async supervisedBinding(workflowId, trigger) {
2911
+ if (trigger.blockType === "core#schedule") return { binding: {
2735
2912
  kind: "schedule",
2736
2913
  workflowId,
2737
2914
  blockType: SCHEDULE_BLOCK,
2738
2915
  config: configRecord(trigger.config)
2739
- };
2916
+ } };
2740
2917
  return this.pieceBinding(workflowId, trigger);
2741
2918
  }
2742
- pieceBinding(workflowId, trigger) {
2743
- const parsed = parseBlockType(trigger.blockType, packagePieces.versions());
2744
- if (!parsed || parsed.kind !== "trigger") return void 0;
2919
+ async pieceBinding(workflowId, trigger) {
2920
+ const resolution = await this.resolveBlockType(trigger.blockType, `workflow ${workflowId}`, { timeoutMs: PIECE_VERSION_LOOKUP_TIMEOUT_MS });
2921
+ const parsed = resolution.kind === "resolved" ? resolution.block : void 0;
2922
+ if (parsed?.kind !== "trigger") return { resolution };
2745
2923
  const { config, pollIntervalMs } = splitPollInterval(configRecord(trigger.config));
2746
2924
  return {
2747
- workflowId,
2748
- blockType: trigger.blockType,
2749
- packageName: parsed.packageName,
2750
- version: parsed.version,
2751
- triggerName: parsed.name,
2752
- config,
2753
- connectionId: trigger.connectionId,
2754
- pollIntervalMs
2925
+ resolution,
2926
+ binding: {
2927
+ workflowId,
2928
+ blockType: trigger.blockType,
2929
+ packageName: parsed.packageName,
2930
+ version: parsed.version,
2931
+ triggerName: parsed.name,
2932
+ config,
2933
+ connectionId: trigger.connectionId,
2934
+ pollIntervalMs
2935
+ }
2936
+ };
2937
+ }
2938
+ async resolveBlockType(blockType, caller = "a design-time request", options = {}) {
2939
+ const parsed = parseBlockType(blockType, packagePieces.versions());
2940
+ if (parsed) return {
2941
+ kind: "resolved",
2942
+ block: parsed
2755
2943
  };
2944
+ const parts = blockTypeParts(blockType);
2945
+ if (!parts) return { kind: "absent" };
2946
+ const found = await this.pieceVersion(parts.packageName, options);
2947
+ if (found.kind !== "found") return found;
2948
+ this.logger.info("Resolving @block for @caller: it pins no version and this reactor holds no package piece of that name, so it reads as version @version, the one the piece catalog serves today. Pin a version in the block type to hold it still across upgrades.", blockType, caller, found.version);
2949
+ return {
2950
+ kind: "resolved",
2951
+ block: {
2952
+ packageName: parts.packageName,
2953
+ version: found.version,
2954
+ kind: parts.kind,
2955
+ name: parts.name
2956
+ }
2957
+ };
2958
+ }
2959
+ async resolvedBlock(blockType) {
2960
+ const resolution = await this.resolveBlockType(blockType, void 0, { timeoutMs: PIECE_VERSION_LOOKUP_TIMEOUT_MS });
2961
+ return resolution.kind === "resolved" ? resolution.block : void 0;
2962
+ }
2963
+ unarmed = /* @__PURE__ */ new Set();
2964
+ reportUnarmedTrigger(workflowId, trigger, resolution) {
2965
+ if (blockTypeParts(trigger.blockType)?.kind !== "trigger") return;
2966
+ const unreachable = resolution?.kind === "unreachable";
2967
+ const retryAt = unreachable ? new Date(Date.now() + this.scheduleResolutionRetry(workflowId)) : void 0;
2968
+ const reason = unreachable ? `The piece behind the trigger block type "${trigger.blockType}" could not be resolved, so this workflow is not armed: it pins no version, this reactor holds no package piece of that name, and the piece catalog could not be reached (${resolution.detail}). Retrying at ${retryAt?.toISOString() ?? "the next registration"}; this is a connectivity failure, not a missing piece.` : `No piece answers for the trigger block type "${trigger.blockType}", so this workflow will not arm: it pins no version, this reactor holds no package piece of that name, and the piece catalog has none either. Pin a version in the block type, or install the package that ships the piece.`;
2969
+ this.logger.warn("Workflow @workflow: @reason", workflowId, reason);
2970
+ this.unarmed.add(workflowId);
2971
+ this.supervisor().reject(workflowId, trigger.blockType, configRecord(trigger.config), reason, retryAt).catch((error) => {
2972
+ this.logger.error(`Could not record the unresolved trigger for workflow ${workflowId}`, error);
2973
+ });
2974
+ }
2975
+ resolutionRetries = /* @__PURE__ */ new Map();
2976
+ scheduleResolutionRetry(workflowId) {
2977
+ const previous = this.resolutionRetries.get(workflowId);
2978
+ if (previous) clearTimeout(previous.timer);
2979
+ const delayMs = Math.min(previous ? previous.delayMs * 2 : UNREACHABLE_RETRY_MS, UNREACHABLE_RETRY_CAP_MS);
2980
+ const timer = setTimeout(() => {
2981
+ this.resolutionRetries.delete(workflowId);
2982
+ this.refreshRegistration(workflowId).catch((error) => {
2983
+ this.logger.warn(`Could not retry the unresolved trigger for workflow ${workflowId}`, error);
2984
+ });
2985
+ }, delayMs);
2986
+ timer.unref();
2987
+ this.resolutionRetries.set(workflowId, {
2988
+ timer,
2989
+ delayMs
2990
+ });
2991
+ return delayMs;
2992
+ }
2993
+ cancelResolutionRetry(workflowId) {
2994
+ const pending = this.resolutionRetries.get(workflowId);
2995
+ if (!pending) return;
2996
+ clearTimeout(pending.timer);
2997
+ this.resolutionRetries.delete(workflowId);
2756
2998
  }
2757
2999
  dropSupervised(workflowId) {
2758
3000
  this.supervisor().remove(workflowId).catch((error) => {
@@ -2963,8 +3205,8 @@ var WorkflowRuntimeService = class {
2963
3205
  cacheDir: BUNDLE_CACHE_DIR,
2964
3206
  resolver: pieceResolver(),
2965
3207
  egress: configuredEgress(),
2966
- defaultIntervalMs: Number(process.env.WORKFLOW_POLL_INTERVAL_MS) || void 0,
2967
- reconcileIntervalMs: Number(process.env.WORKFLOW_WEBHOOK_RECONCILE_MS) || void 0
3208
+ defaultIntervalMs: Number(process.env.PH_WORKFLOWS_POLL_INTERVAL_MS) || void 0,
3209
+ reconcileIntervalMs: Number(process.env.PH_WORKFLOWS_WEBHOOK_RECONCILE_MS) || void 0
2968
3210
  });
2969
3211
  return this.triggerSupervisor;
2970
3212
  }
@@ -2975,6 +3217,8 @@ var WorkflowRuntimeService = class {
2975
3217
  this.triggerSupervisor?.stop();
2976
3218
  }
2977
3219
  shutdown() {
3220
+ for (const { timer } of this.resolutionRetries.values()) clearTimeout(timer);
3221
+ this.resolutionRetries.clear();
2978
3222
  this.stopTriggerSupervisor();
2979
3223
  this.pieceWorkers?.dispose();
2980
3224
  this.designWorker?.dispose();
@@ -3248,7 +3492,7 @@ var WorkflowRuntimeService = class {
3248
3492
  detail: "Connection is revoked",
3249
3493
  accountLabel
3250
3494
  };
3251
- if (state.status === "UNCONFIGURED") return this.recordCheckResult(document, {
3495
+ if (state.authType !== "NONE" && !hasCredentials(state)) return this.recordCheckResult(document, {
3252
3496
  ok: false,
3253
3497
  detail: "Connection is not configured",
3254
3498
  accountLabel
@@ -3261,8 +3505,9 @@ var WorkflowRuntimeService = class {
3261
3505
  const packageName = packageFromConnectorId(state.connectorId);
3262
3506
  let moduleRef;
3263
3507
  try {
3264
- const version = await this.pieceVersion(packageName);
3265
- moduleRef = pieceModuleRef(await pieceResolver().resolve(packageName, version));
3508
+ const found = await this.pieceVersion(packageName, { fresh: true });
3509
+ if (found.kind !== "found") throw new Error(`Could not resolve a version for piece "${packageName}"` + (found.kind === "unreachable" ? `: ${found.detail}` : ""));
3510
+ moduleRef = pieceModuleRef(await pieceResolver().resolve(packageName, found.version));
3266
3511
  } catch (error) {
3267
3512
  return this.recordCheckResult(document, {
3268
3513
  ok: false,
@@ -3305,7 +3550,7 @@ var WorkflowRuntimeService = class {
3305
3550
  });
3306
3551
  if (outcome.result === false) return this.recordCheckResult(document, {
3307
3552
  ok: false,
3308
- detail: "Connection check failed",
3553
+ detail: outcome.detail ?? "Connection check failed",
3309
3554
  accountLabel
3310
3555
  });
3311
3556
  return this.recordCheckResult(document, {
@@ -3314,16 +3559,77 @@ var WorkflowRuntimeService = class {
3314
3559
  accountLabel: accountLabelFromCheckResult(outcome.result) ?? accountLabel
3315
3560
  });
3316
3561
  }
3317
- async pieceVersion(packageName) {
3562
+ versionMisses = /* @__PURE__ */ new Map();
3563
+ versionLookups = /* @__PURE__ */ new Map();
3564
+ pieceVersion(packageName, options = {}) {
3318
3565
  const local = packagePieces.lookup(packageName);
3319
- if (local) return local.version;
3566
+ if (local) return Promise.resolve({
3567
+ kind: "found",
3568
+ version: local.version
3569
+ });
3570
+ if (packageName === CORE_PACKAGE) return Promise.resolve({ kind: "absent" });
3571
+ const missedAt = this.versionMisses.get(packageName);
3572
+ if (!options.fresh && missedAt !== void 0 && Date.now() - missedAt < PIECE_VERSION_MISS_TTL_MS) return Promise.resolve({ kind: "absent" });
3573
+ if (options.fresh) this.versionMisses.delete(packageName);
3574
+ const lookup = this.versionLookups.get(packageName) ?? this.startVersionLookup(packageName);
3575
+ return options.timeoutMs === void 0 ? lookup : this.boundedLookup(packageName, lookup, options.timeoutMs);
3576
+ }
3577
+ startVersionLookup(packageName) {
3578
+ const lookup = this.lookUpPieceVersion(packageName).then((found) => {
3579
+ if (found.kind === "absent") this.versionMisses.set(packageName, Date.now());
3580
+ else if (found.kind === "found") this.versionMisses.delete(packageName);
3581
+ this.versionLookups.delete(packageName);
3582
+ return found;
3583
+ });
3584
+ this.versionLookups.set(packageName, lookup);
3585
+ return lookup;
3586
+ }
3587
+ boundedLookup(packageName, lookup, timeoutMs) {
3588
+ return new Promise((resolve) => {
3589
+ const timer = setTimeout(() => {
3590
+ this.logger.debug("Gave the piece catalog @ms ms for @package and went on without it", timeoutMs, packageName);
3591
+ resolve({
3592
+ kind: "unreachable",
3593
+ detail: `the piece catalog did not answer within ${timeoutMs}ms`
3594
+ });
3595
+ }, timeoutMs);
3596
+ timer.unref();
3597
+ lookup.then((found) => {
3598
+ clearTimeout(timer);
3599
+ resolve(found);
3600
+ }, () => {
3601
+ clearTimeout(timer);
3602
+ resolve({
3603
+ kind: "unreachable",
3604
+ detail: "the piece catalog failed"
3605
+ });
3606
+ });
3607
+ });
3608
+ }
3609
+ async lookUpPieceVersion(packageName) {
3320
3610
  try {
3321
3611
  const version = (await fetchPieceCatalog()).find((entry) => entry.name === packageName)?.version;
3322
- if (version) return version;
3612
+ if (version) return {
3613
+ kind: "found",
3614
+ version
3615
+ };
3323
3616
  } catch {}
3324
- const detail = await fetchPieceDetail(packageName);
3325
- if (typeof detail.version === "string" && detail.version !== "") return detail.version;
3326
- throw new Error(`Could not resolve a version for piece "${packageName}"`);
3617
+ try {
3618
+ const detail = await fetchPieceDetail(packageName);
3619
+ if (typeof detail.version === "string" && detail.version !== "") return {
3620
+ kind: "found",
3621
+ version: detail.version
3622
+ };
3623
+ return { kind: "absent" };
3624
+ } catch (error) {
3625
+ if (isAbsentFromCatalog(error)) return { kind: "absent" };
3626
+ const detail = error instanceof Error ? error.message : String(error);
3627
+ this.logger.debug("The piece catalog could not be reached for @package: @error", packageName, error);
3628
+ return {
3629
+ kind: "unreachable",
3630
+ detail
3631
+ };
3632
+ }
3327
3633
  }
3328
3634
  async recordCheckResult(document, result) {
3329
3635
  const action = actions.recordCheckResult({
@@ -3366,20 +3672,27 @@ var WorkflowRuntimeService = class {
3366
3672
  this.logger.warn(`Serving package pieces only: ${String(error)}`);
3367
3673
  published = [];
3368
3674
  }
3369
- return [...entries, ...published.filter((entry) => !names.has(entry.name))].sort((a, b) => a.displayName.localeCompare(b.displayName));
3675
+ return [
3676
+ catalogEntry(CORE_DESCRIPTOR, CORE_PIECE_NAME, ""),
3677
+ ...entries,
3678
+ ...published.filter((entry) => !names.has(entry.name))
3679
+ ].sort((a, b) => a.displayName.localeCompare(b.displayName));
3370
3680
  }
3371
3681
  async pieceActions(packageName) {
3682
+ if (packageName === "core") return actionsResult(CORE_DESCRIPTOR, CORE_PIECE_NAME, "");
3372
3683
  const local = await this.localPiece(packageName);
3373
3684
  return local ? actionsResult(local.descriptor, local.piece.name, local.piece.version) : fetchPieceActions(packageName);
3374
3685
  }
3375
3686
  async pieceTriggers(packageName) {
3687
+ if (packageName === "core") return triggersResult(CORE_DESCRIPTOR, CORE_PIECE_NAME, "");
3376
3688
  const local = await this.localPiece(packageName);
3377
3689
  return local ? triggersResult(local.descriptor, local.piece.name, local.piece.version) : fetchPieceTriggers(packageName);
3378
3690
  }
3379
3691
  async searchBlocks(query, limit) {
3380
- let local;
3692
+ const core = localSearchHits(CORE_DESCRIPTOR, CORE_PIECE_NAME);
3693
+ let local = indexFromHits(core);
3381
3694
  try {
3382
- local = indexFromHits((await this.localPieces()).flatMap(({ piece, descriptor }) => localSearchHits(descriptor, piece.name)));
3695
+ local = indexFromHits([...core, ...(await this.localPieces()).flatMap(({ piece, descriptor }) => localSearchHits(descriptor, piece.name))]);
3383
3696
  } catch (error) {
3384
3697
  this.logger.warn(`Could not index the package pieces: ${String(error)}`);
3385
3698
  }
@@ -3390,7 +3703,8 @@ var WorkflowRuntimeService = class {
3390
3703
  return local ? detailResult(local.descriptor, local.piece.name, local.piece.version) : fetchPieceDetail(packageName);
3391
3704
  }
3392
3705
  async blockDescriptor(blockType) {
3393
- const parsed = parseBlockType(blockType, packagePieces.versions());
3706
+ if (isCoreBlock(blockType)) return coreBlockDescriptor(blockType);
3707
+ const parsed = await this.resolvedBlock(blockType);
3394
3708
  if (!parsed) return null;
3395
3709
  const descriptor = await this.pieceDescriptor(parsed.packageName, parsed.version);
3396
3710
  const common = {
@@ -3434,7 +3748,7 @@ var WorkflowRuntimeService = class {
3434
3748
  await this.host.assertCanWrite(documentId, ctx);
3435
3749
  }
3436
3750
  async blockOptions(blockType, propName, input, connectionId, ctx) {
3437
- const parsed = parseBlockType(blockType, packagePieces.versions());
3751
+ const parsed = await this.resolvedBlock(blockType);
3438
3752
  if (!parsed) throw new Error(`Not a piece block type: "${blockType}"`);
3439
3753
  let auth;
3440
3754
  if (connectionId) {
@@ -3453,9 +3767,9 @@ var WorkflowRuntimeService = class {
3453
3767
  propName,
3454
3768
  refresherValues: input ?? {},
3455
3769
  auth,
3456
- ...piece.local ? { reactorAccess: true } : {},
3770
+ ...servesReactorPort(parsed.packageName) ? { reactorAccess: true } : {},
3457
3771
  ...this.designEgress ? { egress: this.designEgress } : {}
3458
- }, piece.local ? { hostCalls: reactorHandlers(new ScopedDesignTimeReactorPort(this.host, ctx)) } : {})).output;
3772
+ }, servesReactorPort(parsed.packageName) ? { hostCalls: reactorHandlers(new ScopedDesignTimeReactorPort(this.host, ctx)) } : {})).output;
3459
3773
  }
3460
3774
  async blockOutputTree(blockType, config) {
3461
3775
  const record = config ?? {};
@@ -3526,7 +3840,7 @@ var WorkflowRuntimeService = class {
3526
3840
  };
3527
3841
  }
3528
3842
  default: {
3529
- const parsed = parseBlockType(blockType, packagePieces.versions());
3843
+ const parsed = await this.resolvedBlock(blockType);
3530
3844
  if (!parsed) return {
3531
3845
  source: "none",
3532
3846
  nodes: []
@@ -3582,25 +3896,27 @@ var WorkflowRuntimeService = class {
3582
3896
  const trigger = (await this.host.reactorClient.get(workflowId)).state.global.trigger;
3583
3897
  if (!trigger) throw new Error("Workflow has no trigger");
3584
3898
  if (trigger.connectionId) await this.assertCanReadDocument(trigger.connectionId, ctx);
3585
- const binding = this.pieceBinding(workflowId, trigger);
3899
+ const { binding } = await this.pieceBinding(workflowId, trigger);
3586
3900
  if (!binding) throw new Error(`"${trigger.blockType}" is not a piece trigger`);
3587
3901
  return this.supervisor().test(binding);
3588
3902
  }
3589
3903
  workers() {
3590
3904
  return this.pieceWorkers ??= new PieceWorkerPool({
3591
- size: Number(process.env.WORKFLOW_RUN_CONCURRENCY) || void 0,
3592
- maxQueueDepth: Number(process.env.WORKFLOW_RUN_QUEUE_DEPTH) || void 0
3905
+ size: Number(process.env.PH_WORKFLOWS_RUN_CONCURRENCY) || void 0,
3906
+ maxQueueDepth: Number(process.env.PH_WORKFLOWS_RUN_QUEUE_DEPTH) || void 0
3593
3907
  });
3594
3908
  }
3595
3909
  async fire(workflowId, triggerPayload, triggerKind = "manual", resume, ctx, enqueuedRunId) {
3596
3910
  const store = await this.store();
3597
3911
  let state;
3912
+ let documentName;
3598
3913
  let definition;
3599
3914
  try {
3600
3915
  if (triggerKind === "manual") await this.assertCanReadDocument(workflowId, ctx);
3601
3916
  const document = await this.host.reactorClient.get(workflowId);
3602
3917
  if (document.header.documentType !== "powerhouse/workflow") throw new Error(`Document "${workflowId}" is not a powerhouse/workflow`);
3603
3918
  state = document.state.global;
3919
+ documentName = document.header.name;
3604
3920
  if (state.status !== "ENABLED") throw new Error(`Workflow is ${state.status}; only ENABLED workflows can fire`);
3605
3921
  definition = toWorkflowDefinition(state);
3606
3922
  } catch (error) {
@@ -3608,15 +3924,18 @@ var WorkflowRuntimeService = class {
3608
3924
  throw error;
3609
3925
  }
3610
3926
  const connections = declaredConnectionIds(definition);
3611
- this.executor ??= createBlockExecutor(this.host, this.secretProvider(), this.attachments, store ? createPieceStorePort(store, currentWorkflowId) : void 0);
3927
+ this.executor ??= createBlockExecutor(this.host, this.secretProvider(), this.attachments, store ? createPieceStorePort(store, currentWorkflowId) : void 0, async (stepBlockType) => {
3928
+ const resolution = await this.resolveBlockType(stepBlockType, `a step of workflow ${currentWorkflowId() ?? "?"}`);
3929
+ return resolution.kind === "resolved" ? resolution.block : void 0;
3930
+ });
3612
3931
  let runId = enqueuedRunId ?? null;
3613
3932
  if (enqueuedRunId) await store?.beginRun(enqueuedRunId, {
3614
- workflowName: state.name,
3933
+ workflowName: runJournalName(state.name, documentName),
3615
3934
  workflowVersion: state.version
3616
3935
  });
3617
3936
  else runId = await store?.startRun({
3618
3937
  workflowId,
3619
- workflowName: state.name,
3938
+ workflowName: runJournalName(state.name, documentName),
3620
3939
  workflowVersion: state.version,
3621
3940
  triggerKind,
3622
3941
  triggerPayload,