@aglyn/plugins-workflows 1.8.0 → 1.9.0
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/package.json +12 -12
- package/src/lib/components/host-webhooks-card.component.js +5 -4
- package/src/lib/components/host-webhooks-card.component.js.map +1 -1
- package/src/lib/engine/run-event-actions.js +13 -5
- package/src/lib/engine/run-event-actions.js.map +1 -1
- package/src/lib/engine/run-event-workflows.js +9 -1
- package/src/lib/engine/run-event-workflows.js.map +1 -1
- package/src/lib/model/step-outcomes.d.ts +1 -1
- package/src/lib/model/step-outcomes.js +1 -1
- package/src/lib/model/step-outcomes.js.map +1 -1
- package/src/lib/server.js +5 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/usage-axes.js +8 -1
- package/src/lib/usage-axes.js.map +1 -1
|
@@ -16,6 +16,9 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { checkEntitlement, evaluateExpression, resolveOrgEntitlements } from "@aglyn/aglyn/server";
|
|
18
18
|
import { activitySearchTokens } from "@aglyn/aglyn/app-utils/activity-search";
|
|
19
|
+
// By its own module, not the server barrel: specs stub the barrel with a
|
|
20
|
+
// partial object, and the run overage question is the plan table's to answer.
|
|
21
|
+
import { runOverageSold } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
19
22
|
import { triggerFilterProblem } from "@aglyn/aglyn/app-utils/site-interactions";
|
|
20
23
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
21
24
|
import { FieldValue } from "firebase-admin/firestore";
|
|
@@ -148,7 +151,12 @@ import { FLOW_TIMED_OUT_FIELD } from "../model/host-actions.js";
|
|
|
148
151
|
// Plan-less orgs resolve as free (AGL-247) — the cap always runs.
|
|
149
152
|
const limit = resolveOrgEntitlements(org).workflowRunsPerMonth;
|
|
150
153
|
const used = await runsUsedThisMonth(meter);
|
|
151
|
-
|
|
154
|
+
// Past the band is a wall only where the plan sells no runs past it
|
|
155
|
+
// (pricing v4): on a plan with a run rate the workflows run, and the
|
|
156
|
+
// excess bills on the month's invoice (`priceRunOverage`).
|
|
157
|
+
if (used + workflows.length > limit && !runOverageSold(org)) {
|
|
158
|
+
return alerts;
|
|
159
|
+
}
|
|
152
160
|
}
|
|
153
161
|
const [functionDocs, variableDocs] = await Promise.all([
|
|
154
162
|
hostRef.collection('functions').limit(100).get(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/engine/run-event-workflows.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n checkEntitlement,\n evaluateExpression,\n type HostEventType,\n type HostFunction,\n type HostVariable,\n resolveOrgEntitlements,\n} from '@aglyn/aglyn/server'\nimport { activitySearchTokens } from '@aglyn/aglyn/app-utils/activity-search'\nimport { triggerFilterProblem } from '@aglyn/aglyn/app-utils/site-interactions'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport type { HostEventPayload } from '@aglyn/tenant-runtime/host-event-listeners'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { runSummaryFields } from '../model/run-history'\nimport { ACTION_MAX_EVENT_DEPTH, type HostWorkflow, runWorkflow } from '../model/workflows'\nimport { eventRunSuspension } from './site-suspension'\nimport {\n recordRuns,\n type RunMeterScope,\n runMonthKey,\n runsUsedThisMonth,\n} from './run-meter'\nimport {\n deferFlowEnrollment,\n endFlowEnrollment,\n type FlowEnrollment,\n} from './flow-enrollments'\nimport {\n automationRunEnv,\n executeWorkflow,\n FLOW_CLAIM_RETRY_MS,\n SKIP_LOG_EXCLUDED_EVENTS,\n stopFlowEnrollment,\n type WorkflowContext,\n type WorkflowExecution,\n} from './run-event-actions'\nimport {\n type AutomationWorkflow,\n workflowHasActionSteps,\n} from './workflow-steps'\nimport { runTriggeredByFields } from './run-trigger-actor'\nimport { triggeredDocsForEvent } from './triggered-docs'\nimport { FLOW_TIMED_OUT_FIELD, type HostActionAlert } from '../model/host-actions'\n\n/**\n * Every live workflow on the event runs, in document-id order, up to this\n * many (AGL-3458) — the hundred the workflow map below already reads, so a\n * workflow the map can see is one its event can start. See\n * `triggered-docs.ts` for why the dispatch pages rather than truncates.\n */\nconst MAX_TRIGGERED_WORKFLOWS = 100\n\n/**\n * One workflow run's row in the site's activity feed, which is the run\n * history the Workflows tab reads.\n *\n * The one place a workflow's run is written, whichever door started it.\n */\nasync function recordWorkflowRun(\n hostRef: FirebaseFirestore.DocumentReference,\n row: Record<string, unknown>,\n): Promise<void> {\n await hostRef\n .collection('activity')\n .add({\n actorId: null,\n actorEmail: null,\n // Who set this run off (AGL-3376).\n ...runTriggeredByFields(),\n ...row,\n // The site log's search finds a run by its workflow's name (AGL-3321).\n searchTokens: activitySearchTokens({\n target: row['target'] as { name?: unknown } | undefined,\n }),\n createdAt: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n}\n\n/**\n * The history row for a run of a workflow with Actions steps, in the Actions\n * run's phrasing (AGL-2171) — what each step did, joined — so the run table\n * shows every step's outcome whichever engine the step came from. `status`\n * and `durationMs` ride along as they do on every workflow run, for the\n * dashboard feed that renders them.\n */\nexport function workflowRunRow(\n execution: Pick<WorkflowExecution, 'ending' | 'errors' | 'outcomes'>,\n input: {\n event: string\n workflowId: string\n workflowName: string\n durationMs: number\n },\n): Record<string, unknown> {\n const failed = execution.errors.length > 0\n const action = failed\n ? `Workflow ran on ${input.event} with errors: ${execution.errors.join('; ')}`.slice(\n 0,\n 300,\n )\n : execution.ending === 'waiting'\n ? `Workflow is waiting, on ${input.event}`\n : `Workflow ran on ${input.event}`\n return {\n action,\n result: failed ? 'failed' : 'succeeded',\n trigger: input.event,\n // The summary and its search tokens, written together (AGL-3321).\n ...runSummaryFields(\n (execution.outcomes.length\n ? execution.outcomes.join(' · ')\n : 'Ran'\n ).slice(0, 300),\n ),\n status: failed ? 'error' : 'ok',\n durationMs: input.durationMs,\n target: {\n type: 'workflow',\n id: input.workflowId,\n name: input.workflowName,\n },\n }\n}\n\n/**\n * Event-triggered workflow runner (AGL-128): loads workflows whose\n * `trigger.event` matches, evaluates optional trigger filters over the\n * event payload, runs each, and logs runs to the host activity feed.\n * Fire-and-forget from the tenant's event sites (form submit, pageview\n * collector, membership APIs) — it never throws, and a failure must not\n * break the request that emitted the event.\n *\n * A workflow of function calls runs through the pure `runWorkflow`\n * evaluator exactly as it always has. A workflow with Actions steps runs\n * through `executeWorkflow`, which performs them with the Actions executors;\n * the site alerts its steps raise are what this resolves.\n *\n * ONE RUN, METERED ONCE: either kind counts one run on the workflow meter,\n * `workflowRunsPerMonth`, however many steps it has and whatever they are.\n * Its Actions steps take the Actions tier gates step by step, and none of\n * them counts an action run.\n *\n * `depth` is the chain guard actions run under (`ACTION_MAX_EVENT_DEPTH`):\n * an event a workflow's own step raised — a stage it set — is heard one\n * level deeper, so a workflow that sets the stage it listens for stops.\n */\nexport async function runEventWorkflows(\n hostId: string,\n event: HostEventType,\n payload: HostEventPayload = {},\n depth = 0,\n): Promise<HostActionAlert[]> {\n const alerts: HostActionAlert[] = []\n if (depth > ACTION_MAX_EVENT_DEPTH) return alerts\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const workflows = await triggeredDocsForEvent(hostRef.collection('workflows'), event, {\n keep: (doc) => !doc.get('deletedAt'),\n max: MAX_TRIGGERED_WORKFLOWS,\n maxReads: MAX_TRIGGERED_WORKFLOWS * 4,\n })\n if (!workflows.length) return alerts\n // Full workflow map for nested function→workflow calls (AGL-129).\n const allWorkflowDocs = await hostRef\n .collection('workflows')\n .limit(100)\n .get()\n // Double-keyed by doc id AND name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n // Each carries its id, so a workflow a step names by its legacy name\n // still runs as the automation it is (see `WorkflowContext`).\n const workflowMap: WorkflowContext['workflows'] = {}\n for (const doc of allWorkflowDocs.docs) {\n const data = doc.data() as any\n if (data.deletedAt) continue\n const withId = { ...data, $id: doc.id }\n workflowMap[doc.id] = withId\n if (data?.name) workflowMap[data.name] = withId\n }\n\n // Monthly run cap by the owning org's plan (AGL-165).\n // Run caps ride the owning org's doc (AGL-238) — read through\n // `getOrgForHost` below. The host document itself is not consulted: the\n // cap, the counter and the workflow definitions all live elsewhere, so a\n // read of it here would be billed on every host event and used for\n // nothing.\n const owner = await getOrgForHost(hostId)\n // The band is the WORKSPACE's (AGL-3472): every site's runs count\n // against it, read off the org's counter — see `run-meter.ts`.\n const meter: RunMeterScope = {\n firestore,\n hostRef,\n orgId: owner?.orgId,\n counter: 'workflowRuns',\n month: runMonthKey(),\n }\n // A suspended site runs nothing (AGL-3356): see `eventRunSuspension`.\n // Asked before the cap so a locked site's events bill no runs.\n if (await eventRunSuspension(hostRef, owner?.org)) return alerts\n {\n const org = owner?.org\n // Plan-less orgs resolve as free (AGL-247) — the cap always runs.\n const limit = resolveOrgEntitlements(\n org as any,\n ).workflowRunsPerMonth\n const used = await runsUsedThisMonth(meter)\n if (used + workflows.length > limit) return alerts\n }\n\n const [functionDocs, variableDocs] = await Promise.all([\n hostRef.collection('functions').limit(100).get(),\n hostRef.collection('variables').limit(100).get(),\n ])\n const functions: Record<string, HostFunction> = {}\n for (const doc of functionDocs.docs) {\n const definition = doc.data() as any\n if (definition.deletedAt) continue\n functions[doc.id] = definition\n if (definition.name) functions[definition.name] = definition\n }\n const variables: Record<string, HostVariable> = {}\n for (const doc of variableDocs.docs) {\n const variable = doc.data() as any\n if (!variable.deletedAt && variable.name) {\n variables[variable.name] = variable\n }\n }\n\n let executed = 0\n for (const doc of workflows) {\n const workflow = doc.data() as AutomationWorkflow\n const filter = workflow.trigger?.filter?.trim()\n if (filter) {\n /*\n * A filter no event can ever satisfy — a comparison the evaluator\n * does not have, text it cannot read — answers \"why didn't it run?\"\n * in the run history, on every event it would have run on, rather\n * than leaving the workflow silent. The editor refuses to save one;\n * this is the one stored before it did, or written around it.\n */\n const unrunnable = triggerFilterProblem(filter, { remedy: 'action' })\n if (unrunnable) {\n if (!SKIP_LOG_EXCLUDED_EVENTS.has(event)) {\n await recordWorkflowRun(hostRef, {\n action: `Workflow skipped on ${event}`,\n result: 'skipped',\n trigger: event,\n ...runSummaryFields(unrunnable.slice(0, 300)),\n target: { type: 'workflow', id: doc.id, name: workflow.name ?? '' },\n })\n }\n continue\n }\n try {\n const scope: HostEventPayload = { event, ...payload }\n if (!evaluateExpression(filter, scope)) continue\n } catch {\n continue // A field the filter names is not on this event.\n }\n }\n const startedAt = Date.now()\n if (workflowHasActionSteps(workflow)) {\n /*\n * A WORKFLOW WITH ACTIONS STEPS is performed, not evaluated. The\n * maps above are this run's working set, so the executor reads them\n * rather than a second copy; the plan gates come off the org\n * document the cap already read.\n */\n const context: WorkflowContext = {\n functions,\n variables,\n workflows: workflowMap,\n }\n const env = automationRunEnv({\n hostId,\n hostRef,\n owner,\n depth,\n alerts,\n loadWorkflowContext: async () => context,\n })\n const execution = await executeWorkflow(\n env,\n { kind: 'workflow', id: doc.id, name: workflow.name ?? '' },\n workflow,\n event,\n payload,\n )\n executed += 1\n await recordWorkflowRun(\n hostRef,\n workflowRunRow(execution, {\n event,\n workflowId: doc.id,\n workflowName: workflow.name ?? '',\n durationMs: Date.now() - startedAt,\n }),\n )\n continue\n }\n const run = runWorkflow(\n workflow as HostWorkflow,\n functions,\n variables,\n { event, ...payload },\n { workflows: workflowMap },\n )\n const durationMs = Date.now() - startedAt\n executed += 1\n // `=== false` (not `!run.ok`): the union fails to narrow under the\n // stricter build tsconfig otherwise (same quirk as runWorkflow).\n const action =\n run.ok === false\n ? `Workflow failed on ${event}: ${run.error}`.slice(0, 300)\n : `Workflow ran on ${event}`\n /*\n * The run-history shape, not just `status` + `durationMs` (AGL-2222).\n *\n * `actionRunResult()` recognises a run by `result`, falling back to the\n * prose prefix `Action ran on`. This writer's prose begins\n * `Workflow ran on`, so every workflow execution was filtered out of the\n * very table AGL-2171 built — the Runs dialog on the Workflows tab read\n * \"No runs yet\" however many times a workflow had run. The `durationMs`\n * caption in that table could never render either, because the only rows\n * carrying a duration were the ones being dropped.\n *\n * `status` stays: the dashboard activity feed renders it, and removing\n * it would trade one silent gap for another.\n */\n await recordWorkflowRun(hostRef, {\n action,\n result: run.ok === false ? 'failed' : 'succeeded',\n trigger: event,\n ...runSummaryFields(\n run.ok === false ? String(run.error).slice(0, 300) : 'Ran',\n ),\n status: run.ok === false ? 'error' : 'ok',\n durationMs,\n target: { type: 'workflow', id: doc.id, name: workflow.name ?? '' },\n })\n }\n // Filtered-out workflows do not bill — only executed runs count.\n await recordRuns({ ...meter, count: executed })\n } catch (error) {\n console.error('runEventWorkflows failed', hostId, event, error)\n }\n return alerts\n}\n\n/**\n * Continues a WORKFLOW's enrollment from where its wait ended — the\n * workflow twin of the action resume, and asked the same questions.\n *\n * - The kill switch is the workflow document: deleted, and the people inside\n * it stop, exactly as they do when an action is deleted or switched off.\n * - The plan is re-asked: a wait is an Actions step, so a workspace whose\n * plan has lost the actions builder stops the flow rather than finishing\n * it on a plan that no longer carries it.\n * - The snapshot runs, not the workflow's current steps, and the results the\n * function calls bound before the wait ride in its payload.\n * - Counted on the workflow meter, never refused by it: the person is already\n * inside, and the gate belongs at enrollment.\n */\nexport async function resumeWorkflowEnrollment(\n enrollment: FlowEnrollment,\n ref: FirebaseFirestore.DocumentReference,\n options: { timedOut?: boolean; nowMs: number },\n): Promise<'ran' | 'waiting' | 'exited' | 'deferred' | 'stopped'> {\n const { nowMs } = options\n const hostId = enrollment.hostId\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const doc = await hostRef\n .collection('workflows')\n .doc(enrollment.actionId)\n .get()\n .catch(() => null)\n if (!doc?.exists || doc.get('deletedAt')) {\n return await stopFlowEnrollment(\n enrollment,\n ref,\n 'the workflow was deleted',\n )\n }\n const workflow = doc.data() as AutomationWorkflow\n const owner = await getOrgForHost(hostId).catch(() => null)\n if (!checkEntitlement(owner?.org as any, 'actions')) {\n return await stopFlowEnrollment(\n enrollment,\n ref,\n 'this site’s plan no longer includes automations',\n )\n }\n const env = automationRunEnv({ hostId, hostRef, owner, depth: 0 })\n const payload: HostEventPayload = {\n ...((enrollment.payload ?? {}) as HostEventPayload),\n // The timeout BRANCH, as on an action's resume: the step after a\n // `waitForEvent` reads it to tell the clock from the event.\n ...(options.timedOut ? { [FLOW_TIMED_OUT_FIELD]: true } : {}),\n }\n const startedAt = Date.now()\n const execution = await executeWorkflow(\n env,\n { kind: 'workflow', id: doc.id, name: workflow.name ?? '' },\n workflow,\n enrollment.event,\n payload,\n {\n startIndex: enrollment.nextStepIndex,\n steps: enrollment.steps,\n enrollmentRef: ref,\n },\n )\n if (execution.ending === 'deferred') {\n await deferFlowEnrollment(ref, nowMs + FLOW_CLAIM_RETRY_MS, nowMs)\n return execution.ending\n }\n if (execution.ending !== 'waiting') await endFlowEnrollment(ref)\n await recordWorkflowRun(\n hostRef,\n workflowRunRow(execution, {\n event: enrollment.event,\n workflowId: doc.id,\n workflowName: workflow.name ?? '',\n durationMs: Date.now() - startedAt,\n }),\n )\n await recordRuns({\n firestore,\n hostRef,\n orgId: owner?.orgId,\n counter: 'workflowRuns',\n month: runMonthKey(nowMs),\n count: 1,\n })\n return execution.ending\n}\n\nexport default runEventWorkflows\n"],"names":["checkEntitlement","evaluateExpression","resolveOrgEntitlements","activitySearchTokens","triggerFilterProblem","firebaseAdmin","getOrgForHost","FieldValue","runSummaryFields","ACTION_MAX_EVENT_DEPTH","runWorkflow","eventRunSuspension","recordRuns","runMonthKey","runsUsedThisMonth","deferFlowEnrollment","endFlowEnrollment","automationRunEnv","executeWorkflow","FLOW_CLAIM_RETRY_MS","SKIP_LOG_EXCLUDED_EVENTS","stopFlowEnrollment","workflowHasActionSteps","runTriggeredByFields","triggeredDocsForEvent","FLOW_TIMED_OUT_FIELD","MAX_TRIGGERED_WORKFLOWS","recordWorkflowRun","hostRef","row","collection","add","actorId","actorEmail","searchTokens","target","createdAt","serverTimestamp","catch","undefined","workflowRunRow","execution","input","failed","errors","length","action","event","join","slice","ending","result","trigger","outcomes","status","durationMs","type","id","workflowId","name","workflowName","runEventWorkflows","hostId","payload","depth","alerts","firestore","app","doc","workflows","keep","get","max","maxReads","allWorkflowDocs","limit","workflowMap","docs","data","deletedAt","withId","$id","owner","meter","orgId","counter","month","org","workflowRunsPerMonth","used","functionDocs","variableDocs","Promise","all","functions","definition","variables","variable","executed","workflow","filter","trim","unrunnable","remedy","has","scope","startedAt","Date","now","context","env","loadWorkflowContext","kind","run","ok","error","String","count","console","resumeWorkflowEnrollment","enrollment","ref","options","nowMs","actionId","exists","timedOut","startIndex","nextStepIndex","steps","enrollmentRef"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,kBAAkB,EAIlBC,sBAAsB,QACjB,sBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,yCAAwC;AAC7E,SAASC,oBAAoB,QAAQ,2CAA0C;AAC/E,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AAEvE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,gBAAgB,QAAQ,0BAAsB;AACvD,SAASC,sBAAsB,EAAqBC,WAAW,QAAQ,wBAAoB;AAC3F,SAASC,kBAAkB,QAAQ,uBAAmB;AACtD,SACEC,UAAU,EAEVC,WAAW,EACXC,iBAAiB,QACZ,iBAAa;AACpB,SACEC,mBAAmB,EACnBC,iBAAiB,QAEZ,wBAAoB;AAC3B,SACEC,gBAAgB,EAChBC,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,KAAKE,QAAQxG,qBAAqBwG;QAC5D,OAAOlF,UAAUS,MAAM;IACzB;IACA,IAAIT,UAAUS,MAAM,KAAK,WAAW,MAAMlC,kBAAkByG;IAC5D,MAAM9F,kBACJC,SACAY,eAAeC,WAAW;QACxBM,OAAOyE,WAAWzE,KAAK;QACvBW,YAAYU,IAAIX,EAAE;QAClBG,YAAY,GAAEuC,kBAAAA,SAASxC,IAAI,YAAbwC,kBAAiB;QAC/B5C,YAAYoD,KAAKC,GAAG,KAAKF;IAC3B;IAEF,MAAM9F,WAAW;QACfsD;QACAtC;QACAwD,KAAK,EAAEF,yBAAAA,MAAOE,KAAK;QACnBC,SAAS;QACTC,OAAOzE,YAAY8G;QACnBN,OAAO;IACT;IACA,OAAO5E,UAAUS,MAAM;AACzB;AAEA,eAAeW,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/engine/run-event-workflows.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n checkEntitlement,\n evaluateExpression,\n type HostEventType,\n type HostFunction,\n type HostVariable,\n resolveOrgEntitlements,\n} from '@aglyn/aglyn/server'\nimport { activitySearchTokens } from '@aglyn/aglyn/app-utils/activity-search'\n// By its own module, not the server barrel: specs stub the barrel with a\n// partial object, and the run overage question is the plan table's to answer.\nimport { runOverageSold } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { triggerFilterProblem } from '@aglyn/aglyn/app-utils/site-interactions'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport type { HostEventPayload } from '@aglyn/tenant-runtime/host-event-listeners'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { runSummaryFields } from '../model/run-history'\nimport { ACTION_MAX_EVENT_DEPTH, type HostWorkflow, runWorkflow } from '../model/workflows'\nimport { eventRunSuspension } from './site-suspension'\nimport {\n recordRuns,\n type RunMeterScope,\n runMonthKey,\n runsUsedThisMonth,\n} from './run-meter'\nimport {\n deferFlowEnrollment,\n endFlowEnrollment,\n type FlowEnrollment,\n} from './flow-enrollments'\nimport {\n automationRunEnv,\n executeWorkflow,\n FLOW_CLAIM_RETRY_MS,\n SKIP_LOG_EXCLUDED_EVENTS,\n stopFlowEnrollment,\n type WorkflowContext,\n type WorkflowExecution,\n} from './run-event-actions'\nimport {\n type AutomationWorkflow,\n workflowHasActionSteps,\n} from './workflow-steps'\nimport { runTriggeredByFields } from './run-trigger-actor'\nimport { triggeredDocsForEvent } from './triggered-docs'\nimport { FLOW_TIMED_OUT_FIELD, type HostActionAlert } from '../model/host-actions'\n\n/**\n * Every live workflow on the event runs, in document-id order, up to this\n * many (AGL-3458) — the hundred the workflow map below already reads, so a\n * workflow the map can see is one its event can start. See\n * `triggered-docs.ts` for why the dispatch pages rather than truncates.\n */\nconst MAX_TRIGGERED_WORKFLOWS = 100\n\n/**\n * One workflow run's row in the site's activity feed, which is the run\n * history the Workflows tab reads.\n *\n * The one place a workflow's run is written, whichever door started it.\n */\nasync function recordWorkflowRun(\n hostRef: FirebaseFirestore.DocumentReference,\n row: Record<string, unknown>,\n): Promise<void> {\n await hostRef\n .collection('activity')\n .add({\n actorId: null,\n actorEmail: null,\n // Who set this run off (AGL-3376).\n ...runTriggeredByFields(),\n ...row,\n // The site log's search finds a run by its workflow's name (AGL-3321).\n searchTokens: activitySearchTokens({\n target: row['target'] as { name?: unknown } | undefined,\n }),\n createdAt: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n}\n\n/**\n * The history row for a run of a workflow with Actions steps, in the Actions\n * run's phrasing (AGL-2171) — what each step did, joined — so the run table\n * shows every step's outcome whichever engine the step came from. `status`\n * and `durationMs` ride along as they do on every workflow run, for the\n * dashboard feed that renders them.\n */\nexport function workflowRunRow(\n execution: Pick<WorkflowExecution, 'ending' | 'errors' | 'outcomes'>,\n input: {\n event: string\n workflowId: string\n workflowName: string\n durationMs: number\n },\n): Record<string, unknown> {\n const failed = execution.errors.length > 0\n const action = failed\n ? `Workflow ran on ${input.event} with errors: ${execution.errors.join('; ')}`.slice(\n 0,\n 300,\n )\n : execution.ending === 'waiting'\n ? `Workflow is waiting, on ${input.event}`\n : `Workflow ran on ${input.event}`\n return {\n action,\n result: failed ? 'failed' : 'succeeded',\n trigger: input.event,\n // The summary and its search tokens, written together (AGL-3321).\n ...runSummaryFields(\n (execution.outcomes.length\n ? execution.outcomes.join(' · ')\n : 'Ran'\n ).slice(0, 300),\n ),\n status: failed ? 'error' : 'ok',\n durationMs: input.durationMs,\n target: {\n type: 'workflow',\n id: input.workflowId,\n name: input.workflowName,\n },\n }\n}\n\n/**\n * Event-triggered workflow runner (AGL-128): loads workflows whose\n * `trigger.event` matches, evaluates optional trigger filters over the\n * event payload, runs each, and logs runs to the host activity feed.\n * Fire-and-forget from the tenant's event sites (form submit, pageview\n * collector, membership APIs) — it never throws, and a failure must not\n * break the request that emitted the event.\n *\n * A workflow of function calls runs through the pure `runWorkflow`\n * evaluator exactly as it always has. A workflow with Actions steps runs\n * through `executeWorkflow`, which performs them with the Actions executors;\n * the site alerts its steps raise are what this resolves.\n *\n * ONE RUN, METERED ONCE: either kind counts one run on the workflow meter,\n * `workflowRunsPerMonth`, however many steps it has and whatever they are.\n * Its Actions steps take the Actions tier gates step by step, and none of\n * them counts an action run.\n *\n * `depth` is the chain guard actions run under (`ACTION_MAX_EVENT_DEPTH`):\n * an event a workflow's own step raised — a stage it set — is heard one\n * level deeper, so a workflow that sets the stage it listens for stops.\n */\nexport async function runEventWorkflows(\n hostId: string,\n event: HostEventType,\n payload: HostEventPayload = {},\n depth = 0,\n): Promise<HostActionAlert[]> {\n const alerts: HostActionAlert[] = []\n if (depth > ACTION_MAX_EVENT_DEPTH) return alerts\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const workflows = await triggeredDocsForEvent(hostRef.collection('workflows'), event, {\n keep: (doc) => !doc.get('deletedAt'),\n max: MAX_TRIGGERED_WORKFLOWS,\n maxReads: MAX_TRIGGERED_WORKFLOWS * 4,\n })\n if (!workflows.length) return alerts\n // Full workflow map for nested function→workflow calls (AGL-129).\n const allWorkflowDocs = await hostRef\n .collection('workflows')\n .limit(100)\n .get()\n // Double-keyed by doc id AND name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n // Each carries its id, so a workflow a step names by its legacy name\n // still runs as the automation it is (see `WorkflowContext`).\n const workflowMap: WorkflowContext['workflows'] = {}\n for (const doc of allWorkflowDocs.docs) {\n const data = doc.data() as any\n if (data.deletedAt) continue\n const withId = { ...data, $id: doc.id }\n workflowMap[doc.id] = withId\n if (data?.name) workflowMap[data.name] = withId\n }\n\n // Monthly run cap by the owning org's plan (AGL-165).\n // Run caps ride the owning org's doc (AGL-238) — read through\n // `getOrgForHost` below. The host document itself is not consulted: the\n // cap, the counter and the workflow definitions all live elsewhere, so a\n // read of it here would be billed on every host event and used for\n // nothing.\n const owner = await getOrgForHost(hostId)\n // The band is the WORKSPACE's (AGL-3472): every site's runs count\n // against it, read off the org's counter — see `run-meter.ts`.\n const meter: RunMeterScope = {\n firestore,\n hostRef,\n orgId: owner?.orgId,\n counter: 'workflowRuns',\n month: runMonthKey(),\n }\n // A suspended site runs nothing (AGL-3356): see `eventRunSuspension`.\n // Asked before the cap so a locked site's events bill no runs.\n if (await eventRunSuspension(hostRef, owner?.org)) return alerts\n {\n const org = owner?.org\n // Plan-less orgs resolve as free (AGL-247) — the cap always runs.\n const limit = resolveOrgEntitlements(\n org as any,\n ).workflowRunsPerMonth\n const used = await runsUsedThisMonth(meter)\n // Past the band is a wall only where the plan sells no runs past it\n // (pricing v4): on a plan with a run rate the workflows run, and the\n // excess bills on the month's invoice (`priceRunOverage`).\n if (used + workflows.length > limit && !runOverageSold(org as any)) {\n return alerts\n }\n }\n\n const [functionDocs, variableDocs] = await Promise.all([\n hostRef.collection('functions').limit(100).get(),\n hostRef.collection('variables').limit(100).get(),\n ])\n const functions: Record<string, HostFunction> = {}\n for (const doc of functionDocs.docs) {\n const definition = doc.data() as any\n if (definition.deletedAt) continue\n functions[doc.id] = definition\n if (definition.name) functions[definition.name] = definition\n }\n const variables: Record<string, HostVariable> = {}\n for (const doc of variableDocs.docs) {\n const variable = doc.data() as any\n if (!variable.deletedAt && variable.name) {\n variables[variable.name] = variable\n }\n }\n\n let executed = 0\n for (const doc of workflows) {\n const workflow = doc.data() as AutomationWorkflow\n const filter = workflow.trigger?.filter?.trim()\n if (filter) {\n /*\n * A filter no event can ever satisfy — a comparison the evaluator\n * does not have, text it cannot read — answers \"why didn't it run?\"\n * in the run history, on every event it would have run on, rather\n * than leaving the workflow silent. The editor refuses to save one;\n * this is the one stored before it did, or written around it.\n */\n const unrunnable = triggerFilterProblem(filter, { remedy: 'action' })\n if (unrunnable) {\n if (!SKIP_LOG_EXCLUDED_EVENTS.has(event)) {\n await recordWorkflowRun(hostRef, {\n action: `Workflow skipped on ${event}`,\n result: 'skipped',\n trigger: event,\n ...runSummaryFields(unrunnable.slice(0, 300)),\n target: { type: 'workflow', id: doc.id, name: workflow.name ?? '' },\n })\n }\n continue\n }\n try {\n const scope: HostEventPayload = { event, ...payload }\n if (!evaluateExpression(filter, scope)) continue\n } catch {\n continue // A field the filter names is not on this event.\n }\n }\n const startedAt = Date.now()\n if (workflowHasActionSteps(workflow)) {\n /*\n * A WORKFLOW WITH ACTIONS STEPS is performed, not evaluated. The\n * maps above are this run's working set, so the executor reads them\n * rather than a second copy; the plan gates come off the org\n * document the cap already read.\n */\n const context: WorkflowContext = {\n functions,\n variables,\n workflows: workflowMap,\n }\n const env = automationRunEnv({\n hostId,\n hostRef,\n owner,\n depth,\n alerts,\n loadWorkflowContext: async () => context,\n })\n const execution = await executeWorkflow(\n env,\n { kind: 'workflow', id: doc.id, name: workflow.name ?? '' },\n workflow,\n event,\n payload,\n )\n executed += 1\n await recordWorkflowRun(\n hostRef,\n workflowRunRow(execution, {\n event,\n workflowId: doc.id,\n workflowName: workflow.name ?? '',\n durationMs: Date.now() - startedAt,\n }),\n )\n continue\n }\n const run = runWorkflow(\n workflow as HostWorkflow,\n functions,\n variables,\n { event, ...payload },\n { workflows: workflowMap },\n )\n const durationMs = Date.now() - startedAt\n executed += 1\n // `=== false` (not `!run.ok`): the union fails to narrow under the\n // stricter build tsconfig otherwise (same quirk as runWorkflow).\n const action =\n run.ok === false\n ? `Workflow failed on ${event}: ${run.error}`.slice(0, 300)\n : `Workflow ran on ${event}`\n /*\n * The run-history shape, not just `status` + `durationMs` (AGL-2222).\n *\n * `actionRunResult()` recognises a run by `result`, falling back to the\n * prose prefix `Action ran on`. This writer's prose begins\n * `Workflow ran on`, so every workflow execution was filtered out of the\n * very table AGL-2171 built — the Runs dialog on the Workflows tab read\n * \"No runs yet\" however many times a workflow had run. The `durationMs`\n * caption in that table could never render either, because the only rows\n * carrying a duration were the ones being dropped.\n *\n * `status` stays: the dashboard activity feed renders it, and removing\n * it would trade one silent gap for another.\n */\n await recordWorkflowRun(hostRef, {\n action,\n result: run.ok === false ? 'failed' : 'succeeded',\n trigger: event,\n ...runSummaryFields(\n run.ok === false ? String(run.error).slice(0, 300) : 'Ran',\n ),\n status: run.ok === false ? 'error' : 'ok',\n durationMs,\n target: { type: 'workflow', id: doc.id, name: workflow.name ?? '' },\n })\n }\n // Filtered-out workflows do not bill — only executed runs count.\n await recordRuns({ ...meter, count: executed })\n } catch (error) {\n console.error('runEventWorkflows failed', hostId, event, error)\n }\n return alerts\n}\n\n/**\n * Continues a WORKFLOW's enrollment from where its wait ended — the\n * workflow twin of the action resume, and asked the same questions.\n *\n * - The kill switch is the workflow document: deleted, and the people inside\n * it stop, exactly as they do when an action is deleted or switched off.\n * - The plan is re-asked: a wait is an Actions step, so a workspace whose\n * plan has lost the actions builder stops the flow rather than finishing\n * it on a plan that no longer carries it.\n * - The snapshot runs, not the workflow's current steps, and the results the\n * function calls bound before the wait ride in its payload.\n * - Counted on the workflow meter, never refused by it: the person is already\n * inside, and the gate belongs at enrollment.\n */\nexport async function resumeWorkflowEnrollment(\n enrollment: FlowEnrollment,\n ref: FirebaseFirestore.DocumentReference,\n options: { timedOut?: boolean; nowMs: number },\n): Promise<'ran' | 'waiting' | 'exited' | 'deferred' | 'stopped'> {\n const { nowMs } = options\n const hostId = enrollment.hostId\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const doc = await hostRef\n .collection('workflows')\n .doc(enrollment.actionId)\n .get()\n .catch(() => null)\n if (!doc?.exists || doc.get('deletedAt')) {\n return await stopFlowEnrollment(\n enrollment,\n ref,\n 'the workflow was deleted',\n )\n }\n const workflow = doc.data() as AutomationWorkflow\n const owner = await getOrgForHost(hostId).catch(() => null)\n if (!checkEntitlement(owner?.org as any, 'actions')) {\n return await stopFlowEnrollment(\n enrollment,\n ref,\n 'this site’s plan no longer includes automations',\n )\n }\n const env = automationRunEnv({ hostId, hostRef, owner, depth: 0 })\n const payload: HostEventPayload = {\n ...((enrollment.payload ?? {}) as HostEventPayload),\n // The timeout BRANCH, as on an action's resume: the step after a\n // `waitForEvent` reads it to tell the clock from the event.\n ...(options.timedOut ? { [FLOW_TIMED_OUT_FIELD]: true } : {}),\n }\n const startedAt = Date.now()\n const execution = await executeWorkflow(\n env,\n { kind: 'workflow', id: doc.id, name: workflow.name ?? '' },\n workflow,\n enrollment.event,\n payload,\n {\n startIndex: enrollment.nextStepIndex,\n steps: enrollment.steps,\n enrollmentRef: ref,\n },\n )\n if (execution.ending === 'deferred') {\n await deferFlowEnrollment(ref, nowMs + FLOW_CLAIM_RETRY_MS, nowMs)\n return execution.ending\n }\n if (execution.ending !== 'waiting') await endFlowEnrollment(ref)\n await recordWorkflowRun(\n hostRef,\n workflowRunRow(execution, {\n event: enrollment.event,\n workflowId: doc.id,\n workflowName: workflow.name ?? '',\n durationMs: Date.now() - startedAt,\n }),\n )\n await recordRuns({\n firestore,\n hostRef,\n orgId: owner?.orgId,\n counter: 'workflowRuns',\n month: runMonthKey(nowMs),\n count: 1,\n })\n return execution.ending\n}\n\nexport default runEventWorkflows\n"],"names":["checkEntitlement","evaluateExpression","resolveOrgEntitlements","activitySearchTokens","runOverageSold","triggerFilterProblem","firebaseAdmin","getOrgForHost","FieldValue","runSummaryFields","ACTION_MAX_EVENT_DEPTH","runWorkflow","eventRunSuspension","recordRuns","runMonthKey","runsUsedThisMonth","deferFlowEnrollment","endFlowEnrollment","automationRunEnv","executeWorkflow","FLOW_CLAIM_RETRY_MS","SKIP_LOG_EXCLUDED_EVENTS","stopFlowEnrollment","workflowHasActionSteps","runTriggeredByFields","triggeredDocsForEvent","FLOW_TIMED_OUT_FIELD","MAX_TRIGGERED_WORKFLOWS","recordWorkflowRun","hostRef","row","collection","add","actorId","actorEmail","searchTokens","target","createdAt","serverTimestamp","catch","undefined","workflowRunRow","execution","input","failed","errors","length","action","event","join","slice","ending","result","trigger","outcomes","status","durationMs","type","id","workflowId","name","workflowName","runEventWorkflows","hostId","payload","depth","alerts","firestore","app","doc","workflows","keep","get","max","maxReads","allWorkflowDocs","limit","workflowMap","docs","data","deletedAt","withId","$id","owner","meter","orgId","counter","month","org","workflowRunsPerMonth","used","functionDocs","variableDocs","Promise","all","functions","definition","variables","variable","executed","workflow","filter","trim","unrunnable","remedy","has","scope","startedAt","Date","now","context","env","loadWorkflowContext","kind","run","ok","error","String","count","console","resumeWorkflowEnrollment","enrollment","ref","options","nowMs","actionId","exists","timedOut","startIndex","nextStepIndex","steps","enrollmentRef"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,kBAAkB,EAIlBC,sBAAs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F,iBAAiB;QAAE6C;QAAQlC;QAASsD;QAAOlB,OAAO;IAAE;IAChE,MAAMD,UAA4B,cAC3ByD,sBAAAA,WAAWzD,OAAO,YAAlByD,sBAAsB,CAAC,GAGxBE,QAAQI,QAAQ,GAAG;QAAE,CAACrG,qBAAqB,EAAE;IAAK,IAAI,CAAC;IAE7D,MAAMiF,YAAYC,KAAKC,GAAG;IAC1B,MAAMnE,YAAY,MAAMvB,gBACtB4F,KACA;QAAEE,MAAM;QAAYvD,IAAIW,IAAIX,EAAE;QAAEE,IAAI,GAAEwC,iBAAAA,SAASxC,IAAI,YAAbwC,iBAAiB;IAAG,GAC1DA,UACAqB,WAAWzE,KAAK,EAChBgB,SACA;QACEgE,YAAYP,WAAWQ,aAAa;QACpCC,OAAOT,WAAWS,KAAK;QACvBC,eAAeT;IACjB;IAEF,IAAIhF,UAAUS,MAAM,KAAK,YAAY;QACnC,MAAMnC,oBAAoB0G,KAAKE,QAAQxG,qBAAqBwG;QAC5D,OAAOlF,UAAUS,MAAM;IACzB;IACA,IAAIT,UAAUS,MAAM,KAAK,WAAW,MAAMlC,kBAAkByG;IAC5D,MAAM9F,kBACJC,SACAY,eAAeC,WAAW;QACxBM,OAAOyE,WAAWzE,KAAK;QACvBW,YAAYU,IAAIX,EAAE;QAClBG,YAAY,GAAEuC,kBAAAA,SAASxC,IAAI,YAAbwC,kBAAiB;QAC/B5C,YAAYoD,KAAKC,GAAG,KAAKF;IAC3B;IAEF,MAAM9F,WAAW;QACfsD;QACAtC;QACAwD,KAAK,EAAEF,yBAAAA,MAAOE,KAAK;QACnBC,SAAS;QACTC,OAAOzE,YAAY8G;QACnBN,OAAO;IACT;IACA,OAAO5E,UAAUS,MAAM;AACzB;AAEA,eAAeW,kBAAiB"}
|
|
@@ -25,7 +25,7 @@ import type { HostActionStepType } from './host-actions';
|
|
|
25
25
|
* exactly that shape — `Sent email · saved to Leads · webhook 200`.
|
|
26
26
|
*
|
|
27
27
|
* Two maps rather than one derived from the other, because "Send a webhook
|
|
28
|
-
* (
|
|
28
|
+
* (Pro)" cannot be mechanically turned into "webhook" — the plan
|
|
29
29
|
* suffix is part of the picker's label and has no business in a log line.
|
|
30
30
|
* Only the steps a SERVER run can perform appear here; the client-side
|
|
31
31
|
* steps run in the visitor's browser and never reach the activity write.
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* exactly that shape — `Sent email · saved to Leads · webhook 200`.
|
|
24
24
|
*
|
|
25
25
|
* Two maps rather than one derived from the other, because "Send a webhook
|
|
26
|
-
* (
|
|
26
|
+
* (Pro)" cannot be mechanically turned into "webhook" — the plan
|
|
27
27
|
* suffix is part of the picker's label and has no business in a log line.
|
|
28
28
|
* Only the steps a SERVER run can perform appear here; the client-side
|
|
29
29
|
* steps run in the visitor's browser and never reach the activity write.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/model/step-outcomes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostActionStepType } from './host-actions'\n\n/**\n * Past-tense phrases for a run summary (AGL-2171).\n *\n * `HOST_ACTION_STEP_LABELS` (`host-actions.ts`) names what a step WILL do, in the\n * imperative, for a `Do` select — \"Send an email\". A run history is the\n * opposite tense and a different audience: it says what already happened,\n * on one line, several steps at a time. `/product/workflows` advertises\n * exactly that shape — `Sent email · saved to Leads · webhook 200`.\n *\n * Two maps rather than one derived from the other, because \"Send a webhook\n * (
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/model/step-outcomes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostActionStepType } from './host-actions'\n\n/**\n * Past-tense phrases for a run summary (AGL-2171).\n *\n * `HOST_ACTION_STEP_LABELS` (`host-actions.ts`) names what a step WILL do, in the\n * imperative, for a `Do` select — \"Send an email\". A run history is the\n * opposite tense and a different audience: it says what already happened,\n * on one line, several steps at a time. `/product/workflows` advertises\n * exactly that shape — `Sent email · saved to Leads · webhook 200`.\n *\n * Two maps rather than one derived from the other, because \"Send a webhook\n * (Pro)\" cannot be mechanically turned into \"webhook\" — the plan\n * suffix is part of the picker's label and has no business in a log line.\n * Only the steps a SERVER run can perform appear here; the client-side\n * steps run in the visitor's browser and never reach the activity write.\n */\nexport const HOST_ACTION_STEP_OUTCOMES: Partial<\n Record<HostActionStepType, string>\n> = {\n runWorkflow: 'ran workflow',\n siteAlert: 'showed an alert',\n customEvent: 'fired an event',\n datasetAppend: 'saved to dataset',\n updateDataset: 'updated dataset',\n webhookPost: 'webhook',\n sendEmail: 'sent email',\n notifyAdmins: 'notified admins',\n enrollList: 'enrolled in list',\n assignCampaign: 'assigned to campaign',\n wait: 'waiting',\n waitForEvent: 'waiting for',\n exitFlow: 'ended the flow',\n setContactStage: 'set stage',\n addContactTag: 'tagged',\n assignContactOwner: 'assigned owner',\n createCrmTask: 'created task',\n logCrmActivity: 'logged activity',\n}\n\n/**\n * One step's line in a run summary, with the detail that makes it useful.\n *\n * `saved to Leads` beats `saved to dataset`, and `webhook 200` beats\n * `webhook` — the status code is the entire reason anyone opens a run\n * history after a webhook, and it was being discarded on the line it\n * arrived.\n */\nexport function describeStepOutcome(\n type: HostActionStepType,\n detail?: string,\n): string {\n const base = HOST_ACTION_STEP_OUTCOMES[type] ?? String(type)\n const trimmed = detail?.trim()\n if (!trimmed) return base\n if (type === 'datasetAppend' || type === 'updateDataset') {\n // `saved to dataset` + `Leads` reads as `saved to Leads`, not\n // `saved to dataset Leads`.\n return `${base.replace(/ dataset$/, '')} ${trimmed}`\n }\n return `${base} ${trimmed}`\n}\n"],"names":["HOST_ACTION_STEP_OUTCOMES","runWorkflow","siteAlert","customEvent","datasetAppend","updateDataset","webhookPost","sendEmail","notifyAdmins","enrollList","assignCampaign","wait","waitForEvent","exitFlow","setContactStage","addContactTag","assignContactOwner","createCrmTask","logCrmActivity","describeStepOutcome","type","detail","base","String","trimmed","trim","replace"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID;;;;;;;;;;;;;;CAcC,GACD,OAAO,MAAMA,4BAET;IACFC,aAAa;IACbC,WAAW;IACXC,aAAa;IACbC,eAAe;IACfC,eAAe;IACfC,aAAa;IACbC,WAAW;IACXC,cAAc;IACdC,YAAY;IACZC,gBAAgB;IAChBC,MAAM;IACNC,cAAc;IACdC,UAAU;IACVC,iBAAiB;IACjBC,eAAe;IACfC,oBAAoB;IACpBC,eAAe;IACfC,gBAAgB;AAClB,EAAC;AAED;;;;;;;CAOC,GACD,OAAO,SAASC,oBACdC,IAAwB,EACxBC,MAAe;QAEFrB;IAAb,MAAMsB,QAAOtB,kCAAAA,yBAAyB,CAACoB,KAAK,YAA/BpB,kCAAmCuB,OAAOH;IACvD,MAAMI,UAAUH,0BAAAA,OAAQI,IAAI;IAC5B,IAAI,CAACD,SAAS,OAAOF;IACrB,IAAIF,SAAS,mBAAmBA,SAAS,iBAAiB;QACxD,8DAA8D;QAC9D,4BAA4B;QAC5B,OAAO,GAAGE,KAAKI,OAAO,CAAC,aAAa,IAAI,CAAC,EAAEF,SAAS;IACtD;IACA,OAAO,GAAGF,KAAK,CAAC,EAAEE,SAAS;AAC7B"}
|
package/src/lib/server.js
CHANGED
|
@@ -17,6 +17,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
17
17
|
*/ import { checkEntitlement, resolveOrgEntitlements } from "@aglyn/aglyn/server";
|
|
18
18
|
import { registerPluginApiRoute, registerPluginJob } from "@aglyn/aglyn/server";
|
|
19
19
|
import { activitySearchTokens } from "@aglyn/aglyn/app-utils/activity-search";
|
|
20
|
+
// By its own module, as the event gates read it.
|
|
21
|
+
import { runOverageSold } from "@aglyn/aglyn/app-utils/plan-entitlements";
|
|
20
22
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
21
23
|
import { timingSafeEqual } from "crypto";
|
|
22
24
|
import { FieldValue } from "firebase-admin/firestore";
|
|
@@ -187,7 +189,9 @@ function secretsMatch(expected, provided) {
|
|
|
187
189
|
};
|
|
188
190
|
const runLimit = resolveOrgEntitlements(org).workflowRunsPerMonth;
|
|
189
191
|
const runsUsed = await runsUsedThisMonth(meter);
|
|
190
|
-
|
|
192
|
+
// A wall only where the plan sells no runs past the band (pricing v4,
|
|
193
|
+
// `runOverageSold`); otherwise the run goes ahead and the excess bills.
|
|
194
|
+
if (!(runsUsed + 1 <= runLimit) && !runOverageSold(org)) {
|
|
191
195
|
return res.status(402).json({
|
|
192
196
|
error: `This workspace has used its ${runLimit} workflow runs for the month`
|
|
193
197
|
});
|
package/src/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n checkEntitlement,\n type HostFunction,\n type HostVariable,\n resolveOrgEntitlements,\n} from '@aglyn/aglyn/server'\nimport {\n registerPluginApiRoute,\n registerPluginJob,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { activitySearchTokens } from '@aglyn/aglyn/app-utils/activity-search'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { timingSafeEqual } from 'crypto'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { runSummaryFields } from './model/run-history'\nimport { type HostWorkflow, runWorkflow } from './model/workflows'\nimport type { HostWebhook } from './model/webhooks'\nimport { eventRunSuspension } from './engine/site-suspension'\nimport {\n recordRuns,\n type RunMeterScope,\n runMonthKey,\n runsUsedThisMonth,\n} from './engine/run-meter'\nimport { BUNDLE_ID as WORKFLOWS_BUNDLE_ID } from './constants/bundle-common'\nimport { registerWorkflowsServerDeclarations } from './declarations.server'\nimport {\n automationRunEnv,\n executeWorkflow,\n runDueFlowEnrollments,\n workflowContextFromDocs,\n} from './engine/run-event-actions'\nimport {\n type AutomationWorkflow,\n workflowHasActionSteps,\n} from './engine/workflow-steps'\n\n/*==========================================\n * THE BEAT THAT MAKES A WAIT STEP REAL.\n *\n * A `wait` step suspends a run into a `flowEnrollments` row and returns; this\n * is the only thing that ever comes back for it. Without a registration here\n * the wait step would be a delay that never ends — the exact failure\n * `process-abandoned.ts` documents next door, where a Pro entitlement sat\n * behind an HTTP door nothing ever POSTed to.\n *\n * Module scope, like the commerce and bookings registrations: the runner\n * route reaches plugin jobs through `ensureAll(['tenantApi'])`, so a\n * registration inside `registerWorkflowsApi()` would depend on which entry\n * point happened to be loaded.\n *\n * ## Every minute, and why that is cheap\n *\n * `FLOW_WAIT_MIN_MINUTES` is one, so the beat has to be one — a fifteen-minute\n * sweep would make the shortest wait anybody can author wrong by up to\n * fourteen minutes. It costs one collection-group query per minute, which\n * returns nothing at all on a platform with no flow due, because the query\n * asks for `resumeAtMs <= now` rather than for the enrolled population.\n *\n * Bounded and idempotent, the two properties the runner requires: the scan\n * budget bounds one pass, and a transactional claim means an overlapping or\n * repeated beat cannot run the same person's step twice.\n *=========================================*/\nregisterPluginJob({\n pluginId: WORKFLOWS_BUNDLE_ID,\n name: 'resume-flow-waits',\n intervalMinutes: 1,\n description:\n 'Continue automations whose wait step has ended, and time out those ' +\n 'waiting for an event that never arrived.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n await runDueFlowEnrollments(gate)\n },\n})\n\n// Best-effort per-instance rate limit (mirrors forms/submit).\nconst recentByHook = new Map<string, number[]>()\nconst RATE_WINDOW_MS = 60_000\nconst RATE_MAX = 30\n\nfunction rateLimited(key: string): boolean {\n const now = Date.now()\n const hits = (recentByHook.get(key) ?? []).filter(\n (t) => now - t < RATE_WINDOW_MS,\n )\n hits.push(now)\n recentByHook.set(key, hits)\n return hits.length > RATE_MAX\n}\n\nfunction secretsMatch(expected: string, provided: string): boolean {\n if (!expected || expected.length !== provided.length) return false\n return timingSafeEqual(\n new Uint8Array(Buffer.from(expected)),\n new Uint8Array(Buffer.from(provided)),\n )\n}\n\n/**\n * Inbound webhook endpoint (AGL-149): external systems POST JSON to\n * `/api/hooks/{hostId}/{hookId}` with the hook's secret in\n * `x-aglyn-secret`; a valid call enrolls the configured workflow with the\n * payload's top-level primitives in scope. Business tier (`webhooks`\n * flag); runs bill against the workflow-runs meter like any other run —\n * `workflowRunsPerMonth` is checked against the workspace's runs before the\n * run, and the site's and the workspace's counters are incremented after it\n * (AGL-2228, AGL-3472).\n */\nconst inboundHookHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query['hostId'] ?? '')\n const hookId = String(req.query['hookId'] ?? '')\n if (!hostId || !hookId) {\n return res.status(400).json({ error: 'Invalid webhook address' })\n }\n if (rateLimited(`${hostId}/${hookId}`)) {\n return res.status(429).json({ error: 'Too many requests' })\n }\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hookSnapshot = await hostRef.collection('webhooks').doc(hookId).get()\n const hook = hookSnapshot.data() as HostWebhook | undefined\n if (\n !hook ||\n hookSnapshot.get('deletedAt') ||\n hook.direction !== 'inbound' ||\n hook.enabled === false\n ) {\n return res.status(404).json({ error: 'Unknown webhook' })\n }\n const provided = String(req.headers['x-aglyn-secret'] ?? '')\n if (!secretsMatch(hook.secret ?? '', provided)) {\n return res.status(401).json({ error: 'Bad secret' })\n }\n\n // Plan/quota gates ride the owning org's doc (AGL-238).\n const owner = await getOrgForHost(hostId)\n const org = owner?.org\n /*\n * A suspended site takes no inbound run (AGL-3356). The tenant\n * dispatcher's lockdown gate reads `hostId` from the query or body, and\n * this route carries it in the PATH, so the engine's own question is\n * asked here. A 423 rather than a 200: the caller is an integration, and\n * one told a run happened keeps sending.\n */\n const suspended = await eventRunSuspension(hostRef, org)\n if (suspended) {\n return res.status(423).json({ error: 'locked', scope: suspended.scope })\n }\n if (!checkEntitlement(org as any, 'webhooks')) {\n return res\n .status(403)\n .json({ error: 'Webhooks are not enabled on this site' })\n }\n /*\n * The MONTHLY RUN CAP, which this handler's own docblock claimed for\n * years — \"runs bill against the workflow-runs meter like any other run\"\n * — and did not have. It read neither `workflowRunsPerMonth` nor\n * `hosts/{id}/counters/workflowRuns`, and it wrote neither, so an inbound\n * hook was a workflow execution that no cap could refuse and no meter\n * could see: the customer's usage card, the usage-alerts cron and the\n * COGS rollup all read a counter this path never moved.\n *\n * The refusal is a 402 rather than the silent `return` of\n * `runEventWorkflows`: that path is fired from a visitor request whose\n * success must not depend on the workflow, where this one is an\n * integration calling us on purpose and a caller that gets a 200 for a\n * run that did not happen will keep sending. `Retry-After` is deliberately\n * absent — the month, not a delay, is what clears this.\n *\n * The plan-less/unreadable org resolves as FREE\n * (`workflowRunsPerMonth: 0`), so an org doc we cannot read refuses rather\n * than runs. `checkEntitlement(webhooks)` above already refuses free on\n * today's price list; this is not a second gate on the same fact, because\n * a staff `entitlementOverrides` can grant `webhooks` without granting\n * runs, and because the cap is what bounds a BUSINESS org's spend.\n *\n * Read-then-write, like the event path, and bounded the same way: the\n * per-hook limiter above is 30/60s, so the overshoot a race can buy is\n * bounded by concurrency rather than unbounded by design. Making it\n * atomic means a transaction around the whole run and is the same trade\n * `runEventWorkflows` declined.\n */\n // The band is the WORKSPACE's (AGL-3472), so the count it is held to is\n // every site's runs, off the org's counter — see `run-meter.ts`.\n const meter: RunMeterScope = {\n firestore,\n hostRef,\n orgId: owner?.orgId,\n counter: 'workflowRuns',\n month: runMonthKey(),\n }\n const runLimit = resolveOrgEntitlements(org as any).workflowRunsPerMonth\n const runsUsed = await runsUsedThisMonth(meter)\n if (!(runsUsed + 1 <= runLimit)) {\n return res.status(402).json({\n error: `This workspace has used its ${runLimit} workflow runs for the month`,\n })\n }\n\n // Top-level primitives from the JSON body join the workflow scope.\n const body =\n typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n const scope: Record<string, string | number | boolean> = {}\n for (const [key, value] of Object.entries(body)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n scope[key.slice(0, 64)] =\n typeof value === 'string' ? value.slice(0, 2000) : value\n }\n }\n\n const [functionDocs, variableDocs, workflowDocs] = await Promise.all([\n hostRef.collection('functions').limit(100).get(),\n hostRef.collection('variables').limit(100).get(),\n hostRef.collection('workflows').limit(100).get(),\n ])\n const byName = <T extends { name?: string; deletedAt?: unknown }>(\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n ) => {\n const map: Record<string, T> = {}\n for (const doc of docs) {\n const data = doc.data() as T\n if (data?.name && !data.deletedAt) map[data.name] = data\n }\n return map\n }\n const workflows = byName<HostWorkflow>(workflowDocs.docs)\n const workflow = workflows[hook.workflowName?.trim() ?? '']\n if (!workflow) {\n return res.status(422).json({ error: 'No workflow bound to this hook' })\n }\n\n const hookEvent = `hook:${hook.name ?? hookId}`\n /*\n * A workflow of function calls is evaluated, as it always has been. One\n * with Actions steps is PERFORMED by the engine's executor — the posted\n * JSON is its payload — under the Actions tier gates, step by step, and\n * it is still one run on the meter below. Its working set is built from\n * the documents read above rather than read again.\n */\n const outcome: { error: string | null; value: unknown; summary: string } =\n workflowHasActionSteps(workflow)\n ? await (async () => {\n const workflowDoc = workflowDocs.docs.find(\n (doc) =>\n !doc.get('deletedAt') &&\n doc.get('name') === hook.workflowName?.trim(),\n )\n const execution = await executeWorkflow(\n automationRunEnv({\n hostId,\n hostRef,\n owner,\n depth: 0,\n loadWorkflowContext: async () =>\n workflowContextFromDocs(\n functionDocs.docs,\n variableDocs.docs,\n workflowDocs.docs,\n ),\n }),\n {\n kind: 'workflow',\n id: workflowDoc?.id ?? '',\n name: workflow.name ?? '',\n },\n workflow as AutomationWorkflow,\n hookEvent,\n scope,\n )\n return {\n error: execution.errors.length\n ? execution.errors.join('; ')\n : null,\n value: execution.value,\n summary: execution.outcomes.length\n ? execution.outcomes.join(' · ')\n : `Ran ${hook.workflowName}`,\n }\n })()\n : (() => {\n const run = runWorkflow(\n workflow,\n byName<HostFunction>(functionDocs.docs),\n byName<HostVariable>(variableDocs.docs),\n { event: hookEvent, ...scope },\n { workflows },\n )\n return run.ok === false\n ? { error: run.error, value: undefined, summary: '' }\n : {\n error: null,\n value: run.value,\n summary: `Ran ${hook.workflowName}`,\n }\n })()\n const failed = outcome.error !== null\n await hostRef\n .collection('activity')\n .add({\n actorId: null,\n actorEmail: null,\n // An outside system called the hook's URL; the hook is who it was.\n triggeredBy: { kind: 'webhook', name: hook.workflowName },\n action: failed\n ? `Inbound webhook run failed: ${outcome.error}`.slice(0, 300)\n : `Inbound webhook ran \"${hook.workflowName}\"`,\n // The run-history shape (AGL-2222) — without `result` this execution\n // is invisible to the Runs table, which reads a verdict and not prose.\n result: failed ? 'failed' : 'succeeded',\n trigger: hookEvent,\n ...runSummaryFields(\n failed\n ? String(outcome.error).slice(0, 300)\n : outcome.summary.slice(0, 300),\n ),\n target: { type: 'workflow', id: hookId, name: hook.name ?? '' },\n // The site log's search finds a run by its hook's name (AGL-3321).\n searchTokens: activitySearchTokens({ target: { name: hook.name } }),\n createdAt: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n // The run happened, so it counts — including a FAILED one, exactly as\n // `runEventWorkflows` counts its failures. A run that executed and threw\n // spent the same compute as one that returned a value; only a run that\n // never started (the cap above, a missing workflow) must not count.\n await recordRuns({ ...meter, count: 1 })\n\n if (failed) return res.status(422).json({ error: outcome.error })\n return res.status(200).json({ ok: true, value: outcome.value })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Webhook failed' })\n }\n}\n\n/**\n * Registers the workflows plugin's public API routes (AGL-396), and the\n * engine's host-event listener beside them for a process whose boot did not\n * (see `declarations.server.ts`).\n */\nexport function registerWorkflowsApi(): void {\n registerWorkflowsServerDeclarations()\n registerPluginApiRoute('hooks/[hostId]/[hookId]', inboundHookHandler)\n}\n\n/**\n * The console half (AGL-2919), re-exported so one entry point serves both\n * surfaces: the manifest generator resolves every server surface through\n * `@aglyn/plugins-workflows/server`, and a second entry point would be a second\n * thing to keep in step with plugins.config.json.\n */\nexport { registerWorkflowsConsoleApi } from './server-console'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { workflowsPlanEntitlements } from './plan-entitlements'\n"],"names":["checkEntitlement","resolveOrgEntitlements","registerPluginApiRoute","registerPluginJob","activitySearchTokens","firebaseAdmin","getOrgForHost","timingSafeEqual","FieldValue","runSummaryFields","runWorkflow","eventRunSuspension","recordRuns","runMonthKey","runsUsedThisMonth","BUNDLE_ID","WORKFLOWS_BUNDLE_ID","registerWorkflowsServerDeclarations","automationRunEnv","executeWorkflow","runDueFlowEnrollments","workflowContextFromDocs","workflowHasActionSteps","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","recentByHook","Map","RATE_WINDOW_MS","RATE_MAX","rateLimited","key","now","Date","hits","get","filter","t","push","set","length","secretsMatch","expected","provided","Uint8Array","Buffer","from","inboundHookHandler","req","res","method","status","json","error","hostId","String","query","hookId","hook","firestore","app","hostRef","collection","doc","hookSnapshot","data","direction","enabled","headers","secret","owner","org","suspended","meter","orgId","counter","month","runLimit","workflowRunsPerMonth","runsUsed","body","JSON","parse","value","Object","entries","slice","functionDocs","variableDocs","workflowDocs","Promise","all","limit","byName","docs","map","deletedAt","workflows","workflow","workflowName","trim","hookEvent","outcome","workflowDoc","find","execution","depth","loadWorkflowContext","kind","id","errors","join","summary","outcomes","run","event","ok","undefined","failed","add","actorId","actorEmail","triggeredBy","action","result","trigger","target","type","searchTokens","createdAt","serverTimestamp","catch","count","console","registerWorkflowsApi","registerWorkflowsConsoleApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAGhBC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,sBAAsB,EACtBC,iBAAiB,QAEZ,sBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,yCAAwC;AAC7E,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,SAAQ;AACxC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,gBAAgB,QAAQ,yBAAqB;AACtD,SAA4BC,WAAW,QAAQ,uBAAmB;AAElE,SAASC,kBAAkB,QAAQ,8BAA0B;AAC7D,SACEC,UAAU,EAEVC,WAAW,EACXC,iBAAiB,QACZ,wBAAoB;AAC3B,SAASC,aAAaC,mBAAmB,QAAQ,+BAA2B;AAC5E,SAASC,mCAAmC,QAAQ,2BAAuB;AAC3E,SACEC,gBAAgB,EAChBC,eAAe,EACfC,qBAAqB,EACrBC,uBAAuB,QAClB,gCAA4B;AACnC,SAEEC,sBAAsB,QACjB,6BAAyB;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;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AA,KAAKvC,IAAI,YAATuC,cAAa;YAAG;YAC9D,mEAAmE;YACnEsE,cAAcjI,qBAAqB;gBAAE+H,QAAQ;oBAAE3G,MAAMuC,KAAKvC,IAAI;gBAAC;YAAE;YACjE8G,WAAW9H,WAAW+H,eAAe;YAEtCC,KAAK,CAAC,IAAMd;QAEf,sEAAsE;QACtE,yEAAyE;QACzE,uEAAuE;QACvE,oEAAoE;QACpE,MAAM9G,WAAW,aAAKkE;YAAO2D,OAAO;;QAEpC,IAAId,QAAQ,OAAOrE,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAOiD,QAAQjD,KAAK;QAAC;QAC/D,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEgE,IAAI;YAAMjC,OAAOmB,QAAQnB,KAAK;QAAC;IAC/D,EAAE,OAAO9B,OAAO;QACdgF,QAAQhF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASiF;IACd1H;IACAf,uBAAuB,2BAA2BkD;AACpD;AAEA;;;;;CAKC,GACD,SAASwF,2BAA2B,QAAQ,sBAAkB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n checkEntitlement,\n type HostFunction,\n type HostVariable,\n resolveOrgEntitlements,\n} from '@aglyn/aglyn/server'\nimport {\n registerPluginApiRoute,\n registerPluginJob,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { activitySearchTokens } from '@aglyn/aglyn/app-utils/activity-search'\n// By its own module, as the event gates read it.\nimport { runOverageSold } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { timingSafeEqual } from 'crypto'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { runSummaryFields } from './model/run-history'\nimport { type HostWorkflow, runWorkflow } from './model/workflows'\nimport type { HostWebhook } from './model/webhooks'\nimport { eventRunSuspension } from './engine/site-suspension'\nimport {\n recordRuns,\n type RunMeterScope,\n runMonthKey,\n runsUsedThisMonth,\n} from './engine/run-meter'\nimport { BUNDLE_ID as WORKFLOWS_BUNDLE_ID } from './constants/bundle-common'\nimport { registerWorkflowsServerDeclarations } from './declarations.server'\nimport {\n automationRunEnv,\n executeWorkflow,\n runDueFlowEnrollments,\n workflowContextFromDocs,\n} from './engine/run-event-actions'\nimport {\n type AutomationWorkflow,\n workflowHasActionSteps,\n} from './engine/workflow-steps'\n\n/*==========================================\n * THE BEAT THAT MAKES A WAIT STEP REAL.\n *\n * A `wait` step suspends a run into a `flowEnrollments` row and returns; this\n * is the only thing that ever comes back for it. Without a registration here\n * the wait step would be a delay that never ends — the exact failure\n * `process-abandoned.ts` documents next door, where a Pro entitlement sat\n * behind an HTTP door nothing ever POSTed to.\n *\n * Module scope, like the commerce and bookings registrations: the runner\n * route reaches plugin jobs through `ensureAll(['tenantApi'])`, so a\n * registration inside `registerWorkflowsApi()` would depend on which entry\n * point happened to be loaded.\n *\n * ## Every minute, and why that is cheap\n *\n * `FLOW_WAIT_MIN_MINUTES` is one, so the beat has to be one — a fifteen-minute\n * sweep would make the shortest wait anybody can author wrong by up to\n * fourteen minutes. It costs one collection-group query per minute, which\n * returns nothing at all on a platform with no flow due, because the query\n * asks for `resumeAtMs <= now` rather than for the enrolled population.\n *\n * Bounded and idempotent, the two properties the runner requires: the scan\n * budget bounds one pass, and a transactional claim means an overlapping or\n * repeated beat cannot run the same person's step twice.\n *=========================================*/\nregisterPluginJob({\n pluginId: WORKFLOWS_BUNDLE_ID,\n name: 'resume-flow-waits',\n intervalMinutes: 1,\n description:\n 'Continue automations whose wait step has ended, and time out those ' +\n 'waiting for an event that never arrived.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n await runDueFlowEnrollments(gate)\n },\n})\n\n// Best-effort per-instance rate limit (mirrors forms/submit).\nconst recentByHook = new Map<string, number[]>()\nconst RATE_WINDOW_MS = 60_000\nconst RATE_MAX = 30\n\nfunction rateLimited(key: string): boolean {\n const now = Date.now()\n const hits = (recentByHook.get(key) ?? []).filter(\n (t) => now - t < RATE_WINDOW_MS,\n )\n hits.push(now)\n recentByHook.set(key, hits)\n return hits.length > RATE_MAX\n}\n\nfunction secretsMatch(expected: string, provided: string): boolean {\n if (!expected || expected.length !== provided.length) return false\n return timingSafeEqual(\n new Uint8Array(Buffer.from(expected)),\n new Uint8Array(Buffer.from(provided)),\n )\n}\n\n/**\n * Inbound webhook endpoint (AGL-149): external systems POST JSON to\n * `/api/hooks/{hostId}/{hookId}` with the hook's secret in\n * `x-aglyn-secret`; a valid call enrolls the configured workflow with the\n * payload's top-level primitives in scope. Business tier (`webhooks`\n * flag); runs bill against the workflow-runs meter like any other run —\n * `workflowRunsPerMonth` is checked against the workspace's runs before the\n * run, and the site's and the workspace's counters are incremented after it\n * (AGL-2228, AGL-3472).\n */\nconst inboundHookHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query['hostId'] ?? '')\n const hookId = String(req.query['hookId'] ?? '')\n if (!hostId || !hookId) {\n return res.status(400).json({ error: 'Invalid webhook address' })\n }\n if (rateLimited(`${hostId}/${hookId}`)) {\n return res.status(429).json({ error: 'Too many requests' })\n }\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hookSnapshot = await hostRef.collection('webhooks').doc(hookId).get()\n const hook = hookSnapshot.data() as HostWebhook | undefined\n if (\n !hook ||\n hookSnapshot.get('deletedAt') ||\n hook.direction !== 'inbound' ||\n hook.enabled === false\n ) {\n return res.status(404).json({ error: 'Unknown webhook' })\n }\n const provided = String(req.headers['x-aglyn-secret'] ?? '')\n if (!secretsMatch(hook.secret ?? '', provided)) {\n return res.status(401).json({ error: 'Bad secret' })\n }\n\n // Plan/quota gates ride the owning org's doc (AGL-238).\n const owner = await getOrgForHost(hostId)\n const org = owner?.org\n /*\n * A suspended site takes no inbound run (AGL-3356). The tenant\n * dispatcher's lockdown gate reads `hostId` from the query or body, and\n * this route carries it in the PATH, so the engine's own question is\n * asked here. A 423 rather than a 200: the caller is an integration, and\n * one told a run happened keeps sending.\n */\n const suspended = await eventRunSuspension(hostRef, org)\n if (suspended) {\n return res.status(423).json({ error: 'locked', scope: suspended.scope })\n }\n if (!checkEntitlement(org as any, 'webhooks')) {\n return res\n .status(403)\n .json({ error: 'Webhooks are not enabled on this site' })\n }\n /*\n * The MONTHLY RUN CAP, which this handler's own docblock claimed for\n * years — \"runs bill against the workflow-runs meter like any other run\"\n * — and did not have. It read neither `workflowRunsPerMonth` nor\n * `hosts/{id}/counters/workflowRuns`, and it wrote neither, so an inbound\n * hook was a workflow execution that no cap could refuse and no meter\n * could see: the customer's usage card, the usage-alerts cron and the\n * COGS rollup all read a counter this path never moved.\n *\n * The refusal is a 402 rather than the silent `return` of\n * `runEventWorkflows`: that path is fired from a visitor request whose\n * success must not depend on the workflow, where this one is an\n * integration calling us on purpose and a caller that gets a 200 for a\n * run that did not happen will keep sending. `Retry-After` is deliberately\n * absent — the month, not a delay, is what clears this.\n *\n * The plan-less/unreadable org resolves as FREE\n * (`workflowRunsPerMonth: 0`), so an org doc we cannot read refuses rather\n * than runs. `checkEntitlement(webhooks)` above already refuses free on\n * today's price list; this is not a second gate on the same fact, because\n * a staff `entitlementOverrides` can grant `webhooks` without granting\n * runs, and because the cap is what bounds a BUSINESS org's spend.\n *\n * Read-then-write, like the event path, and bounded the same way: the\n * per-hook limiter above is 30/60s, so the overshoot a race can buy is\n * bounded by concurrency rather than unbounded by design. Making it\n * atomic means a transaction around the whole run and is the same trade\n * `runEventWorkflows` declined.\n */\n // The band is the WORKSPACE's (AGL-3472), so the count it is held to is\n // every site's runs, off the org's counter — see `run-meter.ts`.\n const meter: RunMeterScope = {\n firestore,\n hostRef,\n orgId: owner?.orgId,\n counter: 'workflowRuns',\n month: runMonthKey(),\n }\n const runLimit = resolveOrgEntitlements(org as any).workflowRunsPerMonth\n const runsUsed = await runsUsedThisMonth(meter)\n // A wall only where the plan sells no runs past the band (pricing v4,\n // `runOverageSold`); otherwise the run goes ahead and the excess bills.\n if (!(runsUsed + 1 <= runLimit) && !runOverageSold(org as any)) {\n return res.status(402).json({\n error: `This workspace has used its ${runLimit} workflow runs for the month`,\n })\n }\n\n // Top-level primitives from the JSON body join the workflow scope.\n const body =\n typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n const scope: Record<string, string | number | boolean> = {}\n for (const [key, value] of Object.entries(body)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n scope[key.slice(0, 64)] =\n typeof value === 'string' ? value.slice(0, 2000) : value\n }\n }\n\n const [functionDocs, variableDocs, workflowDocs] = await Promise.all([\n hostRef.collection('functions').limit(100).get(),\n hostRef.collection('variables').limit(100).get(),\n hostRef.collection('workflows').limit(100).get(),\n ])\n const byName = <T extends { name?: string; deletedAt?: unknown }>(\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n ) => {\n const map: Record<string, T> = {}\n for (const doc of docs) {\n const data = doc.data() as T\n if (data?.name && !data.deletedAt) map[data.name] = data\n }\n return map\n }\n const workflows = byName<HostWorkflow>(workflowDocs.docs)\n const workflow = workflows[hook.workflowName?.trim() ?? '']\n if (!workflow) {\n return res.status(422).json({ error: 'No workflow bound to this hook' })\n }\n\n const hookEvent = `hook:${hook.name ?? hookId}`\n /*\n * A workflow of function calls is evaluated, as it always has been. One\n * with Actions steps is PERFORMED by the engine's executor — the posted\n * JSON is its payload — under the Actions tier gates, step by step, and\n * it is still one run on the meter below. Its working set is built from\n * the documents read above rather than read again.\n */\n const outcome: { error: string | null; value: unknown; summary: string } =\n workflowHasActionSteps(workflow)\n ? await (async () => {\n const workflowDoc = workflowDocs.docs.find(\n (doc) =>\n !doc.get('deletedAt') &&\n doc.get('name') === hook.workflowName?.trim(),\n )\n const execution = await executeWorkflow(\n automationRunEnv({\n hostId,\n hostRef,\n owner,\n depth: 0,\n loadWorkflowContext: async () =>\n workflowContextFromDocs(\n functionDocs.docs,\n variableDocs.docs,\n workflowDocs.docs,\n ),\n }),\n {\n kind: 'workflow',\n id: workflowDoc?.id ?? '',\n name: workflow.name ?? '',\n },\n workflow as AutomationWorkflow,\n hookEvent,\n scope,\n )\n return {\n error: execution.errors.length\n ? execution.errors.join('; ')\n : null,\n value: execution.value,\n summary: execution.outcomes.length\n ? execution.outcomes.join(' · ')\n : `Ran ${hook.workflowName}`,\n }\n })()\n : (() => {\n const run = runWorkflow(\n workflow,\n byName<HostFunction>(functionDocs.docs),\n byName<HostVariable>(variableDocs.docs),\n { event: hookEvent, ...scope },\n { workflows },\n )\n return run.ok === false\n ? { error: run.error, value: undefined, summary: '' }\n : {\n error: null,\n value: run.value,\n summary: `Ran ${hook.workflowName}`,\n }\n })()\n const failed = outcome.error !== null\n await hostRef\n .collection('activity')\n .add({\n actorId: null,\n actorEmail: null,\n // An outside system called the hook's URL; the hook is who it was.\n triggeredBy: { kind: 'webhook', name: hook.workflowName },\n action: failed\n ? `Inbound webhook run failed: ${outcome.error}`.slice(0, 300)\n : `Inbound webhook ran \"${hook.workflowName}\"`,\n // The run-history shape (AGL-2222) — without `result` this execution\n // is invisible to the Runs table, which reads a verdict and not prose.\n result: failed ? 'failed' : 'succeeded',\n trigger: hookEvent,\n ...runSummaryFields(\n failed\n ? String(outcome.error).slice(0, 300)\n : outcome.summary.slice(0, 300),\n ),\n target: { type: 'workflow', id: hookId, name: hook.name ?? '' },\n // The site log's search finds a run by its hook's name (AGL-3321).\n searchTokens: activitySearchTokens({ target: { name: hook.name } }),\n createdAt: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n // The run happened, so it counts — including a FAILED one, exactly as\n // `runEventWorkflows` counts its failures. A run that executed and threw\n // spent the same compute as one that returned a value; only a run that\n // never started (the cap above, a missing workflow) must not count.\n await recordRuns({ ...meter, count: 1 })\n\n if (failed) return res.status(422).json({ error: outcome.error })\n return res.status(200).json({ ok: true, value: outcome.value })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Webhook failed' })\n }\n}\n\n/**\n * Registers the workflows plugin's public API routes (AGL-396), and the\n * engine's host-event listener beside them for a process whose boot did not\n * (see `declarations.server.ts`).\n */\nexport function registerWorkflowsApi(): void {\n registerWorkflowsServerDeclarations()\n registerPluginApiRoute('hooks/[hostId]/[hookId]', inboundHookHandler)\n}\n\n/**\n * The console half (AGL-2919), re-exported so one entry point serves both\n * surfaces: the manifest generator resolves every server surface through\n * `@aglyn/plugins-workflows/server`, and a second entry point would be a second\n * thing to keep in step with plugins.config.json.\n */\nexport { registerWorkflowsConsoleApi } from './server-console'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { workflowsPlanEntitlements } from './plan-entitlements'\n"],"names":["checkEntitlement","resolveOrgEntitlements","registerPluginApiRoute","registerPluginJob","activitySearchTokens","runOverageSold","firebaseAdmin","getOrgForHost","timingSafeEqual","FieldValue","runSummaryFields","runWorkflow","eventRunSuspension","recordRuns","runMonthKey","runsUsedThisMonth","BUNDLE_ID","WORKFLOWS_BUNDLE_ID","registerWorkflowsServerDeclarations","automationRunEnv","executeWorkflow","runDueFlowEnrollments","workflowContextFromDocs","workflowHasActionSteps","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","recentByHook","Map","RATE_WINDOW_MS","RATE_MAX","rateLimited","key","now","Date","hits","get","filter","t","push","set","length","secretsMatch","expected","provided","Uint8Array","Buffer","from","inboundHookHandler","req","res","method","status","json","error","hostId","String","query","hookId","hook","firestore","app","hostRef","collection","doc","hookSnapshot","data","direction","enabled","headers","secret","owner","org","suspended","meter","orgId","counter","month","runLimit","workflowRunsPerMonth","runsUsed","body","JSON","parse","value","Object","entries","slice","functionDocs","variableDocs","workflowDocs","Promise","all","limit","byName","docs","map","deletedAt","workflows","workflow","workflowName","trim","hookEvent","outcome","workflowDoc","find","execution","depth","loadWorkflowContext","kind","id","errors","join","summary","outcomes","run","event","ok","undefined","failed","add","actorId","actorEmail","triggeredBy","action","result","trigger","target","type","searchTokens","createdAt","serverTimestamp","catch","count","console","registerWorkflowsApi","registerWorkflowsConsoleApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAGhBC,sBAAsB,QACjB,sBAAqB;AAC5B,SACEC,sBAAsB,EACtBC,iBAAiB,QAEZ,sBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,yCAAwC;AAC7E,iDAAiD;AACjD,SAASC,cAAc,QAAQ,2CAA0C;AACzE,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,SAAQ;AACxC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,gBAAgB,QAAQ,yBAAqB;AACtD,SAA4BC,WAAW,QAAQ,uBAAmB;AAElE,SAASC,kBAAkB,QAAQ,8BAA0B;AAC7D,SACEC,UAAU,EAEVC,WAAW,EACXC,iBAAiB,QACZ,wBAAoB;AAC3B,SAASC,aAAaC,mBAAmB,QAAQ,+BAA2B;AAC5E,SAASC,mCAAmC,QAAQ,2BAAuB;AAC3E,SACEC,gBAAgB,EAChBC,eAAe,EACfC,qBAAqB,EACrBC,uBAAuB,QAClB,gCAA4B;AACnC,SAEEC,sBAAsB,QACj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,KAAK,CAAC,GAAG;YAE/BwC,QAAQ;gBAAEC,MAAM;gBAAYlB,IAAIpD;gBAAQtC,IAAI,GAAEuC,cAAAA,KAAKvC,IAAI,YAATuC,cAAa;YAAG;YAC9D,mEAAmE;YACnEsE,cAAclI,qBAAqB;gBAAEgI,QAAQ;oBAAE3G,MAAMuC,KAAKvC,IAAI;gBAAC;YAAE;YACjE8G,WAAW9H,WAAW+H,eAAe;YAEtCC,KAAK,CAAC,IAAMd;QAEf,sEAAsE;QACtE,yEAAyE;QACzE,uEAAuE;QACvE,oEAAoE;QACpE,MAAM9G,WAAW,aAAKkE;YAAO2D,OAAO;;QAEpC,IAAId,QAAQ,OAAOrE,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAOiD,QAAQjD,KAAK;QAAC;QAC/D,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEgE,IAAI;YAAMjC,OAAOmB,QAAQnB,KAAK;QAAC;IAC/D,EAAE,OAAO9B,OAAO;QACdgF,QAAQhF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASiF;IACd1H;IACAhB,uBAAuB,2BAA2BmD;AACpD;AAEA;;;;;CAKC,GACD,SAASwF,2BAA2B,QAAQ,sBAAkB"}
|
package/src/lib/usage-axes.js
CHANGED
|
@@ -56,7 +56,14 @@
|
|
|
56
56
|
noun: 'workflow runs',
|
|
57
57
|
outcome: 'stops',
|
|
58
58
|
reached: 'Workflows pause until next month and nothing is charged — ' + 'upgrade in Billing to keep them running.',
|
|
59
|
-
approach: 'Nothing changes and nothing is charged — at the included amount, ' + 'workflows pause until next month unless you upgrade in Billing.'
|
|
59
|
+
approach: 'Nothing changes and nothing is charged — at the included amount, ' + 'workflows pause until next month unless you upgrade in Billing.',
|
|
60
|
+
// A plan with a run rate (pricing v4: Pro) keeps running past the
|
|
61
|
+
// band and bills the excess on the month's invoice.
|
|
62
|
+
overage: {
|
|
63
|
+
pricedBy: 'extraRunsUsdPer1k',
|
|
64
|
+
reached: 'Workflows keep running, and runs past the included amount are ' + 'billed on your monthly invoice.',
|
|
65
|
+
approach: 'Nothing is charged yet — past the included amount, extra ' + 'workflow runs are billed on your monthly invoice.'
|
|
66
|
+
}
|
|
60
67
|
}
|
|
61
68
|
},
|
|
62
69
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/usage-axes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginUsageAxesDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-usage-axes'\n\n/**\n * THE WORKFLOWS PLUGIN'S METERS (AGL-3080): workflow and action runs, in the\n * platform's cost model and utilization table. Compiled into core by the\n * manifest generator (`register.usageAxes`).\n *\n * ONE cost axis for both counters: a run is the same handful of reads, two\n * writes and a moment of compute whichever builder produced it, so both are\n * priced at `perRun` on one line. TWO bands, because each builder sells its\n * own; the workflow band also warns the workspace as it fills.\n */\nexport function workflowsUsageAxes(): PluginUsageAxesDeclaration {\n return {\n costAxes: [\n {\n id: 'runs',\n order: 90,\n fields: ['workflowRuns', 'actionRuns'],\n rate: 'perRun',\n },\n ],\n bands: [\n {\n id: 'workflowRuns',\n label: 'Workflow runs',\n order: 100,\n fields: ['workflowRuns'],\n entitlement: 'workflowRunsPerMonth',\n hostCounter: 'workflowRuns',\n // The band is the workspace's: every run is counted on the org's\n // counter too, and the run gates are held to it (`run-meter.ts`).\n orgCounter: 'workflowRuns',\n // The runtime stops workflows silently at the monthly cap, so the\n // owner is warned approaching it and told on reaching it why their\n // automations went quiet.\n alert: {\n label: 'monthly workflow runs',\n noun: 'workflow runs',\n outcome: 'stops',\n reached:\n 'Workflows pause until next month and nothing is charged — ' +\n 'upgrade in Billing to keep them running.',\n approach:\n 'Nothing changes and nothing is charged — at the included amount, ' +\n 'workflows pause until next month unless you upgrade in Billing.',\n },\n },\n {\n id: 'actionRuns',\n label: 'Action runs',\n order: 110,\n fields: ['actionRuns'],\n entitlement: 'actionRunsPerMonth',\n orgCounter: 'actionRuns',\n },\n ],\n }\n}\n"],"names":["workflowsUsageAxes","costAxes","id","order","fields","rate","bands","label","entitlement","hostCounter","orgCounter","alert","noun","outcome","reached","approach"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID;;;;;;;;;CASC,GACD,OAAO,SAASA;IACd,OAAO;QACLC,UAAU;YACR;gBACEC,IAAI;gBACJC,OAAO;gBACPC,QAAQ;oBAAC;oBAAgB;iBAAa;gBACtCC,MAAM;YACR;SACD;QACDC,OAAO;YACL;gBACEJ,IAAI;gBACJK,OAAO;gBACPJ,OAAO;gBACPC,QAAQ;oBAAC;iBAAe;gBACxBI,aAAa;gBACbC,aAAa;gBACb,iEAAiE;gBACjE,kEAAkE;gBAClEC,YAAY;gBACZ,kEAAkE;gBAClE,mEAAmE;gBACnE,0BAA0B;gBAC1BC,OAAO;oBACLJ,OAAO;oBACPK,MAAM;oBACNC,SAAS;oBACTC,SACE,+DACA;oBACFC,UACE,sEACA;
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/usage-axes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginUsageAxesDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-usage-axes'\n\n/**\n * THE WORKFLOWS PLUGIN'S METERS (AGL-3080): workflow and action runs, in the\n * platform's cost model and utilization table. Compiled into core by the\n * manifest generator (`register.usageAxes`).\n *\n * ONE cost axis for both counters: a run is the same handful of reads, two\n * writes and a moment of compute whichever builder produced it, so both are\n * priced at `perRun` on one line. TWO bands, because each builder sells its\n * own; the workflow band also warns the workspace as it fills.\n */\nexport function workflowsUsageAxes(): PluginUsageAxesDeclaration {\n return {\n costAxes: [\n {\n id: 'runs',\n order: 90,\n fields: ['workflowRuns', 'actionRuns'],\n rate: 'perRun',\n },\n ],\n bands: [\n {\n id: 'workflowRuns',\n label: 'Workflow runs',\n order: 100,\n fields: ['workflowRuns'],\n entitlement: 'workflowRunsPerMonth',\n hostCounter: 'workflowRuns',\n // The band is the workspace's: every run is counted on the org's\n // counter too, and the run gates are held to it (`run-meter.ts`).\n orgCounter: 'workflowRuns',\n // The runtime stops workflows silently at the monthly cap, so the\n // owner is warned approaching it and told on reaching it why their\n // automations went quiet.\n alert: {\n label: 'monthly workflow runs',\n noun: 'workflow runs',\n outcome: 'stops',\n reached:\n 'Workflows pause until next month and nothing is charged — ' +\n 'upgrade in Billing to keep them running.',\n approach:\n 'Nothing changes and nothing is charged — at the included amount, ' +\n 'workflows pause until next month unless you upgrade in Billing.',\n // A plan with a run rate (pricing v4: Pro) keeps running past the\n // band and bills the excess on the month's invoice.\n overage: {\n pricedBy: 'extraRunsUsdPer1k',\n reached:\n 'Workflows keep running, and runs past the included amount are ' +\n 'billed on your monthly invoice.',\n approach:\n 'Nothing is charged yet — past the included amount, extra ' +\n 'workflow runs are billed on your monthly invoice.',\n },\n },\n },\n {\n id: 'actionRuns',\n label: 'Action runs',\n order: 110,\n fields: ['actionRuns'],\n entitlement: 'actionRunsPerMonth',\n orgCounter: 'actionRuns',\n },\n ],\n }\n}\n"],"names":["workflowsUsageAxes","costAxes","id","order","fields","rate","bands","label","entitlement","hostCounter","orgCounter","alert","noun","outcome","reached","approach","overage","pricedBy"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAID;;;;;;;;;CASC,GACD,OAAO,SAASA;IACd,OAAO;QACLC,UAAU;YACR;gBACEC,IAAI;gBACJC,OAAO;gBACPC,QAAQ;oBAAC;oBAAgB;iBAAa;gBACtCC,MAAM;YACR;SACD;QACDC,OAAO;YACL;gBACEJ,IAAI;gBACJK,OAAO;gBACPJ,OAAO;gBACPC,QAAQ;oBAAC;iBAAe;gBACxBI,aAAa;gBACbC,aAAa;gBACb,iEAAiE;gBACjE,kEAAkE;gBAClEC,YAAY;gBACZ,kEAAkE;gBAClE,mEAAmE;gBACnE,0BAA0B;gBAC1BC,OAAO;oBACLJ,OAAO;oBACPK,MAAM;oBACNC,SAAS;oBACTC,SACE,+DACA;oBACFC,UACE,sEACA;oBACF,kEAAkE;oBAClE,oDAAoD;oBACpDC,SAAS;wBACPC,UAAU;wBACVH,SACE,mEACA;wBACFC,UACE,8DACA;oBACJ;gBACF;YACF;YACA;gBACEb,IAAI;gBACJK,OAAO;gBACPJ,OAAO;gBACPC,QAAQ;oBAAC;iBAAa;gBACtBI,aAAa;gBACbE,YAAY;YACd;SACD;IACH;AACF"}
|