@segmentstream/ontology 0.208.0 → 0.209.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.
@@ -518,6 +518,11 @@ export declare const MigrationPlan: Schema.Struct<{
518
518
  readonly input?: string | undefined;
519
519
  readonly verifyToken?: string | undefined;
520
520
  } | undefined;
521
+ } | {
522
+ readonly kind: "platform";
523
+ readonly name: string;
524
+ readonly description: string;
525
+ readonly events: readonly string[];
521
526
  })[];
522
527
  readonly role: string;
523
528
  readonly action?: {
@@ -904,6 +909,11 @@ export declare const MigrationPlan: Schema.Struct<{
904
909
  readonly input?: string | undefined;
905
910
  readonly verifyToken?: string | undefined;
906
911
  } | undefined;
912
+ } | {
913
+ readonly kind: "platform";
914
+ readonly name: string;
915
+ readonly description: string;
916
+ readonly events: readonly string[];
907
917
  })[];
908
918
  readonly role: string;
909
919
  readonly action?: {
@@ -1290,6 +1300,11 @@ export declare const MigrationPlan: Schema.Struct<{
1290
1300
  readonly input?: string | undefined;
1291
1301
  readonly verifyToken?: string | undefined;
1292
1302
  } | undefined;
1303
+ } | {
1304
+ readonly kind: "platform";
1305
+ readonly name: string;
1306
+ readonly description: string;
1307
+ readonly events: readonly string[];
1293
1308
  })[];
1294
1309
  readonly role: string;
1295
1310
  readonly action?: {
@@ -1676,6 +1691,11 @@ export declare const MigrationPlan: Schema.Struct<{
1676
1691
  readonly input?: string | undefined;
1677
1692
  readonly verifyToken?: string | undefined;
1678
1693
  } | undefined;
1694
+ } | {
1695
+ readonly kind: "platform";
1696
+ readonly name: string;
1697
+ readonly description: string;
1698
+ readonly events: readonly string[];
1679
1699
  })[];
1680
1700
  readonly role: string;
1681
1701
  readonly action?: {
@@ -2192,6 +2212,11 @@ export declare const MigrationPlan: Schema.Struct<{
2192
2212
  }>>;
2193
2213
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
2194
2214
  readonly connection: Schema.optionalKey<Schema.String>;
2215
+ }>, Schema.Struct<{
2216
+ readonly kind: Schema.Literal<"platform">;
2217
+ readonly name: Schema.String;
2218
+ readonly description: Schema.String;
2219
+ readonly events: Schema.$Array<Schema.String>;
2195
2220
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
2196
2221
  readonly action: Schema.optionalKey<Schema.Struct<{
2197
2222
  readonly entity: Schema.String;
@@ -2574,6 +2599,11 @@ export declare const MigrationPlan: Schema.Struct<{
2574
2599
  }>>;
2575
2600
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
2576
2601
  readonly connection: Schema.optionalKey<Schema.String>;
2602
+ }>, Schema.Struct<{
2603
+ readonly kind: Schema.Literal<"platform">;
2604
+ readonly name: Schema.String;
2605
+ readonly description: Schema.String;
2606
+ readonly events: Schema.$Array<Schema.String>;
2577
2607
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
2578
2608
  readonly action: Schema.optionalKey<Schema.Struct<{
2579
2609
  readonly entity: Schema.String;
@@ -2841,6 +2871,11 @@ export declare const MigrationPlan: Schema.Struct<{
2841
2871
  readonly input?: string | undefined;
2842
2872
  readonly verifyToken?: string | undefined;
2843
2873
  } | undefined;
2874
+ } | {
2875
+ readonly kind: "platform";
2876
+ readonly name: string;
2877
+ readonly description: string;
2878
+ readonly events: readonly string[];
2844
2879
  })[];
2845
2880
  readonly role: string;
2846
2881
  readonly action?: {
@@ -3227,6 +3262,11 @@ export declare const MigrationPlan: Schema.Struct<{
3227
3262
  readonly input?: string | undefined;
3228
3263
  readonly verifyToken?: string | undefined;
3229
3264
  } | undefined;
3265
+ } | {
3266
+ readonly kind: "platform";
3267
+ readonly name: string;
3268
+ readonly description: string;
3269
+ readonly events: readonly string[];
3230
3270
  })[];
3231
3271
  readonly role: string;
3232
3272
  readonly action?: {
@@ -0,0 +1,74 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * The catalog of platform events: what the platform recorded for a workspace that a platform
4
+ * trigger, `platform(name, { events })`, starts a workflow for. The platform decides which exist.
5
+ * An event carries ids and codes, never text: the console and the CLI explain them by the same
6
+ * ids. It names no workspace or organization, since it is delivered only to the workspace it is
7
+ * about. A type gains fields compatibly; a change to a field is a new type.
8
+ */
9
+ export declare const PLATFORM_EVENT_TYPES: readonly ["deployment.succeeded", "deployment.failed"];
10
+ export type PlatformEventType = (typeof PLATFORM_EVENT_TYPES)[number];
11
+ /** Who sends an event type: backend-next for deployments. */
12
+ export type PlatformEventSender = "platform";
13
+ export declare const PLATFORM_EVENT_SENDERS: Readonly<Record<PlatformEventType, PlatformEventSender>>;
14
+ /** Whether a value names a type of this SDK's catalog. */
15
+ export declare function isPlatformEventType(value: unknown): value is PlatformEventType;
16
+ /** A production deployment of the workspace became the serving deployment. */
17
+ export declare const DeploymentSucceededEvent: Schema.Struct<{
18
+ /** Derived from the type and the deployment, so every delivery of this outcome carries it. */
19
+ readonly id: Schema.String;
20
+ readonly type: Schema.Literal<"deployment.succeeded">;
21
+ /** When the outcome was recorded, ISO 8601. */
22
+ readonly at: Schema.String;
23
+ readonly deployment: Schema.Struct<{
24
+ readonly id: Schema.String;
25
+ readonly commit: Schema.NullOr<Schema.String>;
26
+ }>;
27
+ }>;
28
+ /** The deployment workflow recorded a failure of a production deployment of the workspace. */
29
+ export declare const DeploymentFailedEvent: Schema.Struct<{
30
+ readonly id: Schema.String;
31
+ readonly type: Schema.Literal<"deployment.failed">;
32
+ readonly at: Schema.String;
33
+ readonly deployment: Schema.Struct<{
34
+ readonly id: Schema.String;
35
+ readonly commit: Schema.NullOr<Schema.String>;
36
+ }>;
37
+ readonly failure: Schema.Struct<{
38
+ /** A code of the deployment failure catalog, such as `ontology_migration_refused`. */
39
+ readonly code: Schema.String;
40
+ /** The `dep_…` reference the console and the CLI show with the full explanation. */
41
+ readonly reference: Schema.String;
42
+ }>;
43
+ }>;
44
+ /** Any event of the catalog, by `type`. Fields a later platform adds are ignored. */
45
+ export declare const PlatformEvent: Schema.Union<readonly [Schema.Struct<{
46
+ /** Derived from the type and the deployment, so every delivery of this outcome carries it. */
47
+ readonly id: Schema.String;
48
+ readonly type: Schema.Literal<"deployment.succeeded">;
49
+ /** When the outcome was recorded, ISO 8601. */
50
+ readonly at: Schema.String;
51
+ readonly deployment: Schema.Struct<{
52
+ readonly id: Schema.String;
53
+ readonly commit: Schema.NullOr<Schema.String>;
54
+ }>;
55
+ }>, Schema.Struct<{
56
+ readonly id: Schema.String;
57
+ readonly type: Schema.Literal<"deployment.failed">;
58
+ readonly at: Schema.String;
59
+ readonly deployment: Schema.Struct<{
60
+ readonly id: Schema.String;
61
+ readonly commit: Schema.NullOr<Schema.String>;
62
+ }>;
63
+ readonly failure: Schema.Struct<{
64
+ /** A code of the deployment failure catalog, such as `ontology_migration_refused`. */
65
+ readonly code: Schema.String;
66
+ /** The `dep_…` reference the console and the CLI show with the full explanation. */
67
+ readonly reference: Schema.String;
68
+ }>;
69
+ }>]>;
70
+ export type PlatformEvent = typeof PlatformEvent.Type;
71
+ /** The event of one catalog type. */
72
+ export type PlatformEventOf<T extends PlatformEventType> = Extract<PlatformEvent, {
73
+ readonly type: T;
74
+ }>;
@@ -0,0 +1,46 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * The catalog of platform events: what the platform recorded for a workspace that a platform
4
+ * trigger, `platform(name, { events })`, starts a workflow for. The platform decides which exist.
5
+ * An event carries ids and codes, never text: the console and the CLI explain them by the same
6
+ * ids. It names no workspace or organization, since it is delivered only to the workspace it is
7
+ * about. A type gains fields compatibly; a change to a field is a new type.
8
+ */
9
+ export const PLATFORM_EVENT_TYPES = ["deployment.succeeded", "deployment.failed"];
10
+ export const PLATFORM_EVENT_SENDERS = {
11
+ "deployment.succeeded": "platform",
12
+ "deployment.failed": "platform",
13
+ };
14
+ /** Whether a value names a type of this SDK's catalog. */
15
+ export function isPlatformEventType(value) {
16
+ return (typeof value === "string" && PLATFORM_EVENT_TYPES.includes(value));
17
+ }
18
+ /** The deployment an event is about: its id, and its commit SHA, `null` for an upload without Git. */
19
+ const EventDeployment = Schema.Struct({
20
+ id: Schema.String,
21
+ commit: Schema.NullOr(Schema.String),
22
+ });
23
+ /** A production deployment of the workspace became the serving deployment. */
24
+ export const DeploymentSucceededEvent = Schema.Struct({
25
+ /** Derived from the type and the deployment, so every delivery of this outcome carries it. */
26
+ id: Schema.String,
27
+ type: Schema.Literal("deployment.succeeded"),
28
+ /** When the outcome was recorded, ISO 8601. */
29
+ at: Schema.String,
30
+ deployment: EventDeployment,
31
+ });
32
+ /** The deployment workflow recorded a failure of a production deployment of the workspace. */
33
+ export const DeploymentFailedEvent = Schema.Struct({
34
+ id: Schema.String,
35
+ type: Schema.Literal("deployment.failed"),
36
+ at: Schema.String,
37
+ deployment: EventDeployment,
38
+ failure: Schema.Struct({
39
+ /** A code of the deployment failure catalog, such as `ontology_migration_refused`. */
40
+ code: Schema.String,
41
+ /** The `dep_…` reference the console and the CLI show with the full explanation. */
42
+ reference: Schema.String,
43
+ }),
44
+ });
45
+ /** Any event of the catalog, by `type`. Fields a later platform adds are ignored. */
46
+ export const PlatformEvent = Schema.Union([DeploymentSucceededEvent, DeploymentFailedEvent]);
@@ -0,0 +1,42 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { PlatformEvent, type PlatformEventSender } from "../platform-events.js";
3
+ /** A platform trigger the events route can start: the workflow's own, with its functions. */
4
+ export interface PlatformTriggerTarget {
5
+ /** The workflow's wire name. */
6
+ readonly workflow: string;
7
+ /** `<workflow>.<trigger>`, in wire names. */
8
+ readonly trigger: string;
9
+ /** The catalog types that start it. */
10
+ readonly events: ReadonlyArray<string>;
11
+ readonly when: ((event: PlatformEvent) => boolean) | undefined;
12
+ readonly input: ((event: PlatformEvent) => unknown) | undefined;
13
+ /** The workflow's input codec, TypeScript names on the type side and wire names encoded. */
14
+ readonly codec: Schema.Top;
15
+ }
16
+ /** Why a trigger an event matched starts no run, when its own code is at fault. */
17
+ export type PlatformTriggerFailure = "trigger_function_failed" | "trigger_input_invalid";
18
+ /** What one trigger does with one event. */
19
+ export type PlatformTriggerOutcome = {
20
+ readonly start: true;
21
+ readonly input: unknown;
22
+ } | {
23
+ readonly start: false;
24
+ } | {
25
+ readonly start: false;
26
+ readonly failed: PlatformTriggerFailure;
27
+ readonly cause: unknown;
28
+ };
29
+ /**
30
+ * The event a sender delivered, decoded with this SDK's catalog. Fields a later platform adds are
31
+ * ignored; an unknown type or a missing field is `undefined`.
32
+ */
33
+ export declare function decodePlatformEvent(value: unknown): PlatformEvent | undefined;
34
+ /** Whether a sender may deliver an event of this type: each sends only what it records. */
35
+ export declare function maySend(sender: PlatformEventSender, event: PlatformEvent): boolean;
36
+ /**
37
+ * Runs a trigger's `when` and `input` on an event, as an action trigger's run on an action: both
38
+ * synchronous workspace code. The input comes back in the workflow input's wire form, validated as
39
+ * a start decodes it. A function that throws, a `when` that is not a boolean and an input the
40
+ * workflow does not accept are the trigger's own failures, which skip it and nothing else.
41
+ */
42
+ export declare function evaluatePlatformTrigger(target: PlatformTriggerTarget, event: PlatformEvent): Effect.Effect<PlatformTriggerOutcome>;
@@ -0,0 +1,67 @@
1
+ import { Effect, Result, Schema } from "effect";
2
+ import { PLATFORM_EVENT_SENDERS, PlatformEvent, } from "../platform-events.js";
3
+ import { validate } from "./validation.js";
4
+ /**
5
+ * The event a sender delivered, decoded with this SDK's catalog. Fields a later platform adds are
6
+ * ignored; an unknown type or a missing field is `undefined`.
7
+ */
8
+ export function decodePlatformEvent(value) {
9
+ const decoded = Schema.decodeUnknownResult(PlatformEvent)(value, {
10
+ errors: "all",
11
+ onExcessProperty: "ignore",
12
+ });
13
+ return Result.isSuccess(decoded) ? decoded.success : undefined;
14
+ }
15
+ /** Whether a sender may deliver an event of this type: each sends only what it records. */
16
+ export function maySend(sender, event) {
17
+ return PLATFORM_EVENT_SENDERS[event.type] === sender;
18
+ }
19
+ /**
20
+ * Runs a trigger's `when` and `input` on an event, as an action trigger's run on an action: both
21
+ * synchronous workspace code. The input comes back in the workflow input's wire form, validated as
22
+ * a start decodes it. A function that throws, a `when` that is not a boolean and an input the
23
+ * workflow does not accept are the trigger's own failures, which skip it and nothing else.
24
+ */
25
+ export function evaluatePlatformTrigger(target, event) {
26
+ return Effect.gen(function* () {
27
+ if (target.when !== undefined) {
28
+ let fires;
29
+ try {
30
+ fires = target.when(event);
31
+ }
32
+ catch (cause) {
33
+ return { start: false, failed: "trigger_function_failed", cause };
34
+ }
35
+ if (typeof fires !== "boolean") {
36
+ return {
37
+ start: false,
38
+ failed: "trigger_function_failed",
39
+ cause: new TypeError(`when returned ${typeof fires}, not a boolean.`),
40
+ };
41
+ }
42
+ if (!fires) {
43
+ return { start: false };
44
+ }
45
+ }
46
+ let mapped;
47
+ try {
48
+ mapped = target.input === undefined ? {} : target.input(event);
49
+ }
50
+ catch (cause) {
51
+ return { start: false, failed: "trigger_function_failed", cause };
52
+ }
53
+ const encoded = yield* Schema.encodeUnknownEffect(target.codec)(mapped, { errors: "all", onExcessProperty: "error" }).pipe(Effect.result);
54
+ if (Result.isFailure(encoded)) {
55
+ return { start: false, failed: "trigger_input_invalid", cause: encoded.failure };
56
+ }
57
+ const decoded = validate(target.codec, encoded.success);
58
+ if (!decoded.ok) {
59
+ return {
60
+ start: false,
61
+ failed: "trigger_input_invalid",
62
+ cause: new TypeError(decoded.issues.map((issue) => issue.message).join("; ")),
63
+ };
64
+ }
65
+ return { start: true, input: JSON.parse(JSON.stringify(encoded.success)) };
66
+ });
67
+ }
@@ -660,6 +660,11 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
660
660
  }>>;
661
661
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
662
662
  readonly connection: Schema.optionalKey<Schema.String>;
663
+ }>, Schema.Struct<{
664
+ readonly kind: Schema.Literal<"platform">;
665
+ readonly name: Schema.String;
666
+ readonly description: Schema.String;
667
+ readonly events: Schema.$Array<Schema.String>;
663
668
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
664
669
  readonly action: Schema.optionalKey<Schema.Struct<{
665
670
  readonly entity: Schema.String;
@@ -1057,6 +1062,11 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
1057
1062
  }>>;
1058
1063
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
1059
1064
  readonly connection: Schema.optionalKey<Schema.String>;
1065
+ }>, Schema.Struct<{
1066
+ readonly kind: Schema.Literal<"platform">;
1067
+ readonly name: Schema.String;
1068
+ readonly description: Schema.String;
1069
+ readonly events: Schema.$Array<Schema.String>;
1060
1070
  }>, Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>>;
1061
1071
  readonly action: Schema.optionalKey<Schema.Struct<{
1062
1072
  readonly entity: Schema.String;
@@ -651,6 +651,13 @@ export function createOntologyService(ontology, config) {
651
651
  if (parts[1] === "api" && parts[2] === "ontology" && entity !== undefined) {
652
652
  return `/api/ontology/${entity.name}/*`;
653
653
  }
654
+ if (parts[1] === "api" &&
655
+ parts[2] === "ontology" &&
656
+ parts[3] === "workflows" &&
657
+ parts[4] === "events" &&
658
+ parts.length === 5) {
659
+ return "/api/ontology/workflows/events";
660
+ }
654
661
  if (parts[1] === "api" && parts[2] === "ontology" && parts[3] === "workflows") {
655
662
  const workflow = ontology.workflows.find((item) => item.name === parts[4]);
656
663
  if (workflow) {
@@ -230,6 +230,8 @@ export declare function scheduledMinute(expression: string, now: Date): string;
230
230
  export declare function triggerPath(workflow: string, trigger: string): string;
231
231
  /** The route Vercel calls every five minutes when the manifest declares an action trigger. */
232
232
  export declare const SWEEP_PATH = "/api/ontology/workflows/sweep";
233
+ /** The route the platform delivers a platform event about this workspace to. */
234
+ export declare const PLATFORM_EVENTS_PATH = "/api/ontology/workflows/events";
233
235
  /**
234
236
  * The workflow routes and the in-process binding of workflow runs:
235
237
  *
@@ -18,7 +18,7 @@ import { Files } from "../files.js";
18
18
  import { canonicalJson } from "../manifest.js";
19
19
  import { unavailableFiles } from "../storage/file-access.js";
20
20
  import { ActionRejected, PermissionDenied, } from "../errors.js";
21
- import { isActionTrigger, isCronTrigger, isWebhookTrigger, } from "../manifest.js";
21
+ import { isActionTrigger, isCronTrigger, isPlatformTrigger, isWebhookTrigger, } from "../manifest.js";
22
22
  import { webhookTokenMatches } from "../webhook-token.js";
23
23
  import { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_VERIFICATION_CHARS, presentedWebhookSignature, WEBHOOK_BASE_PATH, webhookPath, } from "../webhooks.js";
24
24
  import { generatedSignatureMatches, readWebhookBody, signatureCheck, signatureRefusals, utf8Text, } from "./webhooks.js";
@@ -29,7 +29,8 @@ import { writesOnlyThroughActions } from "../runtime/generated-actions.js";
29
29
  import { validate } from "../runtime/validation.js";
30
30
  import { connectionOwnerOf, recordedOwner, runAttributes, triggerContext, WorkflowStartFailed, } from "../runtime/workflow-starts.js";
31
31
  import { RECOVERY_CONFIRM_MS, RECOVERY_COVERAGE_MARGIN_MS, RECOVERY_FIRST_SWEEP_MS, RECOVERY_SWEEP_BUDGET_MS, } from "../start-recovery-contract.js";
32
- import { nextCronTime, } from "../workflow.js";
32
+ import { isWorkflowTrigger, nextCronTime, } from "../workflow.js";
33
+ import { decodePlatformEvent, evaluatePlatformTrigger, maySend, } from "../runtime/platform-triggers.js";
33
34
  import { platformWorkflows, setWorkflowBinding, WORKFLOW_BASE_PATH, workflowSdk, workflowStructures, } from "../workflow-runtime.js";
34
35
  import { callbackIdentityToken, StepIdentityToken } from "./workflow-callback.js";
35
36
  import { OwnerInactive } from "./workflow-errors.js";
@@ -578,15 +579,20 @@ function runStartedBy(attributes) {
578
579
  if (kind === "trigger" && trigger !== undefined) {
579
580
  const actionId = attributes?.["startedBy.actionId"];
580
581
  const recordId = attributes?.["startedBy.recordId"];
582
+ const event = attributes?.["startedBy.event"];
581
583
  const triggerKind = attributes?.["startedBy.triggerKind"];
582
584
  return {
583
585
  kind,
584
- ...(triggerKind === "cron" || triggerKind === "action" || triggerKind === "webhook"
586
+ ...(triggerKind === "cron" ||
587
+ triggerKind === "action" ||
588
+ triggerKind === "webhook" ||
589
+ triggerKind === "platform"
585
590
  ? { triggerKind }
586
591
  : {}),
587
592
  trigger,
588
593
  ...(actionId === undefined ? {} : { actionId }),
589
594
  ...(recordId === undefined ? {} : { recordId }),
595
+ ...(event === undefined ? {} : { event }),
590
596
  };
591
597
  }
592
598
  return undefined;
@@ -636,6 +642,8 @@ export function triggerPath(workflow, trigger) {
636
642
  }
637
643
  /** The route Vercel calls every five minutes when the manifest declares an action trigger. */
638
644
  export const SWEEP_PATH = `${WORKFLOW_BASE_PATH}/workflows/sweep`;
645
+ /** The route the platform delivers a platform event about this workspace to. */
646
+ export const PLATFORM_EVENTS_PATH = `${WORKFLOW_BASE_PATH}/workflows/events`;
639
647
  function workflowView(workflow, now) {
640
648
  return {
641
649
  ...workflow,
@@ -674,7 +682,16 @@ function workflowView(workflow, now) {
674
682
  connection: trigger.connection ?? null,
675
683
  },
676
684
  ]
677
- : []),
685
+ : isPlatformTrigger(trigger)
686
+ ? [
687
+ {
688
+ kind: trigger.kind,
689
+ name: trigger.name,
690
+ description: trigger.description,
691
+ events: trigger.events,
692
+ },
693
+ ]
694
+ : []),
678
695
  };
679
696
  }
680
697
  function isWorkloadToken(token) {
@@ -1268,9 +1285,15 @@ export function workflowsLayer(options) {
1268
1285
  if (allocated._tag === "Failure") {
1269
1286
  return refused(toServerResponse(unavailable(requestId)));
1270
1287
  }
1288
+ // A cron start is admitted once per minute and a platform start once per event, so a
1289
+ // repeated delivery reserves the same row and run.
1271
1290
  const identity = context.startedBy.kind === "trigger" && context.startedBy.triggerKind === "cron"
1272
1291
  ? `${workflow.manifest.name}:${context.startedBy.trigger}:${Math.floor(Date.now() / 60_000)}`
1273
- : `${requestId}:${canonicalJson(context.startedBy)}`;
1292
+ : context.startedBy.kind === "trigger" &&
1293
+ context.startedBy.triggerKind === "platform" &&
1294
+ context.startedBy.event !== undefined
1295
+ ? `${context.startedBy.trigger}:${context.startedBy.event}`
1296
+ : `${requestId}:${canonicalJson(context.startedBy)}`;
1274
1297
  const hash = createHash("sha256").update(identity).digest("hex");
1275
1298
  const actionId = [
1276
1299
  hash.slice(0, 8),
@@ -1803,6 +1826,97 @@ export function workflowsLayer(options) {
1803
1826
  });
1804
1827
  yield* router.add("*", `${WEBHOOK_BASE_PATH}/:name`, webhook);
1805
1828
  yield* router.add("*", `${WEBHOOK_BASE_PATH}/:name/:token`, webhook);
1829
+ // Platform triggers, with their workflows' functions: an event starts each trigger listing
1830
+ // its type once (docs/ontology-platform-triggers-spec.md).
1831
+ const platformTargets = workflows.flatMap((workflow) => workflow.manifest.triggers.filter(isPlatformTrigger).flatMap((trigger) => {
1832
+ const authored = workflow.declaration.triggers.find((candidate) => isWorkflowTrigger(candidate) &&
1833
+ candidate.kind === "platform" &&
1834
+ nameToWire(candidate.name) === trigger.name);
1835
+ return authored === undefined || authored.kind !== "platform"
1836
+ ? []
1837
+ : [
1838
+ {
1839
+ declared: workflow,
1840
+ target: {
1841
+ workflow: workflow.manifest.name,
1842
+ trigger: `${workflow.manifest.name}.${trigger.name}`,
1843
+ events: trigger.events,
1844
+ when: authored.when,
1845
+ input: authored.input,
1846
+ codec: workflow.input,
1847
+ },
1848
+ },
1849
+ ];
1850
+ }));
1851
+ // The platform delivers an event about this workspace: the platform token names this
1852
+ // workspace, which the verifier checks. Each trigger listing the event's type starts its
1853
+ // workflow once per event; a trigger whose own code fails is skipped and logged, and the
1854
+ // others still start. Nothing here opens the database until a trigger starts.
1855
+ yield* router.add("POST", PLATFORM_EVENTS_PATH, authorized((caller, request) => Effect.gen(function* () {
1856
+ const requestId = yield* RequestId;
1857
+ if (caller.kind !== "platform") {
1858
+ return toServerResponse(forbidden(requestId, "Only the platform delivers platform events."));
1859
+ }
1860
+ const text = yield* request.text.pipe(Effect.orElseSucceed(() => ""));
1861
+ let body;
1862
+ try {
1863
+ body = JSON.parse(text);
1864
+ }
1865
+ catch {
1866
+ body = undefined;
1867
+ }
1868
+ const event = decodePlatformEvent(typeof body === "object" && body !== null && !Array.isArray(body)
1869
+ ? body.event
1870
+ : undefined);
1871
+ if (event === undefined) {
1872
+ return json({ error: "platform_event_invalid" }, 422);
1873
+ }
1874
+ if (!maySend("platform", event)) {
1875
+ return toServerResponse(forbidden(requestId, `This sender may not deliver ${event.type} events.`));
1876
+ }
1877
+ const runs = [];
1878
+ const skipped = [];
1879
+ for (const { declared, target } of platformTargets) {
1880
+ if (!target.events.includes(event.type)) {
1881
+ continue;
1882
+ }
1883
+ const outcome = yield* evaluatePlatformTrigger(target, event);
1884
+ if (!outcome.start) {
1885
+ if ("failed" in outcome) {
1886
+ skipped.push({ trigger: target.trigger, code: outcome.failed });
1887
+ yield* Effect.logError("ontology.workflow.platform_trigger_failed", outcome.cause).pipe(Effect.annotateLogs({
1888
+ requestId,
1889
+ trigger: target.trigger,
1890
+ event: event.id,
1891
+ type: event.type,
1892
+ code: outcome.failed,
1893
+ }));
1894
+ }
1895
+ continue;
1896
+ }
1897
+ const begun = yield* beginRun(declared, outcome.input, {
1898
+ startedBy: {
1899
+ kind: "trigger",
1900
+ triggerKind: "platform",
1901
+ trigger: target.trigger,
1902
+ event: event.id,
1903
+ },
1904
+ });
1905
+ // The sender retries a failed delivery; starts already admitted are not repeated.
1906
+ if (!begun.ok) {
1907
+ return begun.response;
1908
+ }
1909
+ runs.push({ trigger: target.trigger, runId: begun.runId });
1910
+ }
1911
+ yield* Effect.logInfo("ontology.workflow.platform_event").pipe(Effect.annotateLogs({
1912
+ requestId,
1913
+ event: event.id,
1914
+ type: event.type,
1915
+ started: runs.length,
1916
+ skipped: skipped.length,
1917
+ }));
1918
+ return json({ runs, skipped }, 202);
1919
+ })));
1806
1920
  // The sweep: Vercel's cron calls it with GET; an operator may POST, with
1807
1921
  // `?retryAbandoned=true` to retry the starts the automatic sweep gave up on.
1808
1922
  const sweep = (request) => Effect.gen(function* () {
@@ -2,6 +2,7 @@ import type { Schema } from "effect";
2
2
  import type { ActionInput, ActionResult, AnyAction } from "./action.js";
3
3
  import type { AnyConnectionHandle } from "./connection.js";
4
4
  import type { ActionHandle, AnyStoredEntity } from "./entity.js";
5
+ import type { PlatformEvent, PlatformEventOf, PlatformEventType } from "./platform-events.js";
5
6
  import type { Edit } from "./runtime/history.js";
6
7
  import type { Principal } from "./runtime.js";
7
8
  import type { WebhookDelivery, WebhookHmacFormat, WebhookSignatureScheme } from "./webhooks.js";
@@ -19,6 +20,11 @@ export declare const MAX_WORKFLOWS = 50;
19
20
  * record. A workflow may carry several, so it exceeds the workflows an ontology may declare.
20
21
  */
21
22
  export declare const MAX_ACTION_TRIGGERS = 100;
23
+ /**
24
+ * The most platform triggers, `platform(…)`, one ontology may declare across its workflows, as for
25
+ * webhooks: it bounds the runs one platform event can start.
26
+ */
27
+ export declare const MAX_PLATFORM_TRIGGERS = 20;
22
28
  /**
23
29
  * What a trigger listed in `defineOntology({ triggers })` runs instead of a workflow: one action,
24
30
  * in a durable run retried like a step, as the trigger's own workflow user holding `role`. The
@@ -235,10 +241,50 @@ export interface WebhookOptions extends TriggerRuns {
235
241
  */
236
242
  export declare function webhook<const Name extends string>(name: Name, options: WebhookOptions): WebhookTrigger<Name>;
237
243
  /**
238
- * What starts a workflow on its own. A discriminated union on `kind`: `cron`, `action` and
239
- * `webhook`; other kinds are additions.
244
+ * A platform trigger, `platform(name, { description, events, when, input })`: starts the workflow
245
+ * for each event of the listed catalog types that the platform records for this workspace, such
246
+ * as a production deployment that failed. `when` and `input` are code: the manifest records the
247
+ * kind, the name, the description and the event types, never the functions.
248
+ */
249
+ export interface PlatformTrigger<Name extends string = string, Input = unknown> {
250
+ readonly [WorkflowTriggerTypeId]: typeof WorkflowTriggerTypeId;
251
+ readonly kind: "platform";
252
+ /** A camelCase name, unique within its workflow: `deployFailed`. */
253
+ readonly name: Name;
254
+ /** Which events start the workflow and why, for people, agents and the catalog. */
255
+ readonly description: string;
256
+ /** The catalog types that start it, such as `"deployment.failed"`. */
257
+ readonly events: ReadonlyArray<string>;
258
+ /** Whether the run starts; omitted means always. */
259
+ readonly when: ((event: PlatformEvent) => boolean) | undefined;
260
+ /** The workflow's input, in TypeScript names; omitted means `{}`. */
261
+ readonly input: ((event: PlatformEvent) => Input) | undefined;
262
+ }
263
+ export interface PlatformOptions<T extends PlatformEventType, Input> {
264
+ /** Required, like every declaration: which events start the workflow and why. */
265
+ readonly description: string;
266
+ /** One or more catalog types. The functions receive the event of any of them. */
267
+ readonly events: readonly [T, ...ReadonlyArray<T>];
268
+ /** Whether the run starts, from the event; synchronous. Omitted means always. */
269
+ readonly when?: (event: PlatformEventOf<T>) => boolean;
270
+ /**
271
+ * The workflow's input, from the event; synchronous. Omitted means `{}`, which the workflow's
272
+ * input must accept.
273
+ */
274
+ readonly input?: (event: PlatformEventOf<T>) => Input;
275
+ }
276
+ /**
277
+ * Declares a platform trigger; list it in `workflow(name, { triggers })`. The workflow starts for
278
+ * each listed event the platform records for this workspace, and its runs act as the workflow's
279
+ * own user. A workflow that follows a deployment declares one; work that follows another workflow
280
+ * stays in that workflow, since workflow runs are not events.
281
+ */
282
+ export declare function platform<const Name extends string, const T extends PlatformEventType, Input = unknown>(name: Name, options: PlatformOptions<T, Input>): PlatformTrigger<Name, Input>;
283
+ /**
284
+ * What starts a workflow on its own. A discriminated union on `kind`: `cron`, `action`, `webhook`
285
+ * and `platform`; other kinds are additions.
240
286
  */
241
- export type WorkflowTrigger<Input = unknown> = CronTrigger<string, Input> | ActionTrigger<string, Input> | WebhookTrigger;
287
+ export type WorkflowTrigger<Input = unknown> = CronTrigger<string, Input> | ActionTrigger<string, Input> | WebhookTrigger | PlatformTrigger<string, Input>;
242
288
  export interface AfterOptions<Event, T, Input> extends TriggerRuns {
243
289
  /** Required, like every declaration: which actions start the workflow and why. */
244
290
  readonly description: string;
@@ -287,13 +333,15 @@ export interface WorkflowRunContext {
287
333
  readonly startedBy: {
288
334
  readonly kind: "trigger";
289
335
  /** The trigger's kind; runs started before it was recorded omit it. */
290
- readonly triggerKind?: "cron" | "action" | "webhook";
336
+ readonly triggerKind?: "cron" | "action" | "webhook" | "platform";
291
337
  /** `<workflow>.<trigger>`, in wire names. */
292
338
  readonly trigger: string;
293
339
  /** For an action trigger: the action whose commit started the run. */
294
340
  readonly actionId?: string;
295
341
  /** For an action trigger evaluated per edited record: that record. */
296
342
  readonly recordId?: string;
343
+ /** For a platform trigger: the id of the event that started the run. */
344
+ readonly event?: string;
297
345
  } | {
298
346
  readonly kind: "member";
299
347
  readonly userId: string;
@@ -332,8 +380,8 @@ export interface WorkflowOptions<S extends AnyInputSchema | undefined = undefine
332
380
  /** The `"use workflow"` function. It receives the decoded input. */
333
381
  readonly run: WorkflowFunction<InputOf<S>>;
334
382
  /**
335
- * What starts the workflow on its own: `cron(…)`, `after(…)` or `webhook(…)`. None means the
336
- * app, the CLI or another workflow.
383
+ * What starts the workflow on its own: `cron(…)`, `after(…)`, `webhook(…)` or `platform(…)`.
384
+ * None means the app, the CLI or another workflow.
337
385
  */
338
386
  readonly triggers?: ReadonlyArray<WorkflowTrigger>;
339
387
  /**