@powerhousedao/reactor-workflow 6.2.3-dev.44 → 6.2.3-dev.46

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,24 +1,25 @@
1
- import { G as unsupportedTrigger, H as UnsupportedPieceFeatureError, S as maxFileBytes, U as authMethodFor, W as unsupportedAuth, a as redactMessage, c as DEFAULT_EGRESS_POLICY, d as parseAddress, m as extractDedupeKey, n as containsRedactedMarker, o as rememberSecrets, r as redact, s as secretsFor, u as isPrivateAddress, y as FileTooLargeError } from "./redact-BlKAG3f0.js";
2
- import { A as resolveStepInput, B as PieceWorker, C as describeBuiltinPiece, E as BoundConnectionResolver, F as parseSecretRef, G as sourcedResolver, H as PieceWorkerTimeoutError, I as secretRefFromId, J as npmRegistryBaseUrl, L as stepBlock, N as SecretDeletedError, O as declaredConnectionIds, P as SecretNotFoundError, R as triggerBlock, S as builtinPiece, T as CORE_PIECE_VERSION, U as bundleResolver, V as PieceWorkerError, W as pieceModuleRef, X as setPieceRegistryUrl, Y as pieceRegistrySource, _ as servesReactorPort, a as runWorkflow, b as unpinnedNote, c as stepConfigHash, d as ActivepiecesBlockExecutor, f as CompositeBlockExecutor, g as resolvedBlock, h as reactorHandlers, i as packagePieces, j as expressionsIn, k as shapeConnection, l as DynamicPropertiesError, m as isHostBound, n as installedPiece, o as canonicalJson, p as REACTOR_PORT_PIECE, r as installedPieces, s as hashOf, t as PieceRegistry, u as checkDynamicProperties, v as storeHandlers, w as CORE_PIECE_NAME, x as blockPorts, y as blockLabel, z as PieceWorkerPool } from "./piece-registry-DMhdxKrs.js";
3
- import { WebhookHandshakeStrategy } from "@powerhousedao/pieces-framework";
1
+ import { B as UnsupportedPieceFeatureError, H as unsupportedAuth, M as maxFileBytes, U as unsupportedTrigger, V as authMethodFor, a as redact, c as rememberSecrets, f as isPrivateAddress, i as containsRedactedMarker, k as FileTooLargeError, l as secretsFor, p as parseAddress, s as redactMessage, u as DEFAULT_EGRESS_POLICY, w as extractDedupeKey } from "./reactor-rpc-BqAjCK1p.js";
2
+ import { A as expressionsIn, B as PieceWorkerError, C as CORE_PIECE_VERSION, D as declaredReactorConnectionIds, E as declaredConnectionIds, F as secretRefFromId, H as bundleResolver, I as stepBlock, J as pieceRegistrySource, L as triggerBlock, M as SecretDeletedError, N as SecretNotFoundError, O as shapeConnection, P as parseSecretRef, R as PieceWorkerPool, S as CORE_PIECE_NAME, U as pieceModuleRef, V as PieceWorkerTimeoutError, W as sourcedResolver, Y as setPieceRegistryUrl, _ as blockLabel, a as errorNameOf, b as builtinPiece, c as hashOf, d as checkDynamicProperties, f as ActivepiecesBlockExecutor, g as storeHandlers, h as resolvedBlock, i as packagePieces, k as resolveStepInput, l as stepConfigHash, m as isHostBound, n as installedPiece, o as runWorkflow, p as CompositeBlockExecutor, q as npmRegistryBaseUrl, r as installedPieces, s as canonicalJson, t as PieceRegistry, u as DynamicPropertiesError, v as unpinnedNote, w as BoundConnectionResolver, x as describeBuiltinPiece, y as blockPorts, z as PieceWorker } from "./piece-registry-BElVYTHd.js";
3
+ import { ReactorAccessDeniedError, ReactorAccessDeniedError as ReactorAccessDeniedError$1, ReactorActionsFailedError as ReactorActionsFailedError$1, ReactorJobFailedError as ReactorJobFailedError$1, ReactorJobPendingError as ReactorJobPendingError$1, WebhookHandshakeStrategy } from "@powerhousedao/pieces-framework";
4
4
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { open, readFile, rm } from "node:fs/promises";
6
6
  import { dirname, join } from "node:path";
7
- import { childLogger, createAction as createAction$1, generateId, withSignaturePolicy } from "document-model";
8
- import { DEFAULT_TIMEZONE, ScheduleConfigError, checkTriggerStrategy, parseScheduleConfig } from "@powerhousedao/pieces-framework/workflow";
7
+ import { childLogger, generateId } from "document-model";
8
+ import { DEFAULT_TIMEZONE, DOCUMENT_REF_KEY, ScheduleConfigError, checkTriggerStrategy, containsDocumentRef, documentRefsIn, expandDocumentRefs, isDocumentRefMarker, parseScheduleConfig, referenceDocuments } from "@powerhousedao/pieces-framework/workflow";
9
9
  import { Cron } from "croner";
10
10
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
11
11
  import dns from "node:dns";
12
12
  import net from "node:net";
13
13
  import { AsyncLocalStorage } from "node:async_hooks";
14
14
  import { blockKey, compareVersions, isExactVersion, rankClosestVersions } from "@powerhousedao/pieces-framework/block-type";
15
- import { actions } from "@powerhousedao/workflow/document-models/connection";
15
+ import { actions, isReactorConnectorId, parseReactorConnectionConfig } from "@powerhousedao/workflow/document-models/connection";
16
16
  import http from "node:http";
17
17
  import https from "node:https";
18
18
  import { actions as actions$1 } from "@powerhousedao/workflow/document-models/workflow";
19
19
  import { Kind, parse } from "graphql";
20
- import { BaseReadModel, JobStatus, defaultReadModelIndexingConfig, isPurgeMarker } from "@powerhousedao/reactor";
21
- import { addFile } from "@powerhousedao/shared/document-drive";
20
+ import { ReactorHostServer } from "@powerhousedao/reactor/rpc";
21
+ import { BaseReadModel, JobStatus, PropagationMode, defaultReadModelIndexingConfig, deleteDocumentAction, isPurgeMarker } from "@powerhousedao/reactor";
22
+ import { DOCUMENT_SCOPE_ACTION_TYPES, initializeAuth, normalizeDocumentModelVersion, withSignaturePolicy } from "@powerhousedao/shared/document-model";
22
23
  //#region src/pieces/activepieces/piece-versions.ts
23
24
  const LISTED_TTL_MS = 3e5;
24
25
  const ABSENT_TTL_MS = 3e4;
@@ -479,7 +480,7 @@ var StoreTokenRefresher = class {
479
480
  };
480
481
  //#endregion
481
482
  //#region src/reactor/reactor-piece.ts
482
- const REACTOR_PIECE = REACTOR_PORT_PIECE;
483
+ const REACTOR_PIECE = "@powerhousedao/piece-reactor";
483
484
  function action$1(name) {
484
485
  return blockKey({
485
486
  pieceName: REACTOR_PIECE,
@@ -611,17 +612,19 @@ function hasOutputSchemaFields(schema) {
611
612
  const fields = schema?.fields;
612
613
  return Array.isArray(fields) && fields.length > 0;
613
614
  }
614
- function fromSample(value, depth = 0) {
615
+ function fromSample(value, depth = 0, documentNodes) {
615
616
  if (value === null || typeof value !== "object" || depth > MAX_DEPTH) return [];
616
- return (Array.isArray(value) ? value.slice(0, 1).map((item) => ["0", item]) : Object.entries(value)).map(([name, child]) => {
617
+ const marker = documentNodes && isDocumentRefMarker(value) ? value[DOCUMENT_REF_KEY] : void 0;
618
+ const nodes = (Array.isArray(value) ? value.slice(0, 1).map((item) => ["0", item]) : Object.entries(value).filter(([name]) => !marker || name !== DOCUMENT_REF_KEY)).map(([name, child]) => {
617
619
  const kind = Array.isArray(child) ? "array" : child === null ? "null" : typeof child;
618
- const children = fromSample(child, depth + 1);
620
+ const children = fromSample(child, depth + 1, documentNodes);
619
621
  return {
620
622
  name,
621
623
  type: kind,
622
624
  ...children.length > 0 ? { children } : {}
623
625
  };
624
626
  });
627
+ return marker && documentNodes ? [...documentNodes(marker), ...nodes] : nodes;
625
628
  }
626
629
  const leaf = (name, type, description) => ({
627
630
  name,
@@ -633,42 +636,51 @@ const OPERATION_NODE = {
633
636
  type: "object",
634
637
  children: [leaf("index", "Int!"), leaf("timestampUtcMs", "String!")]
635
638
  };
636
- function documentBlockTree(stateChildren) {
637
- return [
638
- leaf("documentId", "PHID!"),
639
- leaf("documentType", "String!"),
640
- leaf("name", "String"),
641
- {
642
- name: "state",
643
- type: "object",
644
- description: "Document global state after the actions applied",
645
- ...stateChildren.length > 0 ? { children: stateChildren } : {}
646
- }
647
- ];
639
+ function documentHeaderNode() {
640
+ return {
641
+ name: "header",
642
+ type: "object",
643
+ children: [
644
+ leaf("id", "PHID!"),
645
+ leaf("documentType", "String!"),
646
+ leaf("name", "String"),
647
+ leaf("slug", "String"),
648
+ leaf("branch", "String!"),
649
+ leaf("revision", "JSONObject!", "Operation count per scope"),
650
+ leaf("createdAtUtcIso", "DateTime!"),
651
+ leaf("lastModifiedAtUtcIso", "DateTime!")
652
+ ]
653
+ };
648
654
  }
649
- function documentGetTree(stateChildren) {
650
- return [
651
- ...documentBlockTree(stateChildren).filter((node) => node.name !== "state"),
652
- leaf("slug", "String"),
653
- {
654
- name: "state",
655
+ function documentTree(globalChildren) {
656
+ return [documentHeaderNode(), {
657
+ name: "state",
658
+ type: "object",
659
+ children: [{
660
+ name: "global",
655
661
  type: "object",
656
662
  description: "Document global state as read",
657
- ...stateChildren.length > 0 ? { children: stateChildren } : {}
658
- }
663
+ ...globalChildren.length > 0 ? { children: globalChildren } : {}
664
+ }]
665
+ }];
666
+ }
667
+ function documentReferenceTree() {
668
+ return [
669
+ leaf("documentId", "PHID!"),
670
+ leaf("documentType", "String!"),
671
+ leaf("branch", "String!"),
672
+ leaf("revision", "JSONObject!", "Operation count per scope after the write")
659
673
  ];
660
674
  }
661
675
  function documentFindTree() {
662
- return [leaf("count", "Int!"), {
663
- name: "documents",
676
+ return [{
677
+ name: "results",
664
678
  type: "array",
665
- children: [
666
- leaf("documentId", "PHID!"),
667
- leaf("documentType", "String!"),
668
- leaf("name", "String"),
669
- leaf("slug", "String")
670
- ]
671
- }];
679
+ children: [documentHeaderNode(), leaf("state", "JSONObject", "With Include state only")]
680
+ }, leaf("nextCursor", "String", "Present while more documents match")];
681
+ }
682
+ function treeValue(nodes) {
683
+ return Object.fromEntries(nodes.map((node) => [node.name, node.children ? treeValue(node.children) : node.type]));
672
684
  }
673
685
  function documentTypesTree() {
674
686
  return [leaf("count", "Int!"), {
@@ -1038,6 +1050,7 @@ function detailResult(descriptor, pieceName, version) {
1038
1050
  description: action.description ?? "",
1039
1051
  props: action.props,
1040
1052
  requireAuth: action.requireAuth,
1053
+ ...action.requireReactor ? { requireReactor: action.requireReactor } : {},
1041
1054
  outputSchema: action.outputSchema,
1042
1055
  audience: action.audience
1043
1056
  }])),
@@ -1048,6 +1061,7 @@ function detailResult(descriptor, pieceName, version) {
1048
1061
  type: trigger.strategy,
1049
1062
  props: trigger.props,
1050
1063
  requireAuth: trigger.requireAuth,
1064
+ ...trigger.requireReactor ? { requireReactor: trigger.requireReactor } : {},
1051
1065
  outputSchema: trigger.outputSchema,
1052
1066
  sampleData: trigger.sampleData,
1053
1067
  testStrategy: trigger.testStrategy,
@@ -1352,250 +1366,9 @@ function currentPieceWorker() {
1352
1366
  function currentStepTest() {
1353
1367
  return storage.getStore()?.stepTest ?? false;
1354
1368
  }
1355
- //#endregion
1356
- //#region src/reactor/reactor-port.ts
1357
- const DRIVE_DOCUMENT_TYPES = /* @__PURE__ */ new Set(["powerhouse/document-drive", "powerhouse/reactor-drive"]);
1358
- const FIND_PAGE_LIMIT = 100;
1359
- const DESIGN_TIME_WRITES_REFUSED = "Reactor writes are not available while resolving design-time options";
1360
- const DESIGN_TIME_CALLER_REQUIRED = "Design-time reactor access requires an authenticated request";
1361
- const BASE_ACTIONS = [{
1362
- type: "SET_NAME",
1363
- module: "base",
1364
- inputSchema: "input SetNameInput {\n name: String!\n}"
1365
- }];
1366
- function stateValueAt(document, path) {
1367
- let current = document.state.global;
1368
- for (const segment of path.split(".")) {
1369
- if (typeof current !== "object" || current === null) return void 0;
1370
- current = current[segment];
1371
- }
1372
- return current;
1373
- }
1374
- function matchesState(document, match) {
1375
- if (!match) return true;
1376
- const value = stateValueAt(document, match.path);
1377
- if (typeof value === "string") return value === match.value;
1378
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value) === match.value;
1379
- return false;
1380
- }
1381
- function documentSummary(document, withState) {
1382
- const globalState = document.state.global;
1383
- const stateName = globalState && typeof globalState === "object" ? globalState.name : void 0;
1384
- return {
1385
- documentId: document.header.id,
1386
- documentType: document.header.documentType,
1387
- name: typeof stateName === "string" && stateName || document.header.name || "",
1388
- slug: document.header.slug,
1389
- ...withState ? { state: globalState } : {}
1390
- };
1391
- }
1392
- const JOB_NOT_FOUND = "Job not found";
1393
- function jobState(job) {
1394
- if (job.status === JobStatus.FAILED && job.error?.message === JOB_NOT_FOUND) return {
1395
- jobId: job.id,
1396
- status: "UNKNOWN"
1397
- };
1398
- return {
1399
- jobId: job.id,
1400
- status: job.status,
1401
- ...job.error ? { error: job.error.message } : {},
1402
- ...job.result ? { actions: job.result.actions.map((action) => ({
1403
- actionId: action.actionId,
1404
- kind: action.kind,
1405
- ...action.kind === "reducer-error" ? { message: action.message } : {},
1406
- ...action.kind === "denied" ? { reason: action.reason } : {}
1407
- })) } : {}
1408
- };
1409
- }
1410
- function jobIds(jobs) {
1411
- return Object.entries(jobs).sort(([a], [b]) => Number(b === "create") - Number(a === "create")).map(([, job]) => job.id);
1369
+ function currentRunUser() {
1370
+ return storage.getStore()?.runUser;
1412
1371
  }
1413
- function buildActions(input) {
1414
- return input.actions.map((entry) => createAction$1(entry.type, entry.input, void 0, void 0, entry.scope ?? "global"));
1415
- }
1416
- var SubgraphReactorPort = class {
1417
- host;
1418
- constructor(host) {
1419
- this.host = host;
1420
- }
1421
- get client() {
1422
- return this.host.reactorClient;
1423
- }
1424
- async models() {
1425
- return (await this.client.getDocumentModelModules()).results.map((module) => module.documentModel.global).map((model) => ({
1426
- documentType: model.id,
1427
- name: model.name
1428
- })).filter((entry) => entry.documentType).sort((a, b) => a.documentType.localeCompare(b.documentType));
1429
- }
1430
- async model(documentType) {
1431
- const model = (await this.client.getDocumentModelModule(documentType)).documentModel.global;
1432
- const latest = model.specifications.at(-1);
1433
- return {
1434
- documentType,
1435
- name: model.name,
1436
- stateSchema: latest?.state.global.schema ?? null,
1437
- actions: [...(latest?.modules ?? []).flatMap((specModule) => specModule.operations.flatMap((operation) => operation.name ? [{
1438
- type: operation.name,
1439
- module: specModule.name,
1440
- inputSchema: operation.schema ?? null
1441
- }] : [])), ...BASE_ACTIONS]
1442
- };
1443
- }
1444
- async get(input) {
1445
- const document = await this.client.get(input.documentId, input.branch ? { branch: input.branch } : void 0);
1446
- return this.handOver(documentSummary(document, true));
1447
- }
1448
- async find(input) {
1449
- const limit = input.limit ?? FIND_PAGE_LIMIT;
1450
- let results;
1451
- if (input.documentType) results = await this.findByType(input.documentType, limit, input.parentId);
1452
- else if (input.parentId) results = (await this.client.find({ parentId: input.parentId }, void 0, {
1453
- cursor: "",
1454
- limit
1455
- })).results;
1456
- else {
1457
- const types = (await this.models()).map((model) => model.documentType);
1458
- results = (await Promise.all(types.map((type) => this.findByType(type, limit)))).flat();
1459
- }
1460
- const seen = /* @__PURE__ */ new Set();
1461
- return this.handOver(results.filter((document) => {
1462
- if (seen.has(document.header.id)) return false;
1463
- seen.add(document.header.id);
1464
- return true;
1465
- }).filter((document) => matchesState(document, input.match)).map((document) => documentSummary(document, input.withState === true)));
1466
- }
1467
- async submitCreate(input) {
1468
- const target = input.parentId ? await this.resolveDriveTarget(input.parentId) : null;
1469
- if (!target) {
1470
- const { jobs } = await this.client.createEmptyAsync(input.documentType, { parentIdentifier: input.parentId });
1471
- const documentId = jobs.create.documentId;
1472
- return {
1473
- documentId,
1474
- jobIds: jobIds(jobs),
1475
- followUps: input.name ? [{
1476
- documentId,
1477
- actions: [{
1478
- type: "SET_NAME",
1479
- input: { name: input.name }
1480
- }]
1481
- }] : []
1482
- };
1483
- }
1484
- const module = await this.client.getDocumentModelModule(input.documentType);
1485
- const empty = withSignaturePolicy(module.utils.createDocument(), await this.client.getCreateSignaturePolicy());
1486
- if (input.name) empty.header.name = input.name;
1487
- const documentId = empty.header.id;
1488
- const { jobs } = await this.client.createAsync(empty, target.driveId);
1489
- const { type, input: node } = addFile({
1490
- id: documentId,
1491
- name: empty.header.name || documentId,
1492
- documentType: input.documentType,
1493
- parentFolder: target.parentFolder
1494
- });
1495
- return {
1496
- documentId,
1497
- jobIds: jobIds(jobs),
1498
- followUps: [{
1499
- documentId: target.driveId,
1500
- actions: [{
1501
- type,
1502
- input: node
1503
- }]
1504
- }]
1505
- };
1506
- }
1507
- async submit(input) {
1508
- const actions = buildActions(input);
1509
- return {
1510
- jobId: (await this.client.executeAsync(input.documentId, input.branch ?? "main", actions)).id,
1511
- actionIds: actions.map((action) => action.id)
1512
- };
1513
- }
1514
- async wait(input) {
1515
- const signal = AbortSignal.timeout(input.maxWaitMs);
1516
- try {
1517
- return jobState(await this.client.waitForJob(input.jobId, signal));
1518
- } catch (error) {
1519
- if (!signal.aborted) throw error;
1520
- }
1521
- return jobState(await this.client.getJobStatus(input.jobId));
1522
- }
1523
- async handOver(summaries) {
1524
- const record = currentDocumentRecorder();
1525
- if (record) await record((Array.isArray(summaries) ? summaries : [summaries]).map((summary) => summary.documentId));
1526
- return summaries;
1527
- }
1528
- async findByType(type, limit, parentId) {
1529
- try {
1530
- return (await this.client.find({
1531
- type,
1532
- ...parentId ? { parentId } : {}
1533
- }, void 0, {
1534
- cursor: "",
1535
- limit
1536
- })).results;
1537
- } catch {
1538
- return [];
1539
- }
1540
- }
1541
- async resolveDriveTarget(parentId) {
1542
- try {
1543
- const parent = await this.client.get(parentId);
1544
- return DRIVE_DOCUMENT_TYPES.has(parent.header.documentType) ? { driveId: parent.header.id } : null;
1545
- } catch {
1546
- return this.findFolderDrive(parentId);
1547
- }
1548
- }
1549
- async findFolderDrive(nodeId) {
1550
- const pages = await Promise.all([...DRIVE_DOCUMENT_TYPES].map((type) => this.findByType(type, FIND_PAGE_LIMIT)));
1551
- for (const drive of pages.flat()) try {
1552
- if ((await this.client.drives.getNode(drive.header.id, nodeId)).kind === "folder") return {
1553
- driveId: drive.header.id,
1554
- parentFolder: nodeId
1555
- };
1556
- } catch {}
1557
- return null;
1558
- }
1559
- };
1560
- var ScopedDesignTimeReactorPort = class {
1561
- host;
1562
- caller;
1563
- inner;
1564
- constructor(host, caller) {
1565
- this.host = host;
1566
- this.caller = caller;
1567
- this.inner = new SubgraphReactorPort(host);
1568
- }
1569
- models() {
1570
- return this.inner.models();
1571
- }
1572
- model(documentType) {
1573
- return this.inner.model(documentType);
1574
- }
1575
- async get(input) {
1576
- if (!this.caller) throw new Error(DESIGN_TIME_CALLER_REQUIRED);
1577
- await this.host.assertCanRead(input.documentId, this.caller);
1578
- return this.inner.get(input);
1579
- }
1580
- async find(input) {
1581
- const found = await this.inner.find(input);
1582
- const allowed = await Promise.all(found.map((document) => this.canRead(document.documentId)));
1583
- return found.filter((_, index) => allowed[index]);
1584
- }
1585
- submit(_input) {
1586
- return Promise.reject(/* @__PURE__ */ new Error(DESIGN_TIME_WRITES_REFUSED));
1587
- }
1588
- submitCreate(_input) {
1589
- return Promise.reject(/* @__PURE__ */ new Error(DESIGN_TIME_WRITES_REFUSED));
1590
- }
1591
- wait(_input) {
1592
- return Promise.reject(/* @__PURE__ */ new Error(DESIGN_TIME_WRITES_REFUSED));
1593
- }
1594
- async canRead(documentId) {
1595
- if (!this.caller) return false;
1596
- return this.host.assertCanRead(documentId, this.caller).then(() => true).catch(() => false);
1597
- }
1598
- };
1599
1372
  //#endregion
1600
1373
  //#region src/reactor/piece-store-port.ts
1601
1374
  const logger$4 = childLogger(["workflow", "piece-store"]);
@@ -1741,7 +1514,7 @@ function boundConnections(inner) {
1741
1514
  connectionLogger.warn(`Step "${request?.stepKey ?? "?"}" of workflow "${currentWorkflowId() ?? "?"}" asked for connection "${connectionId}", which its definition does not declare`);
1742
1515
  });
1743
1516
  }
1744
- function createBlockExecutor(host, secrets, attachments, pieceStore, resolveBlock, oauth) {
1517
+ function createBlockExecutor(host, secrets, attachments, pieceStore, resolveBlock, oauth, reactorAccess) {
1745
1518
  return new CompositeBlockExecutor(new ActivepiecesBlockExecutor({
1746
1519
  cacheDir: bundleCacheDir(),
1747
1520
  egress: configuredEgress(),
@@ -1754,7 +1527,7 @@ function createBlockExecutor(host, secrets, attachments, pieceStore, resolveBloc
1754
1527
  }),
1755
1528
  resolver: pieceResolver(),
1756
1529
  ...resolveBlock ? { resolveBlock } : {},
1757
- reactor: new SubgraphReactorPort(host),
1530
+ ...reactorAccess ? { reactorAccess } : {},
1758
1531
  connections: boundConnections(new DocumentConnectionResolver(host, secrets, oauth)),
1759
1532
  ...pieceStore ? { pieceStore } : {},
1760
1533
  onPieceLog: (entry, execution) => {
@@ -1786,6 +1559,7 @@ function stepDefinition(step) {
1786
1559
  pieceVersion: step.pieceVersion,
1787
1560
  actionName: step.actionName,
1788
1561
  connectionId: step.connectionId,
1562
+ reactorConnectionId: step.reactorConnectionId,
1789
1563
  config: step.config,
1790
1564
  timeoutSeconds: step.timeoutSeconds,
1791
1565
  propertySettings: propertySettings(step.propertySettings),
@@ -1803,6 +1577,7 @@ function toWorkflowDefinition(state) {
1803
1577
  pieceVersion: runnable.trigger.pieceVersion,
1804
1578
  triggerName: runnable.trigger.triggerName,
1805
1579
  connectionId: runnable.trigger.connectionId,
1580
+ reactorConnectionId: runnable.trigger.reactorConnectionId,
1806
1581
  config: runnable.trigger.config,
1807
1582
  propertySettings: propertySettings(runnable.trigger.propertySettings)
1808
1583
  },
@@ -1911,6 +1686,491 @@ async function waitForSync(client, documentId, check, timeoutMs) {
1911
1686
  throw denied;
1912
1687
  }
1913
1688
  //#endregion
1689
+ //#region src/reactor/reactor-errors.ts
1690
+ var ReactorError = class extends Error {
1691
+ name;
1692
+ constructor(name, message) {
1693
+ super(message);
1694
+ this.name = name;
1695
+ }
1696
+ };
1697
+ function accessDenied(message) {
1698
+ return new ReactorError(ReactorAccessDeniedError, message);
1699
+ }
1700
+ function refusedMethod(method) {
1701
+ return accessDenied(`${method} is not available to workflow pieces`);
1702
+ }
1703
+ function isReactorError(error, name) {
1704
+ return error instanceof Error && error.name === name;
1705
+ }
1706
+ //#endregion
1707
+ //#region src/reactor/run-user.ts
1708
+ const PUBLISH_WORKFLOW = "PUBLISH_WORKFLOW";
1709
+ function runUserOfOperation(operation, hostIdentity) {
1710
+ const signer = operation.action.context?.signer;
1711
+ const address = signer?.user?.address;
1712
+ if (!signer || !address || !signer.signatures?.length) return null;
1713
+ const key = signer.app?.key;
1714
+ if (hostIdentity && key === hostIdentity.key) return null;
1715
+ return {
1716
+ address,
1717
+ subject: {
1718
+ address,
1719
+ key
1720
+ }
1721
+ };
1722
+ }
1723
+ async function publishRunUser(client, workflowId, hostIdentity, signal) {
1724
+ let page = await client.getOperations(workflowId, { scopes: ["global"] }, { actionTypes: [PUBLISH_WORKFLOW] }, void 0, signal);
1725
+ let latest;
1726
+ for (;;) {
1727
+ for (const operation of page.results) {
1728
+ if (operation.action.type !== "PUBLISH_WORKFLOW") continue;
1729
+ if (operation.error !== void 0) continue;
1730
+ if (!latest || operation.index > latest.index) latest = operation;
1731
+ }
1732
+ if (!page.next || page.results.length === 0) break;
1733
+ page = await page.next();
1734
+ }
1735
+ return latest ? runUserOfOperation(latest, hostIdentity) : null;
1736
+ }
1737
+ //#endregion
1738
+ //#region src/reactor/reactor-access.ts
1739
+ function authEnforced(host) {
1740
+ return host.authEnforcement !== false;
1741
+ }
1742
+ const NO_RUN_USER_DENIAL = "The workflow was published unsigned or by the Switchboard itself, so it gets no reactor access while auth enforcement is on; publish it signed in";
1743
+ async function assertConnectionReadable(host, connectionId, runUser) {
1744
+ if (!await host.reactorClient.isServed(connectionId, { subject: runUser.subject }).catch(() => false)) throw accessDenied(`${runUser.address} cannot read reactor connection "${connectionId}"`);
1745
+ }
1746
+ async function assertReactorConnectionsReadable(host, workflowId, connectionIds, known) {
1747
+ if (connectionIds.size === 0) return void 0;
1748
+ const runUser = known !== void 0 ? known : await publishRunUser(host.reactorClient, workflowId, host.hostIdentity);
1749
+ if (!runUser) {
1750
+ if (authEnforced(host)) throw accessDenied(NO_RUN_USER_DENIAL);
1751
+ return null;
1752
+ }
1753
+ for (const connectionId of connectionIds) await assertConnectionReadable(host, connectionId, runUser);
1754
+ return runUser;
1755
+ }
1756
+ //#endregion
1757
+ //#region src/reactor/run-scope-builder.ts
1758
+ async function buildReactorRunScope(host, request) {
1759
+ const { reactorConnectionId, requireReactor, runUser } = request;
1760
+ if (!reactorConnectionId) throw accessDenied("This step needs reactor access; bind a reactor connection");
1761
+ if (!runUser && authEnforced(host)) throw accessDenied(NO_RUN_USER_DENIAL);
1762
+ let document;
1763
+ try {
1764
+ document = await host.reactorClient.get(reactorConnectionId);
1765
+ } catch {
1766
+ throw accessDenied(`Reactor connection "${reactorConnectionId}" was not found`);
1767
+ }
1768
+ const state = document.state.global;
1769
+ if (document.header.documentType !== "powerhouse/connection" || state.authType !== "REACTOR" || !isReactorConnectorId(state.connectorId)) throw accessDenied(`Connection "${reactorConnectionId}" is not a reactor connection`);
1770
+ if (state.status === "REVOKED") throw accessDenied(`Reactor connection "${reactorConnectionId}" is revoked`);
1771
+ const parsed = parseReactorConnectionConfig(state.config);
1772
+ if (!parsed.ok) throw accessDenied(`Reactor connection "${reactorConnectionId}" is invalid: ${parsed.error}`);
1773
+ return {
1774
+ runUser,
1775
+ requireReactor,
1776
+ connection: { access: parsed.config.access ?? "write" }
1777
+ };
1778
+ }
1779
+ const JOB_NOT_FOUND = "Job not found";
1780
+ const MIN_DEADLINE_MARGIN_MS = 250;
1781
+ const MAX_DEADLINE_MARGIN_MS = 2e3;
1782
+ function deadlineMargin(budgetMs) {
1783
+ return Math.min(Math.max(Math.floor(budgetMs / 10), MIN_DEADLINE_MARGIN_MS), MAX_DEADLINE_MARGIN_MS);
1784
+ }
1785
+ function messageOf(error) {
1786
+ return error instanceof Error ? error.message : String(error);
1787
+ }
1788
+ function jobPending(jobId, status) {
1789
+ return new ReactorError(ReactorJobPendingError$1, status === "UNKNOWN" ? `Reactor job ${jobId} is unknown to the reactor, as after a restart; its actions may or may not have been written` : `Reactor job ${jobId} was still ${status} at the step deadline; its actions may yet be written`);
1790
+ }
1791
+ const AUTHORIZATION_DENIED = "AuthorizationDeniedError";
1792
+ function jobFailed(job) {
1793
+ const error = job.error;
1794
+ if (error?.name === AUTHORIZATION_DENIED) return accessDenied(`The Switchboard has no grant for this operation: ${error.message}`);
1795
+ return new ReactorError(ReactorJobFailedError$1, `Reactor job ${job.id} failed: ${job.error?.message ?? "unknown error"}`);
1796
+ }
1797
+ function assertActionsApplied(job, actions) {
1798
+ const outcomes = job.result?.actions ?? [];
1799
+ const byId = new Map(outcomes.map((outcome) => [outcome.actionId, outcome]));
1800
+ const failed = (actions?.map((action) => ({
1801
+ id: action.id,
1802
+ label: action.type
1803
+ })) ?? outcomes.map((outcome) => ({
1804
+ id: outcome.actionId,
1805
+ label: outcome.actionId
1806
+ }))).flatMap(({ id, label }) => {
1807
+ const outcome = byId.get(id);
1808
+ if (!outcome) return [`Action ${label} produced no operation`];
1809
+ if (outcome.kind === "reducer-error") return [`Action ${label} failed: ${outcome.message}`];
1810
+ if (outcome.kind === "denied") return [`Action ${label} was denied: ${outcome.reason}`];
1811
+ return [];
1812
+ });
1813
+ if (failed.length > 0) throw new ReactorError(ReactorActionsFailedError$1, failed.join("; "));
1814
+ }
1815
+ var RunScopedReactorClient = class {
1816
+ inner;
1817
+ scope;
1818
+ host;
1819
+ options;
1820
+ stopAt;
1821
+ maxPageLimit;
1822
+ constructor(inner, scope, host, options = {}) {
1823
+ this.inner = inner;
1824
+ this.scope = scope;
1825
+ this.host = host;
1826
+ this.options = options;
1827
+ this.stopAt = scope.deadline - deadlineMargin(scope.deadline - Date.now());
1828
+ this.maxPageLimit = options.maxPageLimit ?? 100;
1829
+ }
1830
+ async getDocumentModelModules(namespace, paging, signal) {
1831
+ this.assertAccess();
1832
+ return this.inner.getDocumentModelModules(namespace, this.paging(paging), this.signal(signal));
1833
+ }
1834
+ getDocumentModelModule(documentType) {
1835
+ this.assertAccess();
1836
+ return this.inner.getDocumentModelModule(documentType);
1837
+ }
1838
+ getDocumentModelModuleForDocument(document) {
1839
+ this.assertAccess();
1840
+ return this.inner.getDocumentModelModuleForDocument(document);
1841
+ }
1842
+ async get(identifier, view, signal) {
1843
+ const document = await this.inner.get(identifier, this.readView(view), this.signal(signal));
1844
+ await this.scope.journal.recordDocuments([document.header.id]);
1845
+ return document;
1846
+ }
1847
+ resolveIdOrSlug(identifier, view, signal) {
1848
+ return this.inner.resolveIdOrSlug(identifier, this.readView(view), this.signal(signal));
1849
+ }
1850
+ async getOperations(documentIdentifier, view, filter, paging, signal) {
1851
+ const readView = this.readView(view);
1852
+ const abort = this.signal(signal);
1853
+ const id = await this.inner.resolveIdOrSlug(documentIdentifier, readView, abort);
1854
+ const page = await this.inner.getOperations(id, readView, filter, this.paging(paging), abort);
1855
+ return this.journaled(page, () => [id]);
1856
+ }
1857
+ async getOutgoingRelationships(sourceIdentifier, relationshipType, view, paging, signal) {
1858
+ return this.documents(await this.inner.getOutgoingRelationships(sourceIdentifier, relationshipType, this.readView(view), this.paging(paging), this.signal(signal)));
1859
+ }
1860
+ async getIncomingRelationships(targetIdentifier, relationshipType, view, paging, signal) {
1861
+ return this.documents(await this.inner.getIncomingRelationships(targetIdentifier, relationshipType, this.readView(view), this.paging(paging), this.signal(signal)));
1862
+ }
1863
+ getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, paging, signal) {
1864
+ return this.inner.getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, this.readView(view), this.paging(paging), this.signal(signal));
1865
+ }
1866
+ getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, paging, signal) {
1867
+ return this.inner.getIncomingRelationshipEdges(targetIdentifier, relationshipType, this.readView(view), this.paging(paging), this.signal(signal));
1868
+ }
1869
+ async find(search, view, paging, signal) {
1870
+ return this.documents(await this.inner.find(search, this.readView(view), this.paging(paging), this.signal(signal)));
1871
+ }
1872
+ async create(document, parentIdentifier, signal) {
1873
+ this.assertWritable("create");
1874
+ const abort = this.signal(signal);
1875
+ const parentId = parentIdentifier === void 0 ? void 0 : await this.resolveReference(parentIdentifier, "main", abort);
1876
+ return this.createDocument(document, parentId, abort);
1877
+ }
1878
+ async createEmpty(documentModelType, options, signal) {
1879
+ this.assertWritable("createEmpty");
1880
+ const abort = this.signal(signal);
1881
+ const module = await this.modelModule(documentModelType, options?.documentModelVersion, abort);
1882
+ const parentId = options?.parentIdentifier === void 0 ? void 0 : await this.resolveReference(options.parentIdentifier, "main", abort);
1883
+ const base = await this.inner.getCreateProtocolVersions(parentId, abort);
1884
+ const document = withSignaturePolicy(module.utils.createDocument(), await this.inner.getCreateSignaturePolicy(), { protocolVersions: {
1885
+ ...base,
1886
+ ...options?.protocolVersions
1887
+ } });
1888
+ document.state.document.version = normalizeDocumentModelVersion(module.version);
1889
+ return this.createDocument(document, parentId, abort);
1890
+ }
1891
+ async execute(documentIdentifier, branch, actions, signal, subject) {
1892
+ if (subject !== void 0) throw accessDenied("A piece may not choose the subject it reads as");
1893
+ this.assertWritable("execute");
1894
+ const abort = this.signal(signal);
1895
+ for (const action of actions) {
1896
+ if (action.context?.signer) throw accessDenied(`Action ${action.type} carries a signer; the host signs every action`);
1897
+ if (DOCUMENT_SCOPE_ACTION_TYPES.has(action.type)) throw accessDenied(`${action.type} is a document lifecycle action, which pieces may not execute`);
1898
+ }
1899
+ const id = await this.resolveReference(documentIdentifier, branch, abort);
1900
+ await this.gate(id, branch, actions, abort);
1901
+ await this.run(id, branch, actions, abort);
1902
+ return this.readBack(id, branch, abort);
1903
+ }
1904
+ async deleteDocument(identifier, propagate, signal) {
1905
+ this.assertWritable("deleteDocument");
1906
+ if (propagate === PropagationMode.Cascade) throw accessDenied("Cascade delete is not offered to pieces");
1907
+ const abort = this.signal(signal);
1908
+ const id = await this.resolveReference(identifier, "main", abort);
1909
+ await this.gate(id, "main", [deleteDocumentAction(id)], abort);
1910
+ this.assertTimeLeft("a delete");
1911
+ await this.scope.journal.recordDocuments([id]);
1912
+ try {
1913
+ await this.inner.deleteDocument(id, void 0, abort);
1914
+ } catch (error) {
1915
+ const message = messageOf(error);
1916
+ if (message.startsWith("Authorization denied")) throw accessDenied(`The Switchboard has no grant for this operation: ${message}`);
1917
+ throw error;
1918
+ }
1919
+ }
1920
+ get subject() {
1921
+ return this.scope.runUser?.subject;
1922
+ }
1923
+ assertAccess() {
1924
+ if (this.scope.runUser === null && authEnforced(this.host)) throw accessDenied(NO_RUN_USER_DENIAL);
1925
+ }
1926
+ assertWritable(method) {
1927
+ this.assertAccess();
1928
+ if (this.scope.requireReactor !== "write") throw accessDenied(`${method} writes, and this step declares read access only`);
1929
+ if (this.scope.connection.access !== "write") throw accessDenied(`${method} writes, and the reactor connection grants read access only`);
1930
+ }
1931
+ readView(view) {
1932
+ this.assertAccess();
1933
+ if (view?.subject !== void 0) throw accessDenied("A piece may not choose the subject it reads as");
1934
+ return {
1935
+ ...view,
1936
+ subject: this.subject
1937
+ };
1938
+ }
1939
+ signal(signal) {
1940
+ const deadline = AbortSignal.timeout(Math.max(0, this.scope.deadline - Date.now()));
1941
+ return signal ? AbortSignal.any([signal, deadline]) : deadline;
1942
+ }
1943
+ paging(paging) {
1944
+ return {
1945
+ cursor: paging?.cursor ?? "",
1946
+ limit: Math.min(paging?.limit ?? this.maxPageLimit, this.maxPageLimit)
1947
+ };
1948
+ }
1949
+ async gate(documentId, branch, actions, signal) {
1950
+ if (!authEnforced(this.host) || actions.length === 0) return;
1951
+ const candidates = actions.map((action) => ({
1952
+ scope: action.scope,
1953
+ type: action.type,
1954
+ input: action.input
1955
+ }));
1956
+ let answer;
1957
+ try {
1958
+ answer = await this.inner.evaluateActions(documentId, branch, candidates, this.subject, signal);
1959
+ } catch (error) {
1960
+ throw accessDenied(`Could not check the run user's access to document ${documentId}: ${messageOf(error)}`);
1961
+ }
1962
+ const denied = answer.evaluations.flatMap((evaluation, index) => evaluation.decision === "deny" ? [`${candidates[index].type} (${evaluation.reason})`] : []);
1963
+ if (denied.length > 0) throw accessDenied(`The run user may not apply ${denied.join(", ")} to document ${documentId}`);
1964
+ }
1965
+ async run(documentId, branch, actions, signal) {
1966
+ this.assertTimeLeft(`${actions.length} action(s)`);
1967
+ const info = await this.inner.executeAsync(documentId, branch, actions, signal);
1968
+ await this.scope.journal.recordJob(info.id, [documentId]);
1969
+ const settled = await this.settle(info.id, signal);
1970
+ if (settled.status === JobStatus.FAILED) throw jobFailed(settled);
1971
+ assertActionsApplied(settled, actions);
1972
+ }
1973
+ assertTimeLeft(what) {
1974
+ if (Date.now() >= this.stopAt) throw new Error(`No time was left before the step deadline to submit ${what}; nothing was submitted`);
1975
+ }
1976
+ async settle(jobId, signal) {
1977
+ let status = JobStatus.PENDING;
1978
+ for (;;) {
1979
+ const remaining = this.stopAt - Date.now();
1980
+ if (remaining <= 0) throw jobPending(jobId, status);
1981
+ const wait = AbortSignal.any([signal, AbortSignal.timeout(remaining)]);
1982
+ let job;
1983
+ try {
1984
+ job = await this.inner.waitForJob(jobId, wait);
1985
+ } catch (error) {
1986
+ if (!wait.aborted) throw error;
1987
+ job = await this.inner.getJobStatus(jobId).catch(() => {
1988
+ throw jobPending(jobId, status);
1989
+ });
1990
+ if (job.status !== JobStatus.READ_READY && job.status !== JobStatus.FAILED) throw jobPending(jobId, job.status);
1991
+ }
1992
+ if (job.status === JobStatus.FAILED) {
1993
+ if (job.error?.message === JOB_NOT_FOUND) throw jobPending(jobId, "UNKNOWN");
1994
+ return job;
1995
+ }
1996
+ if (job.status === JobStatus.READ_READY) return job;
1997
+ status = job.status;
1998
+ }
1999
+ }
2000
+ async readBack(documentId, branch, signal) {
2001
+ const document = await this.inner.get(documentId, {
2002
+ branch,
2003
+ subject: this.subject
2004
+ }, signal);
2005
+ await this.scope.journal.recordDocuments([documentId]);
2006
+ return document;
2007
+ }
2008
+ async createDocument(document, parentId, signal) {
2009
+ const prepared = withSignaturePolicy(document, await this.inner.getCreateSignaturePolicy());
2010
+ const documentId = prepared.header.id;
2011
+ this.assertTimeLeft(`a ${prepared.header.documentType} document`);
2012
+ const { jobs } = await this.inner.createAsync(prepared, parentId, signal);
2013
+ const ordered = Object.entries(jobs).sort(([a], [b]) => Number(b === "create") - Number(a === "create"));
2014
+ for (const [key, job] of ordered) await this.scope.journal.recordJob(job.id, key === "create" || parentId === void 0 ? [documentId] : [parentId, documentId]);
2015
+ let landed = false;
2016
+ try {
2017
+ for (const [, job] of ordered) {
2018
+ const settled = await this.settle(job.id, signal);
2019
+ if (settled.status === JobStatus.FAILED) throw jobFailed(settled);
2020
+ assertActionsApplied(settled);
2021
+ landed = true;
2022
+ }
2023
+ await this.grantRunUser(documentId, signal);
2024
+ return await this.readBack(documentId, prepared.header.branch || "main", signal);
2025
+ } catch (error) {
2026
+ if (landed && error instanceof Error) error.message = `Document ${documentId} was created, but: ${error.message}`;
2027
+ throw error;
2028
+ }
2029
+ }
2030
+ async grantRunUser(documentId, signal) {
2031
+ const runUser = this.scope.runUser;
2032
+ if (!runUser) return;
2033
+ if ((await this.inner.get(documentId, void 0, signal)).state.auth.version !== 0) return;
2034
+ const grants = [{
2035
+ id: "run-user",
2036
+ description: "The user whose workflow run created this document",
2037
+ effect: "allow",
2038
+ principal: { address: runUser.address },
2039
+ capability: { can: "execute" }
2040
+ }];
2041
+ if (this.options.hostPrincipal) grants.push({
2042
+ id: "run-host",
2043
+ description: "The host that runs the workflow",
2044
+ effect: "allow",
2045
+ principal: this.options.hostPrincipal,
2046
+ capability: { can: "execute" }
2047
+ });
2048
+ await this.run(documentId, "main", [initializeAuth({
2049
+ version: 1,
2050
+ grants
2051
+ })], signal);
2052
+ }
2053
+ async resolveReference(identifier, branch, signal) {
2054
+ try {
2055
+ return await this.inner.resolveIdOrSlug(identifier, { branch }, signal);
2056
+ } catch {
2057
+ return identifier;
2058
+ }
2059
+ }
2060
+ async modelModule(documentType, version, signal) {
2061
+ if (version === void 0) return this.inner.getDocumentModelModule(documentType);
2062
+ const requested = normalizeDocumentModelVersion(version);
2063
+ let page = await this.inner.getDocumentModelModules(void 0, void 0, signal);
2064
+ for (;;) {
2065
+ const module = page.results.find((m) => m.documentModel.global.id === documentType && normalizeDocumentModelVersion(m.version) === requested);
2066
+ if (module) return module;
2067
+ if (!page.next) break;
2068
+ page = await page.next();
2069
+ }
2070
+ throw new Error(`Document model not found for type: ${documentType} with version: ${version}`);
2071
+ }
2072
+ documents(page) {
2073
+ return this.journaled(page, (documents) => documents.map((document) => document.header.id));
2074
+ }
2075
+ async journaled(page, idsOf) {
2076
+ await this.scope.journal.recordDocuments(idsOf(page.results));
2077
+ const next = page.next;
2078
+ return {
2079
+ ...page,
2080
+ next: next ? async () => this.journaled(await next(), idsOf) : void 0
2081
+ };
2082
+ }
2083
+ };
2084
+ //#endregion
2085
+ //#region src/reactor/reactor-session.ts
2086
+ const SERVED = {
2087
+ get: true,
2088
+ resolveIdOrSlug: true,
2089
+ find: true,
2090
+ getOperations: true,
2091
+ getOutgoingRelationships: true,
2092
+ getIncomingRelationships: true,
2093
+ getOutgoingRelationshipEdges: true,
2094
+ getIncomingRelationshipEdges: true,
2095
+ create: true,
2096
+ createEmpty: true,
2097
+ execute: true,
2098
+ deleteDocument: true
2099
+ };
2100
+ const REFUSED = {
2101
+ createDocumentInDrive: true,
2102
+ executeBatch: true,
2103
+ rename: true,
2104
+ setPreferredEditor: true,
2105
+ addRelationship: true,
2106
+ updateRelationship: true,
2107
+ removeRelationship: true,
2108
+ moveRelationship: true,
2109
+ upgradeDocument: true,
2110
+ deleteDocuments: true,
2111
+ executeAsync: true,
2112
+ createAsync: true,
2113
+ createEmptyAsync: true,
2114
+ getJobStatus: true,
2115
+ waitForJob: true,
2116
+ subscribe: true,
2117
+ loadBatch: true,
2118
+ evaluateActions: true,
2119
+ isDocumentIdTaken: true,
2120
+ isServed: true,
2121
+ getCreateSignaturePolicy: true,
2122
+ getCreateProtocolVersions: true
2123
+ };
2124
+ function servedClient(client) {
2125
+ const facade = Object.create(null);
2126
+ const methods = client;
2127
+ for (const name of Object.keys(SERVED)) facade[name] = (...args) => methods[name](...args);
2128
+ for (const name of Object.keys(REFUSED)) facade[name] = () => {
2129
+ throw refusedMethod(name);
2130
+ };
2131
+ return facade;
2132
+ }
2133
+ function runJournal() {
2134
+ const record = currentDocumentRecorder();
2135
+ return {
2136
+ recordDocuments: (documentIds) => record ? record(documentIds) : Promise.resolve(),
2137
+ recordJob: (_jobId, documentIds) => record ? record(documentIds) : Promise.resolve()
2138
+ };
2139
+ }
2140
+ const NO_JOURNAL = {
2141
+ recordDocuments: () => Promise.resolve(),
2142
+ recordJob: () => Promise.resolve()
2143
+ };
2144
+ function reactorTap(host, base, journal, options = {}) {
2145
+ const clientOptions = {
2146
+ ...host.hostPrincipal ? { hostPrincipal: host.hostPrincipal } : {},
2147
+ ...options
2148
+ };
2149
+ return {
2150
+ requireReactor: base.requireReactor,
2151
+ open(transport, { deadline }) {
2152
+ const client = new RunScopedReactorClient(host.reactorClient, {
2153
+ ...base,
2154
+ deadline,
2155
+ journal
2156
+ }, host, clientOptions);
2157
+ const server = new ReactorHostServer(servedClient(client), transport);
2158
+ server.start();
2159
+ return () => server.stop();
2160
+ }
2161
+ };
2162
+ }
2163
+ function designTimeScope(runUser) {
2164
+ return {
2165
+ runUser,
2166
+ requireReactor: "read",
2167
+ connection: { access: "read" }
2168
+ };
2169
+ }
2170
+ function unboundReactorConnection(reactorConnectionId) {
2171
+ return accessDenied(`Reactor connection "${reactorConnectionId}" must name a connection, not an expression`);
2172
+ }
2173
+ //#endregion
1914
2174
  //#region src/reactor/core-blocks.ts
1915
2175
  const trigger = (name) => blockKey({
1916
2176
  pieceName: CORE_PIECE_NAME,
@@ -2250,6 +2510,7 @@ function draftStepDef(step) {
2250
2510
  pieceVersion: step.pieceVersion,
2251
2511
  actionName: step.actionName,
2252
2512
  connectionId: step.connectionId,
2513
+ reactorConnectionId: step.reactorConnectionId,
2253
2514
  config: step.config,
2254
2515
  timeoutSeconds: step.timeoutSeconds,
2255
2516
  propertySettings: propertySettings(step.propertySettings),
@@ -6909,6 +7170,9 @@ async function up(db) {
6909
7170
  try {
6910
7171
  await db.schema.alterTable("run").addColumn("warning_notes", "text").execute();
6911
7172
  } catch {}
7173
+ for (const table of ["run", "step_execution"]) try {
7174
+ await db.schema.alterTable(table).addColumn("error_name", "text").execute();
7175
+ } catch {}
6912
7176
  await db.schema.createTable("run_document").addColumn("run_id", "text", (col) => col.notNull()).addColumn("document_id", "text", (col) => col.notNull()).addPrimaryKeyConstraint("run_document_pk", ["run_id", "document_id"]).ifNotExists().execute();
6913
7177
  await db.schema.createTable("piece_store").addColumn("scope", "text", (col) => col.notNull()).addColumn("scope_key", "text", (col) => col.notNull()).addColumn("key", "text", (col) => col.notNull()).addColumn("value", "text", (col) => col.notNull()).addColumn("updated_at", "text", (col) => col.notNull()).addPrimaryKeyConstraint("piece_store_pk", [
6914
7178
  "scope",
@@ -7137,9 +7401,10 @@ function stepValues(runId, ordinal, step) {
7137
7401
  block_name: step.blockName,
7138
7402
  status: step.status,
7139
7403
  input: cappedPayload(redact(step.input)),
7140
- output: cappedPayload(redact(step.output)),
7404
+ output: cappedPayload(redact(referenceDocuments(step.output))),
7141
7405
  port: step.port ?? null,
7142
7406
  error: step.error ? redactMessage(step.error) : null,
7407
+ error_name: step.errorName ?? null,
7143
7408
  started_at: step.startedAt ?? null,
7144
7409
  ended_at: step.endedAt ?? null,
7145
7410
  piece_version: step.piece?.version ?? null,
@@ -7185,10 +7450,12 @@ function journaledPayloadNames(json, ids) {
7185
7450
  return (Array.isArray(value) ? value : [value]).some((item) => {
7186
7451
  if (item === null || typeof item !== "object") return false;
7187
7452
  const record = item;
7453
+ const referenced = isDocumentRefMarker(record) ? record[DOCUMENT_REF_KEY].documentId : void 0;
7188
7454
  return [
7189
7455
  record.documentId,
7190
7456
  record.driveId,
7191
- record.parentId
7457
+ record.parentId,
7458
+ referenced
7192
7459
  ].some((id) => typeof id === "string" && ids.includes(id));
7193
7460
  });
7194
7461
  }
@@ -7214,6 +7481,7 @@ const STEP_COLUMNS_WITHOUT_DATA = [
7214
7481
  "status",
7215
7482
  "port",
7216
7483
  "error",
7484
+ "error_name",
7217
7485
  "started_at",
7218
7486
  "ended_at",
7219
7487
  "piece_version",
@@ -7354,6 +7622,7 @@ var WorkflowRunStore = class WorkflowRunStore {
7354
7622
  await this.db.updateTable("run").set({
7355
7623
  status: result.status,
7356
7624
  error: result.error ? redactMessage(result.error) : null,
7625
+ error_name: result.errorName ?? null,
7357
7626
  ended_at: (/* @__PURE__ */ new Date()).toISOString(),
7358
7627
  warnings: notes.length,
7359
7628
  warning_notes: notes.length > 0 ? JSON.stringify(notes) : null
@@ -7383,6 +7652,7 @@ var WorkflowRunStore = class WorkflowRunStore {
7383
7652
  output: eb.ref("excluded.output"),
7384
7653
  port: eb.ref("excluded.port"),
7385
7654
  error: eb.ref("excluded.error"),
7655
+ error_name: eb.ref("excluded.error_name"),
7386
7656
  started_at: eb.ref("excluded.started_at"),
7387
7657
  ended_at: eb.ref("excluded.ended_at"),
7388
7658
  piece_version: eb.ref("excluded.piece_version"),
@@ -7392,12 +7662,13 @@ var WorkflowRunStore = class WorkflowRunStore {
7392
7662
  config_hash: eb.ref("excluded.config_hash")
7393
7663
  }))).execute();
7394
7664
  }
7395
- async failRun(runId, error) {
7665
+ async failRun(runId, error, errorName) {
7396
7666
  this.runsInFlight.delete(runId);
7397
7667
  if (erasedRuns.delete(runId)) return;
7398
7668
  await this.db.updateTable("run").set({
7399
7669
  status: "FAILED",
7400
7670
  error: redactMessage(error),
7671
+ error_name: errorName ?? null,
7401
7672
  ended_at: (/* @__PURE__ */ new Date()).toISOString()
7402
7673
  }).where("id", "=", runId).execute();
7403
7674
  }
@@ -7761,7 +8032,7 @@ var TriggerSupervisor = class {
7761
8032
  warnedMissingJournal = false;
7762
8033
  constructor(options) {
7763
8034
  this.options = options;
7764
- this.worker = options.worker ?? new PieceWorker();
8035
+ this.worker = options.worker ?? new PieceWorker({ models: options.models });
7765
8036
  this.tickMs = options.tickMs ?? 15e3;
7766
8037
  this.defaultIntervalMs = options.defaultIntervalMs ?? 6e4;
7767
8038
  this.hookTimeoutMs = options.hookTimeoutMs ?? 6e4;
@@ -7852,11 +8123,11 @@ var TriggerSupervisor = class {
7852
8123
  ...pieceColumns()
7853
8124
  });
7854
8125
  }
7855
- test(binding) {
8126
+ test(binding, options = {}) {
7856
8127
  return this.enqueue(async () => {
7857
8128
  const store = await this.options.store();
7858
8129
  try {
7859
- return (await this.hook(binding, "test")).output;
8130
+ return (await this.hook(binding, "test", { ...options.runUser !== void 0 ? { runUser: options.runUser } : {} })).output;
7860
8131
  } finally {
7861
8132
  await this.dropTestPartitions(store, binding.workflowId);
7862
8133
  }
@@ -7916,7 +8187,7 @@ var TriggerSupervisor = class {
7916
8187
  const piece = await this.resolver().resolve(targetOf$1(binding));
7917
8188
  const auth = await this.options.resolveAuth(binding.connectionId, { piecePackage: binding.packageName });
7918
8189
  const redactValues = secretsFor(auth);
7919
- const reactor = servesReactorPort(binding.packageName) ? this.options.reactor : void 0;
8190
+ const reactor = await this.reactorFor(binding, hook, options.runUser);
7920
8191
  return this.worker.runTriggerHook({
7921
8192
  ...pieceModuleRef(piece),
7922
8193
  triggerName: binding.triggerName,
@@ -7925,7 +8196,6 @@ var TriggerSupervisor = class {
7925
8196
  auth,
7926
8197
  ...redactValues.length > 0 ? { redactValues } : {},
7927
8198
  ...pieceStore ? { durableStore: true } : {},
7928
- ...reactor ? { reactorAccess: true } : {},
7929
8199
  identity: {
7930
8200
  flowId: binding.workflowId,
7931
8201
  projectId: PROJECT_SCOPE_KEY
@@ -7936,13 +8206,23 @@ var TriggerSupervisor = class {
7936
8206
  ...this.egress ? { egress: this.egress } : {}
7937
8207
  }, {
7938
8208
  timeoutMs: this.hookTimeoutMs,
7939
- ...pieceStore || reactor ? { hostCalls: {
7940
- ...pieceStore ? storeHandlers(pieceStore) : {},
7941
- ...reactor ? reactorHandlers(reactor) : {}
7942
- } } : {}
8209
+ ...pieceStore ? { hostCalls: storeHandlers(pieceStore) } : {},
8210
+ ...reactor ? { reactor } : {}
7943
8211
  });
7944
8212
  }
7945
- async deliveryFor(binding) {
8213
+ async reactorFor(binding, hook, runUser) {
8214
+ const access = this.options.reactorAccess;
8215
+ if (!access) return void 0;
8216
+ const declared = (await this.triggerDescriptor(binding))?.requireReactor;
8217
+ if (!declared) return void 0;
8218
+ try {
8219
+ return await access(binding, declared, runUser);
8220
+ } catch (error) {
8221
+ if (hook === "onDisable") return void 0;
8222
+ throw error;
8223
+ }
8224
+ }
8225
+ async pieceDescriptor(binding) {
7946
8226
  const key = `${binding.source ?? ""}:${binding.packageName}@${binding.version}`;
7947
8227
  let descriptor = this.descriptors.get(key);
7948
8228
  if (!descriptor) {
@@ -7955,6 +8235,13 @@ var TriggerSupervisor = class {
7955
8235
  }, { timeoutMs: this.hookTimeoutMs })).output;
7956
8236
  this.descriptors.set(key, descriptor);
7957
8237
  }
8238
+ return descriptor;
8239
+ }
8240
+ async triggerDescriptor(binding) {
8241
+ return (await this.pieceDescriptor(binding)).triggers.find((candidate) => candidate.name === binding.triggerName);
8242
+ }
8243
+ async deliveryFor(binding) {
8244
+ const descriptor = await this.pieceDescriptor(binding);
7958
8245
  const trigger = descriptor.triggers.find((candidate) => candidate.name === binding.triggerName);
7959
8246
  const subject = `Trigger "${binding.triggerName}" of "${binding.packageName}"`;
7960
8247
  if (!trigger) throw new TriggerConfigError(`${subject}: not in ${binding.version}`);
@@ -8787,7 +9074,11 @@ var WorkflowRuntimeService = class {
8787
9074
  }
8788
9075
  async seedRegistry() {
8789
9076
  const page = await this.host.reactorClient.find({ type: "powerhouse/workflow" });
8790
- for (const document of page.results) await this.updateRegistration(document.header.id, document.state.global);
9077
+ for (const document of page.results) {
9078
+ const state = document.state.global;
9079
+ if (state.status === "ENABLED") await this.seedReactorAccess(document.header.id, state);
9080
+ await this.updateRegistration(document.header.id, state);
9081
+ }
8791
9082
  if (this.registry.size === 0 && await this.hasWebhookEndpoints()) {
8792
9083
  this.logger.warn("Trigger registry seeded no workflows, but @count webhook endpoint(s) exist: their deliveries will be refused as unknown tokens", await this.endpointCount());
8793
9084
  return;
@@ -8816,6 +9107,11 @@ var WorkflowRuntimeService = class {
8816
9107
  async applyRegistration(workflowId, state) {
8817
9108
  if (this.unarmed.delete(workflowId)) this.dropSupervised(workflowId);
8818
9109
  this.cancelResolutionRetry(workflowId);
9110
+ const denial = state.status === "ENABLED" ? this.reactorDenials.get(workflowId) : void 0;
9111
+ if (denial) {
9112
+ this.refuseArming(workflowId, state, denial);
9113
+ return;
9114
+ }
8819
9115
  const trigger = state.status === "ENABLED" ? runnableDefinition(state).trigger : void 0;
8820
9116
  const block = trigger ? triggerBlock(trigger) : void 0;
8821
9117
  if (block && blockKey(block) === WEBHOOK_BLOCK) {
@@ -8979,6 +9275,7 @@ var WorkflowRuntimeService = class {
8979
9275
  triggerName: parsed.name,
8980
9276
  config,
8981
9277
  connectionId: trigger.connectionId,
9278
+ reactorConnectionId: trigger.reactorConnectionId,
8982
9279
  pollIntervalMs,
8983
9280
  ...settings && settings.length > 0 ? { propertySettings: settings } : {}
8984
9281
  }
@@ -9015,6 +9312,56 @@ var WorkflowRuntimeService = class {
9015
9312
  async resolvedPiece(block) {
9016
9313
  return resolvedBlock(await this.resolveBlock(block));
9017
9314
  }
9315
+ reactorDenials = /* @__PURE__ */ new Map();
9316
+ async recheckReactorAccess(workflowId, operation) {
9317
+ if (operation.error !== void 0) return false;
9318
+ const type = operation.action.type;
9319
+ const enabling = type === "SET_WORKFLOW_STATUS" && operation.action.input?.status === "ENABLED";
9320
+ if (type !== "PUBLISH_WORKFLOW" && !enabling) return false;
9321
+ const state = parseWorkflowState(operation.resultingState) ?? (await this.host.reactorClient.get(workflowId)).state.global;
9322
+ const before = this.reactorDenials.get(workflowId);
9323
+ await this.checkReactorAccess(workflowId, state, type === "PUBLISH_WORKFLOW" ? runUserOfOperation(operation, this.host.hostIdentity) : void 0);
9324
+ return this.reactorDenials.get(workflowId) !== before;
9325
+ }
9326
+ async checkReactorAccess(workflowId, state, runUser) {
9327
+ const { trigger, steps } = runnableDefinition(state);
9328
+ const connectionIds = declaredReactorConnectionIds({
9329
+ trigger,
9330
+ steps,
9331
+ edges: []
9332
+ });
9333
+ try {
9334
+ await assertReactorConnectionsReadable(this.host, workflowId, connectionIds, runUser);
9335
+ this.reactorDenials.delete(workflowId);
9336
+ } catch (error) {
9337
+ if (!isReactorError(error, ReactorAccessDeniedError$1)) throw error;
9338
+ this.reactorDenials.set(workflowId, error.message);
9339
+ }
9340
+ }
9341
+ async seedReactorAccess(workflowId, state) {
9342
+ try {
9343
+ await this.checkReactorAccess(workflowId, state);
9344
+ } catch (error) {
9345
+ const message = error instanceof Error ? error.message : String(error);
9346
+ this.logger.warn("Could not check reactor access for workflow @workflow: @error", workflowId, error);
9347
+ this.reactorDenials.set(workflowId, message);
9348
+ }
9349
+ }
9350
+ reactorAccessDenial(workflowId) {
9351
+ return this.reactorDenials.get(workflowId);
9352
+ }
9353
+ refuseArming(workflowId, state, reason) {
9354
+ const had = this.registry.get(workflowId);
9355
+ this.registry.delete(workflowId);
9356
+ if (had && SUPERVISED_KINDS.has(had.kind)) this.dropSupervised(workflowId);
9357
+ this.logger.warn("Workflow @workflow is not armed: @reason", workflowId, reason);
9358
+ this.unarmed.add(workflowId);
9359
+ const trigger = runnableDefinition(state).trigger;
9360
+ if (!trigger) return;
9361
+ this.supervisor().reject(workflowId, triggerBlock(trigger), configRecord(trigger.config), reason).catch((error) => {
9362
+ this.logger.error(`Could not record the reactor access denial for workflow ${workflowId}`, error);
9363
+ });
9364
+ }
9018
9365
  unarmed = /* @__PURE__ */ new Set();
9019
9366
  reportUnarmedTrigger(workflowId, trigger, resolution) {
9020
9367
  const block = triggerBlock(trigger);
@@ -9101,11 +9448,14 @@ var WorkflowRuntimeService = class {
9101
9448
  });
9102
9449
  if (this.alreadySeen(opKey)) continue;
9103
9450
  if (context.scope === DOCUMENT_SCOPE) {
9104
- await this.matchDocumentLifecycle(operation, context, hints, opKey);
9451
+ await this.matchDocumentLifecycle(operation, context, hints);
9105
9452
  await this.forgetDeletedWorkflow(operation, context);
9106
9453
  continue;
9107
9454
  }
9108
- if (context.documentType === "powerhouse/workflow") await this.refreshRegistration(context.documentId, operation.resultingState, true);
9455
+ if (context.documentType === "powerhouse/workflow") {
9456
+ const rechecked = await this.recheckReactorAccess(context.documentId, operation);
9457
+ await this.refreshRegistration(context.documentId, operation.resultingState, !rechecked);
9458
+ }
9109
9459
  if (operation.error !== void 0) continue;
9110
9460
  for (const registration of this.registry.values()) {
9111
9461
  if (registration.kind !== "document-event") continue;
@@ -9124,12 +9474,12 @@ var WorkflowRuntimeService = class {
9124
9474
  timestampUtcMs: operation.timestampUtcMs
9125
9475
  }
9126
9476
  };
9127
- await this.enqueueFire(registration.workflowId, payload, registration.kind, opKey);
9477
+ await this.enqueueFire(registration.workflowId, payload, registration.kind, `op:${opKey}`);
9128
9478
  }
9129
9479
  if (context.documentType === DRIVE_DOCUMENT_TYPE) await this.matchDriveLifecycle(context.documentId, operation.action.type, operation.action.input, {
9130
9480
  index: operation.index,
9131
9481
  timestampUtcMs: operation.timestampUtcMs
9132
- }, opKey);
9482
+ });
9133
9483
  }
9134
9484
  }
9135
9485
  unjournaledFires = /* @__PURE__ */ new Set();
@@ -9142,13 +9492,13 @@ var WorkflowRuntimeService = class {
9142
9492
  }
9143
9493
  this.fireFromTrigger(workflowId, payload, kind);
9144
9494
  }
9145
- async enqueueFire(workflowId, payload, kind, opKey) {
9146
- const fireKey = JSON.stringify([workflowId, opKey]);
9495
+ async enqueueFire(workflowId, payload, kind, dedupeKey) {
9496
+ const fireKey = JSON.stringify([workflowId, dedupeKey]);
9147
9497
  const store = await this.store();
9148
9498
  if (this.unjournaledFires.has(fireKey)) {
9149
9499
  if (!store) return;
9150
9500
  try {
9151
- await store.claimDedupe(workflowId, `op:${opKey}`, OPERATION_DEDUPE_TTL_MS, (/* @__PURE__ */ new Date()).toISOString());
9501
+ await store.claimDedupe(workflowId, dedupeKey, OPERATION_DEDUPE_TTL_MS, (/* @__PURE__ */ new Date()).toISOString());
9152
9502
  this.unjournaledFires.delete(fireKey);
9153
9503
  } catch (error) {
9154
9504
  this.logger.warn(`Could not record the unjournaled ${kind} fire for workflow ${workflowId}: @error`, error);
@@ -9161,7 +9511,7 @@ var WorkflowRuntimeService = class {
9161
9511
  }
9162
9512
  let runId;
9163
9513
  try {
9164
- runId = await store.claimAndEnqueueRun(`op:${opKey}`, OPERATION_DEDUPE_TTL_MS, (/* @__PURE__ */ new Date()).toISOString(), {
9514
+ runId = await store.claimAndEnqueueRun(dedupeKey, OPERATION_DEDUPE_TTL_MS, (/* @__PURE__ */ new Date()).toISOString(), {
9165
9515
  workflowId,
9166
9516
  triggerKind: kind,
9167
9517
  triggerPayload: payload
@@ -9208,12 +9558,12 @@ var WorkflowRuntimeService = class {
9208
9558
  }
9209
9559
  return targets;
9210
9560
  }
9211
- async fireLifecycle(kind, payload, opKey) {
9561
+ async fireLifecycle(kind, payload) {
9212
9562
  let matched = false;
9213
9563
  for (const target of this.lifecycleTargets(kind)) {
9214
9564
  if (!matchesLifecycleFilter(target.filter, payload.documentType, payload.driveId)) continue;
9215
9565
  matched = true;
9216
- await this.enqueueFire(target.workflowId, payload, kind, opKey);
9566
+ await this.enqueueFire(target.workflowId, payload, kind, `lifecycle:${kind}:${payload.documentId}`);
9217
9567
  }
9218
9568
  if (matched) this.recordLifecycleFired(kind, payload.documentId);
9219
9569
  }
@@ -9266,7 +9616,7 @@ var WorkflowRuntimeService = class {
9266
9616
  await store.deleteDedupe(workflowId);
9267
9617
  for (const scope of ["FLOW", "PROJECT"]) await store.deletePieceStore(scope, testPartitionKey(scope, workflowId));
9268
9618
  }
9269
- async matchDocumentLifecycle(operation, context, hints, opKey) {
9619
+ async matchDocumentLifecycle(operation, context, hints) {
9270
9620
  const kind = lifecycleKindForDocumentAction(operation.action.type);
9271
9621
  if (!kind) return;
9272
9622
  if (operation.error !== void 0) return;
@@ -9287,9 +9637,9 @@ var WorkflowRuntimeService = class {
9287
9637
  index: operation.index,
9288
9638
  timestampUtcMs: operation.timestampUtcMs
9289
9639
  }
9290
- }, opKey);
9640
+ });
9291
9641
  }
9292
- async matchDriveLifecycle(driveId, actionType, input, operation, opKey) {
9642
+ async matchDriveLifecycle(driveId, actionType, input, operation) {
9293
9643
  const kind = lifecycleKindForDriveAction(actionType);
9294
9644
  if (!kind) return;
9295
9645
  if (this.lifecycleTargets(kind).length === 0) return;
@@ -9313,7 +9663,7 @@ var WorkflowRuntimeService = class {
9313
9663
  driveId,
9314
9664
  parentId: stringField(record, "parentFolder") ?? null,
9315
9665
  operation
9316
- }, opKey);
9666
+ });
9317
9667
  }
9318
9668
  triggerSupervisor;
9319
9669
  supervisor() {
@@ -9328,10 +9678,11 @@ var WorkflowRuntimeService = class {
9328
9678
  this.fireFromTrigger(workflowId, payload, kind);
9329
9679
  },
9330
9680
  webhookUrlFor: async (workflowId) => (await this.mintWebhookEndpoint(workflowId))?.url,
9681
+ reactorAccess: (binding, requireReactor, runUser) => this.triggerReactorAccess(binding, requireReactor, runUser),
9682
+ models: this.models,
9331
9683
  cacheDir: bundleCacheDir(),
9332
9684
  resolver: pieceResolver(),
9333
9685
  egress: configuredEgress(),
9334
- reactor: new SubgraphReactorPort(this.host),
9335
9686
  defaultIntervalMs: Number(process.env.PH_WORKFLOWS_POLL_INTERVAL_MS) || void 0,
9336
9687
  reconcileIntervalMs: Number(process.env.PH_WORKFLOWS_WEBHOOK_RECONCILE_MS) || void 0
9337
9688
  });
@@ -9544,6 +9895,60 @@ var WorkflowRuntimeService = class {
9544
9895
  return;
9545
9896
  }
9546
9897
  }
9898
+ models = {
9899
+ entries: () => this.host.modelManifest?.() ?? [],
9900
+ lookup: (documentType) => this.modelEntries(documentType)
9901
+ };
9902
+ async modelEntries(documentType) {
9903
+ const lookup = this.host.modelEntries?.bind(this.host);
9904
+ if (!lookup) return [];
9905
+ if (documentType !== void 0) return lookup(documentType);
9906
+ const types = new Set((this.host.modelManifest?.() ?? []).map((entry) => entry.documentType));
9907
+ const modules = await this.host.reactorClient.getDocumentModelModules();
9908
+ for (const module of modules.results) types.add(module.documentModel.global.id);
9909
+ return [...types].flatMap((type) => lookup(type));
9910
+ }
9911
+ async declaredReactor(block) {
9912
+ if (builtinPiece(block.packageName)) return void 0;
9913
+ const descriptor = await this.pieceDescriptor(targetOf(block));
9914
+ return (block.kind === "trigger" ? descriptor.triggers : descriptor.actions).find((candidate) => candidate.name === block.name)?.requireReactor;
9915
+ }
9916
+ callerRunUser(ctx) {
9917
+ const subject = ctx ? this.host.subjectOf?.(ctx) : void 0;
9918
+ return subject?.address ? {
9919
+ address: subject.address,
9920
+ subject
9921
+ } : null;
9922
+ }
9923
+ async reactorScope(reactorConnectionId, requireReactor, runUser) {
9924
+ if (reactorConnectionId?.includes("{{")) throw unboundReactorConnection(reactorConnectionId);
9925
+ const base = await buildReactorRunScope(this.host, {
9926
+ reactorConnectionId,
9927
+ requireReactor,
9928
+ runUser
9929
+ });
9930
+ if (runUser && reactorConnectionId) await assertConnectionReadable(this.host, reactorConnectionId, runUser);
9931
+ return base;
9932
+ }
9933
+ async stepReactorAccess(request) {
9934
+ const declared = await this.declaredReactor(request.block);
9935
+ if (!declared) return void 0;
9936
+ const base = await this.reactorScope(request.reactorConnectionId, declared, currentRunUser() ?? null);
9937
+ return reactorTap(this.host, base, runJournal());
9938
+ }
9939
+ async triggerReactorAccess(binding, requireReactor, runUser) {
9940
+ const bound = binding.reactorConnectionId;
9941
+ const user = runUser !== void 0 ? runUser : await assertReactorConnectionsReadable(this.host, binding.workflowId, new Set(bound ? [bound] : [])) ?? null;
9942
+ const base = await this.reactorScope(bound, requireReactor, user);
9943
+ return reactorTap(this.host, base, NO_JOURNAL);
9944
+ }
9945
+ async designReactorAccess(block, ctx, reactorConnectionId) {
9946
+ if (!await this.declaredReactor(block)) return void 0;
9947
+ const runUser = this.callerRunUser(ctx);
9948
+ if (!runUser && authEnforced(this.host)) throw accessDenied("Design-time reactor access requires a signed-in caller while auth enforcement is on");
9949
+ if (reactorConnectionId) await this.reactorScope(reactorConnectionId, "read", runUser);
9950
+ return reactorTap(this.host, designTimeScope(runUser), NO_JOURNAL);
9951
+ }
9547
9952
  descriptors = /* @__PURE__ */ new Map();
9548
9953
  designWorker;
9549
9954
  designEgress = configuredEgress() ?? DEFAULT_EGRESS_POLICY;
@@ -9566,7 +9971,7 @@ var WorkflowRuntimeService = class {
9566
9971
  let descriptor = this.descriptors.get(cacheKey);
9567
9972
  if (!descriptor) {
9568
9973
  const piece = await pieceResolver().resolve(target);
9569
- this.designWorker ??= new PieceWorker();
9974
+ this.designWorker ??= new PieceWorker({ models: this.models });
9570
9975
  let output;
9571
9976
  try {
9572
9977
  output = (await this.designWorker.describePiece({
@@ -9706,6 +10111,14 @@ var WorkflowRuntimeService = class {
9706
10111
  detail: "Connection is revoked",
9707
10112
  accountLabel
9708
10113
  };
10114
+ if (state.authType === "REACTOR") {
10115
+ const parsed = parseReactorConnectionConfig(state.config);
10116
+ return this.recordCheckResult(document, {
10117
+ ok: parsed.ok,
10118
+ detail: parsed.ok ? `Local reactor, ${parsed.config.access ?? "write"} access` : parsed.error,
10119
+ accountLabel
10120
+ });
10121
+ }
9709
10122
  if (state.authType !== "NONE" && !hasCredentials(state)) return this.recordCheckResult(document, {
9710
10123
  ok: false,
9711
10124
  detail: "Connection is not configured",
@@ -9745,7 +10158,7 @@ var WorkflowRuntimeService = class {
9745
10158
  }
9746
10159
  let outcome;
9747
10160
  try {
9748
- this.designWorker ??= new PieceWorker();
10161
+ this.designWorker ??= new PieceWorker({ models: this.models });
9749
10162
  outcome = (await this.designWorker.checkConnection({
9750
10163
  ...moduleRef,
9751
10164
  auth: shapedAuth,
@@ -10023,8 +10436,9 @@ var WorkflowRuntimeService = class {
10023
10436
  if (!ctx) throw new Error("Connection access requires an authenticated request");
10024
10437
  await this.host.assertCanWrite(documentId, ctx);
10025
10438
  }
10026
- async blockOptions(block, propName, input, connectionId, ctx, searchValue) {
10439
+ async blockOptions(block, propName, input, connectionId, ctx, searchValue, reactorConnectionId) {
10027
10440
  if (connectionId) await this.assertCanReadDocument(connectionId, ctx);
10441
+ if (reactorConnectionId) await this.assertCanReadDocument(reactorConnectionId, ctx);
10028
10442
  const resolution = await this.resolveBlock(block);
10029
10443
  const parsed = resolvedBlock(resolution);
10030
10444
  if (!parsed) throw new Error(resolution.note ?? `${blockLabel(block)} does not resolve`);
@@ -10032,7 +10446,8 @@ var WorkflowRuntimeService = class {
10032
10446
  let auth;
10033
10447
  if (connectionId) auth = await new DocumentConnectionResolver(this.host, this.secretProvider(), this.oauthRefresher()).resolve(connectionId, { piecePackage: parsed.packageName });
10034
10448
  const piece = await pieceResolver().resolve(targetOf(parsed));
10035
- this.designWorker ??= new PieceWorker();
10449
+ const reactor = await this.designReactorAccess(parsed, ctx, reactorConnectionId);
10450
+ this.designWorker ??= new PieceWorker({ models: this.models });
10036
10451
  return (await this.designWorker.resolveOptions({
10037
10452
  ...pieceModuleRef(piece),
10038
10453
  actionName: parsed.name,
@@ -10042,9 +10457,8 @@ var WorkflowRuntimeService = class {
10042
10457
  ...searchValue !== void 0 ? { searchValue } : {},
10043
10458
  auth,
10044
10459
  projectId: PROJECT_SCOPE_KEY,
10045
- ...servesReactorPort(parsed.packageName) ? { reactorAccess: true } : {},
10046
10460
  ...this.designEgress ? { egress: this.designEgress } : {}
10047
- }, servesReactorPort(parsed.packageName) ? { hostCalls: reactorHandlers(new ScopedDesignTimeReactorPort(this.host, ctx)) } : {})).output;
10461
+ }, reactor ? { reactor } : {})).output;
10048
10462
  }
10049
10463
  async blockOutputTree(block, config) {
10050
10464
  const record = config ?? {};
@@ -10117,17 +10531,14 @@ var WorkflowRuntimeService = class {
10117
10531
  const stateChildren = await this.stateFields(staticString(record.documentType));
10118
10532
  return {
10119
10533
  source: stateChildren.length > 0 ? "schema" : "static",
10120
- nodes: documentGetTree(stateChildren)
10534
+ nodes: documentTree(stateChildren)
10121
10535
  };
10122
10536
  }
10123
10537
  case DOCUMENT_CREATE_BLOCK:
10124
- case DOCUMENT_DISPATCH_BLOCK: {
10125
- const stateChildren = await this.stateFields(staticString(record.documentType));
10126
- return {
10127
- source: stateChildren.length > 0 ? "schema" : "static",
10128
- nodes: documentBlockTree(stateChildren)
10129
- };
10130
- }
10538
+ case DOCUMENT_DISPATCH_BLOCK: return {
10539
+ source: "static",
10540
+ nodes: documentReferenceTree()
10541
+ };
10131
10542
  default: {
10132
10543
  const parsed = await this.resolvedPiece(block);
10133
10544
  if (!parsed) return {
@@ -10188,7 +10599,8 @@ var WorkflowRuntimeService = class {
10188
10599
  const trigger = state.trigger;
10189
10600
  if (!trigger) throw new Error("Workflow has no trigger");
10190
10601
  if (trigger.connectionId) await this.assertCanReadDocument(trigger.connectionId, ctx);
10191
- const test = await this.triggerTest(workflowId, trigger, options);
10602
+ if (trigger.reactorConnectionId) await this.assertCanReadDocument(trigger.reactorConnectionId, ctx);
10603
+ const test = await this.triggerTest(workflowId, trigger, options, ctx);
10192
10604
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
10193
10605
  const recordTest = (outcome) => this.recordTest(workflowId, state, document.header.name, {
10194
10606
  stepId: trigger.id,
@@ -10204,9 +10616,11 @@ var WorkflowRuntimeService = class {
10204
10616
  try {
10205
10617
  output = await test.sample();
10206
10618
  } catch (error) {
10619
+ const errorName = errorNameOf(error);
10207
10620
  await recordTest({
10208
10621
  status: "FAILED",
10209
- error: pieceFailureDetail(error, "Trigger test timed out")
10622
+ error: pieceFailureDetail(error, "Trigger test timed out"),
10623
+ ...errorName ? { errorName } : {}
10210
10624
  });
10211
10625
  throw error;
10212
10626
  }
@@ -10217,7 +10631,7 @@ var WorkflowRuntimeService = class {
10217
10631
  });
10218
10632
  return output;
10219
10633
  }
10220
- async triggerTest(workflowId, trigger, options) {
10634
+ async triggerTest(workflowId, trigger, options, ctx) {
10221
10635
  const config = configRecord(trigger.config);
10222
10636
  const block = triggerBlock(trigger);
10223
10637
  switch (blockKey(block)) {
@@ -10249,7 +10663,7 @@ var WorkflowRuntimeService = class {
10249
10663
  if (!binding) throw new Error(`${blockLabel(block)} is not a trigger this runtime can test`);
10250
10664
  return {
10251
10665
  input: binding.config,
10252
- sample: () => this.supervisor().test(binding)
10666
+ sample: () => this.supervisor().test(binding, { runUser: this.callerRunUser(ctx) })
10253
10667
  };
10254
10668
  }
10255
10669
  webhookTests = /* @__PURE__ */ new Map();
@@ -10298,7 +10712,8 @@ var WorkflowRuntimeService = class {
10298
10712
  await store.finishRun(runId, {
10299
10713
  status: record.status === "FAILED" ? "FAILED" : "SUCCEEDED",
10300
10714
  steps: [record],
10301
- ...record.error ? { error: record.error } : {}
10715
+ ...record.error ? { error: record.error } : {},
10716
+ ...record.errorName ? { errorName: record.errorName } : {}
10302
10717
  });
10303
10718
  } catch (error) {
10304
10719
  this.logger.warn(`Could not journal the test of "@step" on workflow ${workflowId}: @error`, record.key, error);
@@ -10318,10 +10733,11 @@ var WorkflowRuntimeService = class {
10318
10733
  }
10319
10734
  }
10320
10735
  blockExecutor(store) {
10321
- return this.executor ??= createBlockExecutor(this.host, this.secretProvider(), this.attachments, store ? createPieceStorePort(store, currentWorkflowId) : void 0, (block) => this.resolveBlock(block), this.oauthRefresher());
10736
+ return this.executor ??= createBlockExecutor(this.host, this.secretProvider(), this.attachments, store ? createPieceStorePort(store, currentWorkflowId) : void 0, (block) => this.resolveBlock(block), this.oauthRefresher(), (request) => this.stepReactorAccess(request));
10322
10737
  }
10323
10738
  workers() {
10324
10739
  return this.pieceWorkers ??= new PieceWorkerPool({
10740
+ models: this.models,
10325
10741
  size: Number(process.env.PH_WORKFLOWS_RUN_CONCURRENCY) || void 0,
10326
10742
  maxQueueDepth: Number(process.env.PH_WORKFLOWS_RUN_QUEUE_DEPTH) || void 0
10327
10743
  });
@@ -10331,6 +10747,7 @@ var WorkflowRuntimeService = class {
10331
10747
  let state;
10332
10748
  let documentName;
10333
10749
  let definition;
10750
+ let runUser;
10334
10751
  try {
10335
10752
  if (triggerKind === "manual") await this.assertCanReadDocument(workflowId, ctx);
10336
10753
  const document = await this.host.reactorClient.get(workflowId);
@@ -10339,8 +10756,9 @@ var WorkflowRuntimeService = class {
10339
10756
  documentName = document.header.name;
10340
10757
  if (state.status !== "ENABLED") throw new Error(`Workflow is ${state.status}; only ENABLED workflows can fire`);
10341
10758
  definition = toWorkflowDefinition(state);
10759
+ runUser = await assertReactorConnectionsReadable(this.host, workflowId, declaredReactorConnectionIds(definition));
10342
10760
  } catch (error) {
10343
- if (enqueuedRunId) await store?.failRun(enqueuedRunId, error instanceof Error ? error.message : String(error));
10761
+ if (enqueuedRunId) await store?.failRun(enqueuedRunId, error instanceof Error ? error.message : String(error), errorNameOf(error));
10344
10762
  throw error;
10345
10763
  }
10346
10764
  const connections = declaredConnectionIds(definition);
@@ -10373,6 +10791,7 @@ var WorkflowRuntimeService = class {
10373
10791
  runId,
10374
10792
  connections,
10375
10793
  pieceWorker: session,
10794
+ ...runUser !== void 0 ? { runUser } : {},
10376
10795
  recordDocuments: async (documentIds) => {
10377
10796
  for (const documentId of documentIds) handed.add(documentId);
10378
10797
  if (journal && journaledRunId) await journal.recordRunDocuments(journaledRunId, documentIds);
@@ -10415,7 +10834,7 @@ var WorkflowRuntimeService = class {
10415
10834
  runId
10416
10835
  };
10417
10836
  } catch (error) {
10418
- if (store && runId) await store.failRun(runId, error instanceof Error ? error.message : String(error));
10837
+ if (store && runId) await store.failRun(runId, error instanceof Error ? error.message : String(error), errorNameOf(error));
10419
10838
  throw error;
10420
10839
  } finally {
10421
10840
  session?.close();
@@ -10442,6 +10861,7 @@ var WorkflowRuntimeService = class {
10442
10861
  if (!current || current.key !== row.step_key || row.config_hash === null || stepConfigHash(current) !== row.config_hash) continue;
10443
10862
  const output = row.output === null ? void 0 : JSON.parse(row.output);
10444
10863
  if (isTruncatedStepPayload(output)) continue;
10864
+ if (containsDocumentRef(output) && await this.rereads(current)) continue;
10445
10865
  completedSteps.set(row.step_id, {
10446
10866
  output,
10447
10867
  port: row.port
@@ -10452,6 +10872,10 @@ var WorkflowRuntimeService = class {
10452
10872
  rerunOf: runId
10453
10873
  }, ctx);
10454
10874
  }
10875
+ async rereads(step) {
10876
+ const parsed = resolvedBlock(await this.resolveBlock(stepBlock(step)));
10877
+ return parsed ? await this.declaredReactor(parsed) === "read" : false;
10878
+ }
10455
10879
  async testStep(workflowId, stepId, ctx, access = {}) {
10456
10880
  await this.assertCanReadWorkflow(workflowId, ctx, access.driveId);
10457
10881
  const document = await this.host.reactorClient.get(workflowId);
@@ -10459,6 +10883,7 @@ var WorkflowRuntimeService = class {
10459
10883
  const step = state.steps.find((candidate) => candidate.id === stepId);
10460
10884
  if (!step) throw new Error(`Step "${stepId}" not found`);
10461
10885
  if (step.connectionId) await this.assertCanReadDocument(step.connectionId, ctx);
10886
+ if (step.reactorConnectionId) await this.assertCanReadDocument(step.reactorConnectionId, ctx);
10462
10887
  const refused = (error) => ({
10463
10888
  runId: null,
10464
10889
  status: "FAILED",
@@ -10521,6 +10946,7 @@ var WorkflowRuntimeService = class {
10521
10946
  connections: declaredConnectionIds(definition),
10522
10947
  pieceWorker: session,
10523
10948
  stepTest: true,
10949
+ runUser: this.callerRunUser(ctx),
10524
10950
  recordDocuments: async (documentIds) => {
10525
10951
  for (const documentId of documentIds) handed.add(documentId);
10526
10952
  if (store && journaledRunId) await store.recordRunDocuments(journaledRunId, documentIds);
@@ -10536,7 +10962,7 @@ var WorkflowRuntimeService = class {
10536
10962
  } catch (error) {
10537
10963
  if (store && runId) {
10538
10964
  const detail = error instanceof Error ? error.message : String(error);
10539
- await store.failRun(runId, detail).catch(() => void 0);
10965
+ await store.failRun(runId, detail, errorNameOf(error)).catch(() => void 0);
10540
10966
  await this.noteLastTest(workflowId, {
10541
10967
  stepId: step.id,
10542
10968
  key: step.key
@@ -10563,6 +10989,7 @@ var WorkflowRuntimeService = class {
10563
10989
  status: record.status === "FAILED" ? "FAILED" : "SUCCEEDED",
10564
10990
  ...served && record.output !== void 0 ? { output: record.output } : {},
10565
10991
  ...record.error ? { error: record.error } : {},
10992
+ ...record.errorName ? { errorName: record.errorName } : {},
10566
10993
  durationMs
10567
10994
  };
10568
10995
  }
@@ -10578,7 +11005,9 @@ var WorkflowRuntimeService = class {
10578
11005
  lastTest: state.trigger.lastTest
10579
11006
  }, ctx);
10580
11007
  if (sample.kind !== "succeeded") return { error: untestedError("the trigger", sample) };
10581
- const { payload, empty } = triggerSamplePayload(sample.output);
11008
+ const read = await this.readReferencedDocuments(sample.output, ctx);
11009
+ if ("error" in read) return { error: `The last test of the trigger read ${read.error}` };
11010
+ const { payload, empty } = triggerSamplePayload(read.value);
10582
11011
  if (empty) return { error: "Test the trigger first: its last test returned no items" };
10583
11012
  triggerPayload = payload;
10584
11013
  samples.push({
@@ -10608,10 +11037,12 @@ var WorkflowRuntimeService = class {
10608
11037
  continue;
10609
11038
  }
10610
11039
  if (sample.kind !== "succeeded") return { error: untestedError(label, sample) };
10611
- priorSteps[candidate.key] = { output: sample.output };
11040
+ const read = await this.readReferencedDocuments(sample.output, ctx);
11041
+ if ("error" in read) return { error: `The last test of ${label} read ${read.error}` };
11042
+ priorSteps[candidate.key] = { output: read.value };
10612
11043
  samples.push({
10613
11044
  label,
10614
- value: sample.output
11045
+ value: read.value
10615
11046
  });
10616
11047
  }
10617
11048
  return {
@@ -10620,6 +11051,52 @@ var WorkflowRuntimeService = class {
10620
11051
  samples
10621
11052
  };
10622
11053
  }
11054
+ async readReferencedDocuments(value, ctx) {
11055
+ const references = documentRefsIn(value);
11056
+ if (references.length === 0) return { value };
11057
+ const subject = ctx ? this.host.subjectOf?.(ctx) : void 0;
11058
+ const key = (reference) => `${reference.branch}:${reference.documentId}`;
11059
+ const read = /* @__PURE__ */ new Map();
11060
+ for (const reference of references) {
11061
+ if (read.has(key(reference))) continue;
11062
+ try {
11063
+ await this.assertCanReadDocument(reference.documentId, ctx);
11064
+ const document = await this.host.reactorClient.get(reference.documentId, {
11065
+ branch: reference.branch,
11066
+ ...subject ? { subject } : {}
11067
+ });
11068
+ read.set(key(reference), {
11069
+ header: document.header,
11070
+ state: document.state
11071
+ });
11072
+ } catch (error) {
11073
+ const detail = error instanceof Error ? error.message : String(error);
11074
+ return { error: `document "${reference.documentId}", which cannot be read now: ${detail}` };
11075
+ }
11076
+ }
11077
+ return { value: expandDocumentRefs(value, (reference) => read.get(key(reference))) };
11078
+ }
11079
+ async documentShapes(value) {
11080
+ const types = [...new Set(documentRefsIn(value).map((ref) => ref.documentType))];
11081
+ const fields = new Map(await Promise.all(types.map(async (type) => [type, await this.stateFields(type)])));
11082
+ const treeOf = (reference) => documentTree(fields.get(reference.documentType) ?? []);
11083
+ return {
11084
+ value: expandDocumentRefs(value, (reference) => {
11085
+ const shape = treeValue(treeOf(reference));
11086
+ return {
11087
+ ...shape,
11088
+ header: {
11089
+ ...shape.header,
11090
+ id: reference.documentId,
11091
+ documentType: reference.documentType,
11092
+ branch: reference.branch,
11093
+ revision: reference.revision
11094
+ }
11095
+ };
11096
+ }),
11097
+ nodes: fromSample(value, 0, treeOf)
11098
+ };
11099
+ }
10623
11100
  async lastTestSample(block, ctx) {
10624
11101
  const lastTest = block.lastTest;
10625
11102
  const store = await this.store();
@@ -10666,10 +11143,11 @@ var WorkflowRuntimeService = class {
10666
11143
  lastTest: found.lastTest
10667
11144
  }, ctx);
10668
11145
  if (sample.kind === "succeeded") {
10669
- const value = isTrigger ? triggerSamplePayload(sample.output).payload : sample.output;
11146
+ const journaled = isTrigger ? triggerSamplePayload(sample.output).payload : sample.output;
11147
+ const { value, nodes } = await this.documentShapes(journaled);
10670
11148
  return {
10671
11149
  source: "test",
10672
- nodes: fromSample(value),
11150
+ nodes,
10673
11151
  sample: value,
10674
11152
  testedAt: sample.testedAt,
10675
11153
  runId: sample.runId
@@ -10731,6 +11209,6 @@ var WorkflowTriggersReadModel = class extends BaseReadModel {
10731
11209
  }
10732
11210
  };
10733
11211
  //#endregion
10734
- export { CORE_PIECE_NAME, CORE_PIECE_VERSION, InvalidRunCursorError, PieceRegistry, WORKFLOW_PACKAGE_NAME, WORKFLOW_SYNCING_MESSAGE, WORKFLOW_TRIGGERS_READ_MODEL, WORKFLOW_TRIGGERS_READ_MODEL_STAGE, WorkflowRuntimeService, WorkflowSyncingError, WorkflowTriggersReadModel, createAttachmentPort, createWorkflowRuntime, packagePieces, setPieceRegistryUrl };
11212
+ export { CORE_PIECE_NAME, CORE_PIECE_VERSION, InvalidRunCursorError, PieceRegistry, WORKFLOW_PACKAGE_NAME, WORKFLOW_SYNCING_MESSAGE, WORKFLOW_TRIGGERS_READ_MODEL, WORKFLOW_TRIGGERS_READ_MODEL_STAGE, WorkflowRuntimeService, WorkflowSyncingError, WorkflowTriggersReadModel, createAttachmentPort, createWorkflowRuntime, packagePieces, publishRunUser, setPieceRegistryUrl };
10735
11213
 
10736
11214
  //# sourceMappingURL=index.js.map