@composable-os/cli 0.0.0-stage → 0.1.0-beta.8

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.
Files changed (140) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/blocks-DEELKGDC.js +233 -0
  4. package/dist/chunk-2ABSVMGB.js +13 -0
  5. package/dist/chunk-2S7375SC.js +802 -0
  6. package/dist/chunk-5KSXSK7Y.js +47 -0
  7. package/dist/chunk-6UWRT4VM.js +220 -0
  8. package/dist/chunk-E5JLTLRM.js +50 -0
  9. package/dist/chunk-G3ORKXVP.js +1178 -0
  10. package/dist/chunk-HDIOVFAZ.js +544 -0
  11. package/dist/chunk-KGHA67HG.js +765 -0
  12. package/dist/chunk-KOKYDJ7Z.js +1423 -0
  13. package/dist/chunk-KTXGEXTY.js +358 -0
  14. package/dist/chunk-LTQDLCP7.js +16486 -0
  15. package/dist/chunk-MAXLUQKB.js +1287 -0
  16. package/dist/chunk-STJZJIRA.js +11378 -0
  17. package/dist/chunk-X6I2LWB3.js +24319 -0
  18. package/dist/chunk-XDDBLYKW.js +29154 -0
  19. package/dist/chunk-ZRWF6QZS.js +2357 -0
  20. package/dist/cli-BRSACHSG.js +31393 -0
  21. package/dist/cli-DTMGNDXN.js +121 -0
  22. package/dist/cli.js +25 -0
  23. package/dist/client-repo-ZVZ6KW5S.js +55 -0
  24. package/dist/create.js +25 -0
  25. package/dist/fields-64BQJA62.js +48 -0
  26. package/dist/invoke-NHHOLLF6.js +26 -0
  27. package/dist/person-WMWRF2HV.js +58 -0
  28. package/dist/platform/migrations/0001_init.sql +59 -0
  29. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  30. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  31. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  32. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  33. package/dist/platform/migrations/0006_search.sql +223 -0
  34. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  35. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  36. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  37. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  38. package/dist/platform/migrations/0020_extensions.sql +373 -0
  39. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  40. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  41. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  42. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  43. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  44. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  45. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  46. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  47. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  48. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  49. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  50. package/dist/platform/migrations/0110_integrations.sql +103 -0
  51. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  52. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  53. package/dist/platform/migrations/0130_automations.sql +113 -0
  54. package/dist/platform/migrations/0131_notifications.sql +29 -0
  55. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  56. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  57. package/dist/platform/migrations/0160_releases.sql +41 -0
  58. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  59. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  60. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  61. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  62. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  63. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  64. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  65. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  66. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  67. package/dist/platform/migrations/0250_judge.sql +11 -0
  68. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  69. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  70. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  71. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  72. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  73. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  74. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  75. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  76. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  77. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  78. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  79. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  80. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  81. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  82. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  83. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  84. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  85. package/dist/platform/migrations/0365_routines.sql +38 -0
  86. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  87. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  88. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  89. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  90. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  91. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  92. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  93. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  94. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  95. package/dist/platform/migrations/0421_orders.sql +134 -0
  96. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  97. package/dist/platform/migrations/0440_capacity.sql +100 -0
  98. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  99. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  100. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  101. package/dist/platform/migrations/0460_content.sql +59 -0
  102. package/dist/platform/migrations/0461_media.sql +52 -0
  103. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  104. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  105. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  106. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  107. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  108. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  109. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  110. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  111. package/dist/platform/sdk/automation-check.ts +534 -0
  112. package/dist/platform/sdk/automation.ts +743 -0
  113. package/dist/platform/sdk/behaviour.ts +215 -0
  114. package/dist/platform/sdk/capacity.ts +112 -0
  115. package/dist/platform/sdk/contract.ts +766 -0
  116. package/dist/platform/sdk/document.ts +788 -0
  117. package/dist/platform/sdk/field-types.ts +106 -0
  118. package/dist/platform/sdk/formula/ast.ts +72 -0
  119. package/dist/platform/sdk/formula/compile.ts +454 -0
  120. package/dist/platform/sdk/formula/index.ts +4 -0
  121. package/dist/platform/sdk/formula/parser.ts +417 -0
  122. package/dist/platform/sdk/index.ts +33 -0
  123. package/dist/platform/sdk/manifest.ts +1484 -0
  124. package/dist/platform/sdk/media.ts +46 -0
  125. package/dist/platform/sdk/permissions.ts +60 -0
  126. package/dist/platform/sdk/renamed.ts +63 -0
  127. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  128. package/dist/platform/sdk/rich-text.ts +173 -0
  129. package/dist/platform/sdk/runtime.ts +410 -0
  130. package/dist/platform/sdk/sellable.ts +396 -0
  131. package/dist/platform/sdk/slug.ts +25 -0
  132. package/dist/platform/sdk/states.ts +162 -0
  133. package/dist/platform/sdk/testing.ts +836 -0
  134. package/dist/products-2H5DR232.js +11 -0
  135. package/dist/run-4JNFLYXV.js +847 -0
  136. package/dist/src-G6OF5SKW.js +31 -0
  137. package/dist/src-J27WXNLY.js +270 -0
  138. package/dist/token-MOJUA2U6.js +70 -0
  139. package/dist/token-util-TENRN4V7.js +6 -0
  140. package/package.json +33 -4
@@ -0,0 +1,743 @@
1
+ // Automations (ADR 0028, ADR 0130, ADR 0131): `defineAutomation` declares a trigger, optional
2
+ // declarative conditions, the steps it takes (with their intents: what they read, write, notify
3
+ // and wait for) and a `run` handler shaped like a Cloudflare Workflow. The host renders the
4
+ // plain-English summary and step diagram from the declarations alone (no AI), evaluates the
5
+ // conditions before it starts a run, and runs `run` durably on Cloudflare Workflows: every
6
+ // `step.do` executes in a Dynamic Worker as actor `automation` under the extension principal.
7
+ //
8
+ // The declarations are the contract the diagram, the summary and the approval screen show, so the
9
+ // runtime holds `run` to them: every `step.do` / `step.sleep` / `step.waitForEvent` name must be a
10
+ // declared step of the matching kind. Effects a step did not declare are still gated at run time
11
+ // (and flagged in the run history), never silently allowed.
12
+ import { z } from "zod";
13
+ import {
14
+ type ExtensionContext,
15
+ type FilterOp,
16
+ GATEKEEPER_MODULES,
17
+ type GatekeeperModuleName,
18
+ type StageType,
19
+ type ViewFilter,
20
+ } from "./contract.ts";
21
+
22
+ // ---------------------------------------------------------------------------------------------
23
+ // Durations
24
+
25
+ /** `"3 days"`, `"90 minutes"`, `"1 week"`, or milliseconds. */
26
+ export type Duration =
27
+ | number
28
+ | `${number} ${"second" | "seconds" | "minute" | "minutes" | "hour" | "hours" | "day" | "days" | "week" | "weeks"}`;
29
+
30
+ const UNIT_MS: Record<string, number> = {
31
+ second: 1_000,
32
+ minute: 60_000,
33
+ hour: 3_600_000,
34
+ day: 86_400_000,
35
+ week: 604_800_000,
36
+ };
37
+
38
+ /** Milliseconds in a duration. Throws on a malformed one. */
39
+ export function durationMs(duration: Duration): number {
40
+ if (typeof duration === "number") {
41
+ if (!Number.isFinite(duration) || duration < 0) throw new Error("Durations are >= 0 ms");
42
+ return duration;
43
+ }
44
+ const match = /^\s*(\d+(?:\.\d+)?)\s+(second|minute|hour|day|week)s?\s*$/.exec(duration);
45
+ if (!match) throw new Error(`"${duration}" is not a duration like "3 days" or "90 minutes"`);
46
+ return Math.round(Number(match[1]) * (UNIT_MS[match[2] as string] as number));
47
+ }
48
+
49
+ // ---------------------------------------------------------------------------------------------
50
+ // Triggers
51
+
52
+ /** Record lifecycle events every core and extension object emits after commit. */
53
+ export const RECORD_EVENTS = ["created", "updated", "deleted", "restored"] as const;
54
+ export type RecordEventType = (typeof RECORD_EVENTS)[number];
55
+
56
+ /**
57
+ * A value a `fieldChanged` trigger compares a field's before / after value with: a literal, one
58
+ * of several literals, or (for an object's stage relation) the type of the stage.
59
+ */
60
+ export type ValueMatch =
61
+ | string
62
+ | number
63
+ | boolean
64
+ | null
65
+ | { in: readonly (string | number | boolean | null)[] }
66
+ | { stageType: StageType };
67
+
68
+ /**
69
+ * Sync events (stage 6, ADR 0112): what the built-in email and calendar sync records when it
70
+ * writes, updates or removes an activity. `meeting.scheduled` is a new meeting (the sync service
71
+ * records it as `meeting.created`; both names match it).
72
+ */
73
+ export const SYNC_EVENT_TYPES = [
74
+ "email.received",
75
+ "email.sent",
76
+ "email.deleted",
77
+ "meeting.scheduled",
78
+ "meeting.created",
79
+ "meeting.updated",
80
+ "meeting.cancelled",
81
+ ] as const;
82
+ export type SyncEventType = (typeof SYNC_EVENT_TYPES)[number];
83
+
84
+ /**
85
+ * What starts a run. Inbound webhooks and sync events (stage 6b) come from integrations; the host
86
+ * dispatches each kind of event to its own trigger source.
87
+ */
88
+ export type AutomationTrigger =
89
+ | {
90
+ /** A record of `object` was created, updated, deleted (to Trash) or restored. */
91
+ type: "record";
92
+ /** Core (`person`, `organisation`, `task`, `activity`) or `<extension>.<object>`. */
93
+ object: string;
94
+ on: readonly RecordEventType[];
95
+ /**
96
+ * Also fire for records changed by bulk operations (imports, `*Many`, backfills). Off by
97
+ * default: one import must not start thousands of runs (cost audit U3).
98
+ */
99
+ includeBulk?: boolean;
100
+ }
101
+ | {
102
+ /** A field of a record of `object` changed, optionally from / to given values. */
103
+ type: "fieldChanged";
104
+ object: string;
105
+ field: string;
106
+ from?: ValueMatch;
107
+ to?: ValueMatch;
108
+ includeBulk?: boolean;
109
+ }
110
+ | {
111
+ /**
112
+ * A cron expression (5 fields: minute hour day-of-month month day-of-week), evaluated in
113
+ * the deployment's automation timezone (Settings → Automations). The finest granularity
114
+ * is the host's cron tick (one minute).
115
+ */
116
+ type: "schedule";
117
+ cron: string;
118
+ }
119
+ | {
120
+ /**
121
+ * `offsetDays` days after (positive) or before (negative) a date field of each live record
122
+ * of `object`; 0 is the day itself. Evaluated once a day, in the automation timezone; or,
123
+ * with `zoneField`, in each record's own time zone (ADR 0460): the day of the date and
124
+ * "today" are both that zone's, and the run starts in the first hour of that local day.
125
+ */
126
+ type: "dateRelative";
127
+ object: string;
128
+ field: string;
129
+ offsetDays: number;
130
+ /** A `timezone` field of `object`: count days in the zone each record names. */
131
+ zoneField?: string;
132
+ }
133
+ | {
134
+ /**
135
+ * A person starts it from a record page (a button) or for selected records on a list (a
136
+ * bulk action, when `bulk` is true).
137
+ */
138
+ type: "manual";
139
+ object: string;
140
+ /** The button's label, e.g. "Send renewal reminder". */
141
+ label: string;
142
+ bulk?: boolean;
143
+ }
144
+ | {
145
+ /** A pending action was decided in the Approvals inbox. */
146
+ type: "approvalDecided";
147
+ /** Default `any`. */
148
+ decision?: "approved" | "rejected" | "any";
149
+ /** Only actions of this operation (e.g. `record.update`). */
150
+ operation?: string;
151
+ /** Only actions touching records of this object. */
152
+ object?: string;
153
+ }
154
+ | {
155
+ /**
156
+ * A verified delivery to an inbound webhook endpoint (the `webhook` gatekeeper, ADR 0113).
157
+ * The run gets the typed event in `event.integration` (`payload.payload` is the sender's
158
+ * JSON).
159
+ */
160
+ type: "webhook";
161
+ /** The endpoint id an admin set up (`webhook://endpoint/<id>`), e.g. `stripe-billing`. */
162
+ endpoint: string;
163
+ /** Only these event types (e.g. `invoice.paid`). Omitted: every event. */
164
+ events?: readonly string[];
165
+ }
166
+ | {
167
+ /**
168
+ * Email or calendar sync wrote, changed or removed an activity (ADR 0112). The trigger
169
+ * record is that activity; the event carries ids only, never content.
170
+ */
171
+ type: "syncEvent";
172
+ event: SyncEventType;
173
+ /**
174
+ * Only when the email or meeting is linked to a known `person`, a known `organisation`, or
175
+ * (the default) `either`. Sync records activities only for known people and organisations.
176
+ */
177
+ from?: "person" | "organisation" | "either";
178
+ };
179
+
180
+ export type AutomationTriggerType = AutomationTrigger["type"];
181
+ export const AUTOMATION_TRIGGER_TYPES = [
182
+ "record",
183
+ "fieldChanged",
184
+ "schedule",
185
+ "dateRelative",
186
+ "manual",
187
+ "approvalDecided",
188
+ "webhook",
189
+ "syncEvent",
190
+ ] as const satisfies readonly AutomationTriggerType[];
191
+
192
+ /**
193
+ * A connection an automation needs (ADR 0051, ADR 0170). When the automation is approved or
194
+ * installed, a person binds each one to a connection they own or to an org connection; steps then
195
+ * reach it with `ctx.gatekeeper(gatekeeper).call(id, resource, method, ...args)`, acting as that
196
+ * connection's owner. Until every declared connection is bound, the automation does not run.
197
+ */
198
+ export interface AutomationConnection {
199
+ /** camelCase, unique within the automation: what steps pass as the connection id. */
200
+ id: string;
201
+ /** The gatekeeper (host module) it is a connection of; declare it in permissions.modules. */
202
+ gatekeeper: GatekeeperModuleName;
203
+ /** Why it needs it, shown to the person binding it ("Send the welcome email"). */
204
+ purpose: string;
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------------------------
208
+ // Steps and their intents
209
+
210
+ /**
211
+ * Who a notification goes to. `{ field }` is a `user` field of the trigger record (e.g. a deal's
212
+ * `owner`); `{ managerOf }` is the manager of the user in that field, or the admins when the
213
+ * deployment has no manager for them (the Deals README says so); `admins` is every admin.
214
+ */
215
+ export type Recipient =
216
+ | { field: string }
217
+ | { managerOf: string }
218
+ | { userId: string }
219
+ | "admins"
220
+ | "actor";
221
+
222
+ /** One kind of record a step creates or changes. */
223
+ export interface WriteIntent {
224
+ /** Core or `<extension>.<object>`. */
225
+ object: string;
226
+ /** Default `create`. */
227
+ action?: "create" | "update" | "delete";
228
+ /** How many records, when fixed (e.g. 3 onboarding tasks). Omitted: "one or more". */
229
+ count?: number;
230
+ /** Titles of the records created, when fixed: shown in the diagram. */
231
+ titles?: readonly string[];
232
+ /** For tasks: who they are assigned to. */
233
+ assignTo?: Recipient;
234
+ /** Linked to the trigger record. Default true for tasks and activities. */
235
+ linkedToTrigger?: boolean;
236
+ }
237
+
238
+ /** A notification a step sends (through `notification.send`). */
239
+ export interface NotifyIntent {
240
+ to: Recipient;
241
+ /** The title as written, with `{record}` standing for the trigger record's title. */
242
+ message: string;
243
+ /** The body as written, when it sends one (shortened in the host summary). */
244
+ body?: string;
245
+ }
246
+
247
+ interface StepBase {
248
+ /** Unique within the automation, camelCase: what `run` passes to `step.*`. */
249
+ name: string;
250
+ /** Short label for the diagram ("Create onboarding tasks"). Default: the name, humanised. */
251
+ label?: string;
252
+ }
253
+
254
+ /**
255
+ * A declared step. `do` steps run extension code; `sleep` and `waitForEvent` are durable waits;
256
+ * a `condition` is a branch `run` takes in code, declared so the diagram shows it (the steps
257
+ * after it run only when it holds).
258
+ */
259
+ export type AutomationStep =
260
+ | (StepBase & {
261
+ kind?: "do";
262
+ /** Objects it reads. */
263
+ reads?: readonly string[];
264
+ writes?: readonly WriteIntent[];
265
+ notifies?: readonly NotifyIntent[];
266
+ /** Further operations it calls (e.g. `query.sql`), for the permissions summary. */
267
+ calls?: readonly string[];
268
+ })
269
+ | (StepBase & { kind: "sleep"; duration: Duration })
270
+ | (StepBase & {
271
+ kind: "waitForEvent";
272
+ /** The event type `step.waitForEvent` waits for. */
273
+ event: string;
274
+ /** Default 7 days. */
275
+ timeout?: Duration;
276
+ })
277
+ | (StepBase & {
278
+ kind: "condition";
279
+ /** The question, e.g. "Any onboarding task still open?". */
280
+ label: string;
281
+ /**
282
+ * The condition as the summary says it after "if", e.g. "any of those tasks are still
283
+ * open". Default: the label, lower-cased, without its question mark.
284
+ */
285
+ clause?: string;
286
+ });
287
+
288
+ /** What happens when a person rejects a change a run queued for approval. Default `stop`. */
289
+ export type OnRejected = "stop" | "continue" | { notify: Recipient; message?: string };
290
+
291
+ /** Per-automation limits, within the host's maxima (Settings shows both). */
292
+ export interface AutomationRails {
293
+ /** Default 60. Above it the automation auto-pauses and admins are notified. */
294
+ maxRunsPerMinute?: number;
295
+ /** Default 500 writes an hour across all its runs. */
296
+ maxWritesPerHour?: number;
297
+ /** Seconds within which `updated` events for one record coalesce into one run. */
298
+ debounceSeconds?: number;
299
+ }
300
+
301
+ // ---------------------------------------------------------------------------------------------
302
+ // The run handler
303
+
304
+ /** The event a run starts from, as `run` receives it. */
305
+ export interface AutomationEvent {
306
+ /** `<extension>.<automation>` */
307
+ automation: string;
308
+ runId: string;
309
+ trigger: AutomationTriggerType;
310
+ /** The trigger record (record, fieldChanged, dateRelative, manual), as read when the run started. */
311
+ record?: {
312
+ object: string;
313
+ id: string;
314
+ data: Record<string, unknown> | null;
315
+ /** The record's title when the run started (what `{record}` in a notification stands for). */
316
+ title?: string | null;
317
+ };
318
+ /** record / fieldChanged: what changed. `diff` holds changed fields only. */
319
+ change?: {
320
+ action: RecordEventType;
321
+ diff: Record<string, { before: unknown; after: unknown }>;
322
+ };
323
+ /** schedule / dateRelative: the period this run is for, e.g. `2026-11-05` or `2026-11-05T09:00`. */
324
+ period?: string;
325
+ /** manual: who started it, and every selected record for a bulk action. */
326
+ manual?: { userId: string; recordIds: string[] };
327
+ /** approvalDecided: the decided action. */
328
+ approval?: {
329
+ actionId: string;
330
+ operation: string;
331
+ decision: "approved" | "rejected";
332
+ records: { object: string; id: string }[];
333
+ };
334
+ /**
335
+ * webhook / syncEvent: the integration event. Webhooks carry the sender's verified JSON in
336
+ * `payload.payload`; sync events carry ids only (`activityId`, `personIds`, `organisationIds`).
337
+ */
338
+ integration?: {
339
+ eventId: string;
340
+ source: "webhook" | "sync";
341
+ type: string;
342
+ connectionId: string | null;
343
+ payload: unknown;
344
+ };
345
+ /** True in test mode: writes are simulated, waits are skipped. */
346
+ test: boolean;
347
+ }
348
+
349
+ /** The Workflow-shaped step API `run` receives. */
350
+ export interface AutomationStepApi {
351
+ /**
352
+ * Runs `fn` once, durably: its result is stored, and a run resumed after a restart or a wait
353
+ * gets the stored result instead of running it again. It is retried with backoff when it
354
+ * throws. `name` must be a declared `do` step (an intent here is checked against it).
355
+ */
356
+ do<T>(name: string, fn: () => Promise<T> | T): Promise<T>;
357
+ do<T>(
358
+ name: string,
359
+ intent: Omit<Extract<AutomationStep, { kind?: "do" }>, "name" | "kind">,
360
+ fn: () => Promise<T> | T,
361
+ ): Promise<T>;
362
+ /** A durable wait (survives redeploys). Skipped, and shown, in test mode. */
363
+ sleep(name: string, duration: Duration): Promise<void>;
364
+ /** Waits for an event of the declared type; null on timeout. Skipped (null) in test mode. */
365
+ waitForEvent<T = unknown>(name: string): Promise<T | null>;
366
+ }
367
+
368
+ /** `ctx` in `run`: the extension's host modules plus notifications. */
369
+ export interface AutomationContext extends ExtensionContext {
370
+ /**
371
+ * Sends an in-app notification through `notification.send` (the extension needs it in
372
+ * `permissions.operations`). `{record}` in the title stands for the trigger record's title.
373
+ */
374
+ notify(
375
+ to: Recipient | Recipient[],
376
+ message: { title: string; body?: string; link?: "record" | "run" },
377
+ ): Promise<{ sent: number }>;
378
+ }
379
+
380
+ export interface AutomationSpec<T extends AutomationTrigger = AutomationTrigger> {
381
+ /** Name shown in the list and on the automation page, e.g. "Won deal → onboarding". */
382
+ label: string;
383
+ /** One or two sentences for people and models: what and why. */
384
+ description: string;
385
+ trigger: T;
386
+ /**
387
+ * Declarative conditions on the trigger record (the same filter language as views), checked
388
+ * by the host before a run starts, and rendered in the summary.
389
+ */
390
+ conditions?: ViewFilter;
391
+ /** Every step `run` may take, in order. */
392
+ steps: readonly AutomationStep[];
393
+ onRejected?: OnRejected;
394
+ rails?: AutomationRails;
395
+ /** Connections it needs, bound by a person when it is approved or installed. */
396
+ connections?: readonly AutomationConnection[];
397
+ /**
398
+ * `false`: installed turned off; a person turns it on under Automations (ADR 0246). Only the
399
+ * first install reads it; after that, on or off is the person's choice.
400
+ */
401
+ enabled?: boolean;
402
+ run(event: AutomationEvent, step: AutomationStepApi, ctx: AutomationContext): Promise<unknown>;
403
+ }
404
+
405
+ export function defineAutomation<const T extends AutomationTrigger>(
406
+ automation: AutomationSpec<T>,
407
+ ): AutomationSpec<T> {
408
+ return automation;
409
+ }
410
+
411
+ // ---------------------------------------------------------------------------------------------
412
+ // Manifest form (JSON: no handler). Stored in core_automations.spec.
413
+
414
+ const scalar = z.union([z.string().max(500), z.number(), z.boolean(), z.null()]);
415
+ export const valueMatchSchema = z.union([
416
+ scalar,
417
+ z.object({ in: z.array(scalar).min(1).max(50) }).strict(),
418
+ z.object({ stageType: z.enum(["open", "won", "lost"]) }).strict(),
419
+ ]);
420
+
421
+ const objectName = z.string().min(1).max(80);
422
+ const fieldName = z.string().min(1).max(80);
423
+
424
+ export const automationTriggerSchema = z.discriminatedUnion("type", [
425
+ z
426
+ .object({
427
+ type: z.literal("record"),
428
+ object: objectName,
429
+ on: z.array(z.enum(RECORD_EVENTS)).min(1).max(4),
430
+ includeBulk: z.boolean().optional(),
431
+ })
432
+ .strict(),
433
+ z
434
+ .object({
435
+ type: z.literal("fieldChanged"),
436
+ object: objectName,
437
+ field: fieldName,
438
+ from: valueMatchSchema.optional(),
439
+ to: valueMatchSchema.optional(),
440
+ includeBulk: z.boolean().optional(),
441
+ })
442
+ .strict(),
443
+ z.object({ type: z.literal("schedule"), cron: z.string().min(9).max(100) }).strict(),
444
+ z
445
+ .object({
446
+ type: z.literal("dateRelative"),
447
+ object: objectName,
448
+ field: fieldName,
449
+ offsetDays: z.number().int().min(-365).max(365),
450
+ zoneField: fieldName.optional(),
451
+ })
452
+ .strict(),
453
+ z
454
+ .object({
455
+ type: z.literal("manual"),
456
+ object: objectName,
457
+ label: z.string().min(1).max(60),
458
+ bulk: z.boolean().optional(),
459
+ })
460
+ .strict(),
461
+ z
462
+ .object({
463
+ type: z.literal("approvalDecided"),
464
+ decision: z.enum(["approved", "rejected", "any"]).optional(),
465
+ operation: z.string().max(100).optional(),
466
+ object: objectName.optional(),
467
+ })
468
+ .strict(),
469
+ z
470
+ .object({
471
+ type: z.literal("webhook"),
472
+ endpoint: z
473
+ .string()
474
+ .min(1)
475
+ .max(64)
476
+ .regex(/^[a-z0-9][a-z0-9_-]*$/, "Endpoint ids are lowercase letters, digits, - and _"),
477
+ events: z.array(z.string().min(1).max(200)).min(1).max(50).optional(),
478
+ })
479
+ .strict(),
480
+ z
481
+ .object({
482
+ type: z.literal("syncEvent"),
483
+ event: z.enum(SYNC_EVENT_TYPES),
484
+ from: z.enum(["person", "organisation", "either"]).optional(),
485
+ })
486
+ .strict(),
487
+ ]);
488
+
489
+ export const automationConnectionSchema = z
490
+ .object({
491
+ id: z.string().min(1).max(40),
492
+ gatekeeper: z.enum(GATEKEEPER_MODULES),
493
+ purpose: z.string().min(1).max(200),
494
+ })
495
+ .strict();
496
+
497
+ export const durationSchema = z.union([
498
+ z.number().int().min(0),
499
+ z.string().regex(/^\s*\d+(?:\.\d+)?\s+(second|minute|hour|day|week)s?\s*$/),
500
+ ]);
501
+
502
+ export const recipientSchema = z.union([
503
+ z.literal("admins"),
504
+ z.literal("actor"),
505
+ z.object({ field: fieldName }).strict(),
506
+ z.object({ managerOf: fieldName }).strict(),
507
+ z.object({ userId: z.string().min(1).max(64) }).strict(),
508
+ ]);
509
+
510
+ const writeIntentSchema = z
511
+ .object({
512
+ object: objectName,
513
+ action: z.enum(["create", "update", "delete"]).optional(),
514
+ count: z.number().int().min(1).max(10_000).optional(),
515
+ titles: z.array(z.string().max(200)).max(50).optional(),
516
+ assignTo: recipientSchema.optional(),
517
+ linkedToTrigger: z.boolean().optional(),
518
+ })
519
+ .strict();
520
+
521
+ const notifyIntentSchema = z
522
+ .object({
523
+ to: recipientSchema,
524
+ message: z.string().min(1).max(500),
525
+ body: z.string().min(1).max(2000).optional(),
526
+ })
527
+ .strict();
528
+
529
+ const stepName = z.string().min(1).max(60);
530
+ const stepLabel = z.string().min(1).max(120).optional();
531
+
532
+ export const automationStepSchema = z.union([
533
+ z
534
+ .object({
535
+ name: stepName,
536
+ label: stepLabel,
537
+ kind: z.literal("do").optional(),
538
+ reads: z.array(objectName).max(50).optional(),
539
+ writes: z.array(writeIntentSchema).max(20).optional(),
540
+ notifies: z.array(notifyIntentSchema).max(20).optional(),
541
+ calls: z.array(z.string().max(100)).max(50).optional(),
542
+ })
543
+ .strict(),
544
+ z
545
+ .object({
546
+ name: stepName,
547
+ label: stepLabel,
548
+ kind: z.literal("sleep"),
549
+ duration: durationSchema,
550
+ })
551
+ .strict(),
552
+ z
553
+ .object({
554
+ name: stepName,
555
+ label: stepLabel,
556
+ kind: z.literal("waitForEvent"),
557
+ event: z.string().min(1).max(100),
558
+ timeout: durationSchema.optional(),
559
+ })
560
+ .strict(),
561
+ z
562
+ .object({
563
+ name: stepName,
564
+ label: z.string().min(1).max(120),
565
+ kind: z.literal("condition"),
566
+ clause: z.string().min(1).max(200).optional(),
567
+ })
568
+ .strict(),
569
+ ]);
570
+
571
+ const filterOpSchema = z.enum([
572
+ "eq",
573
+ "neq",
574
+ "lt",
575
+ "lte",
576
+ "gt",
577
+ "gte",
578
+ "between",
579
+ "in",
580
+ "not_in",
581
+ "contains",
582
+ "not_contains",
583
+ "starts_with",
584
+ "ends_with",
585
+ "is_null",
586
+ "is_not_null",
587
+ ] as const satisfies readonly FilterOp[]);
588
+
589
+ export const automationConditionSchema: z.ZodType<ViewFilter> = z.lazy(() =>
590
+ z.union([
591
+ z.object({ field: fieldName, op: filterOpSchema, value: z.unknown().optional() }).strict(),
592
+ z.object({ and: z.array(automationConditionSchema).min(1).max(20) }).strict(),
593
+ z.object({ or: z.array(automationConditionSchema).min(1).max(20) }).strict(),
594
+ ]),
595
+ ) as z.ZodType<ViewFilter>;
596
+
597
+ export const onRejectedSchema = z.union([
598
+ z.literal("stop"),
599
+ z.literal("continue"),
600
+ z.object({ notify: recipientSchema, message: z.string().max(500).optional() }).strict(),
601
+ ]);
602
+
603
+ export const automationRailsSchema = z
604
+ .object({
605
+ maxRunsPerMinute: z.number().int().min(1).max(600).optional(),
606
+ maxWritesPerHour: z.number().int().min(1).max(100_000).optional(),
607
+ debounceSeconds: z.number().int().min(0).max(3600).optional(),
608
+ })
609
+ .strict();
610
+
611
+ export const automationManifestSchema = z.object({
612
+ label: z.string().min(1).max(100),
613
+ description: z.string().min(1).max(2000),
614
+ trigger: automationTriggerSchema,
615
+ conditions: automationConditionSchema.optional(),
616
+ steps: z.array(automationStepSchema).min(1).max(50),
617
+ onRejected: onRejectedSchema.optional(),
618
+ rails: automationRailsSchema.optional(),
619
+ connections: z.array(automationConnectionSchema).max(10).optional(),
620
+ enabled: z.boolean().optional(),
621
+ });
622
+ export type AutomationManifest = z.infer<typeof automationManifestSchema>;
623
+
624
+ // ---------------------------------------------------------------------------------------------
625
+ // The runtime protocol between the host (a Workflow) and the Dynamic Worker (ADR 0130)
626
+ //
627
+ // The host replays `run` from the start on every advance, with a journal of the steps already
628
+ // done; the SDK runtime returns stored results for those, runs the first new `step.do` and stops
629
+ // there (or stops at the first new sleep / wait, without running anything). The host wraps each
630
+ // advance in a Workflow `step.do`, so a finished advance is never repeated after a restart, and
631
+ // performs sleeps and waits as Workflow `step.sleep` / `step.waitForEvent`.
632
+
633
+ export interface AutomationJournalEntry {
634
+ name: string;
635
+ kind: "do" | "sleep" | "waitForEvent";
636
+ /** The step.do result, or the waitForEvent payload (null on timeout); null for a sleep. */
637
+ value: unknown;
638
+ }
639
+
640
+ export interface AutomationRunRequest {
641
+ /** The automation's key in `automations`. */
642
+ automation: string;
643
+ event: AutomationEvent;
644
+ journal: AutomationJournalEntry[];
645
+ /** `advance`: run one new step and stop. `test`: run to the end, skipping waits. */
646
+ mode: "advance" | "test";
647
+ version: string;
648
+ }
649
+
650
+ /** What one advance did. */
651
+ export type AutomationAdvance =
652
+ /** Ran the step.do `name` (the host calls `operations` it made through codemode:ops). */
653
+ | { kind: "do"; name: string; value: unknown }
654
+ /** Stopped at a sleep: the host sleeps `ms`, journals it and advances again. */
655
+ | { kind: "sleep"; name: string; ms: number }
656
+ /** Stopped at a wait: the host waits for `event` up to `timeoutMs`. */
657
+ | { kind: "waitForEvent"; name: string; event: string; timeoutMs: number }
658
+ /** `run` returned. */
659
+ | { kind: "done"; value: unknown };
660
+
661
+ /** One step as test mode reports it (every step, in order, waits included). */
662
+ export interface AutomationTestStep {
663
+ name: string;
664
+ kind: "do" | "sleep" | "waitForEvent";
665
+ /** do: its result. sleep / waitForEvent: skipped, and how long it would wait. */
666
+ value?: unknown;
667
+ skippedMs?: number;
668
+ }
669
+
670
+ // ---------------------------------------------------------------------------------------------
671
+ // ctx.notify → notification.send
672
+
673
+ /** One recipient as `notification.send` takes it (core `recipientInputSchema`). */
674
+ export type NotificationRecipientInput =
675
+ | { userId: string }
676
+ | { role: "admin" }
677
+ | { field: string; record: { object: string; id: string } }
678
+ | { managerOf: string; record: { object: string; id: string } };
679
+
680
+ /** The `notification.send` input `ctx.notify(to, message)` makes for a run. */
681
+ export interface NotificationSendInput {
682
+ to: NotificationRecipientInput[];
683
+ type: "automation.message";
684
+ title: string;
685
+ body?: string;
686
+ link?:
687
+ | { kind: "record"; object: string; id: string }
688
+ | { kind: "automationRun"; automationId: string; runId: string };
689
+ dedupeKey: string;
690
+ }
691
+
692
+ /**
693
+ * Turns `ctx.notify(to, message)` into a `notification.send` input for `event`'s run: field and
694
+ * manager recipients point at the trigger record, `"actor"` is whoever started a manual run,
695
+ * `{record}` in the title and body becomes the trigger record's title, and the dedupe key
696
+ * (`<runId>:<key>`, key = `<step name>:<n>` with n counting notify calls within that step, so it is the same on every replay) makes a retried or replayed step send each
697
+ * notification once. Shared by the runtime and the testing harness.
698
+ */
699
+ export function notificationInput(
700
+ event: AutomationEvent,
701
+ to: Recipient | readonly Recipient[],
702
+ message: { title: string; body?: string; link?: "record" | "run" },
703
+ key: string,
704
+ ): NotificationSendInput {
705
+ const record = event.record;
706
+ const recipients: readonly Recipient[] = Array.isArray(to) ? to : [to as Recipient];
707
+ const resolved = recipients.map((recipient): NotificationRecipientInput => {
708
+ if (recipient === "admins") return { role: "admin" };
709
+ if (recipient === "actor") {
710
+ const userId = event.manual?.userId;
711
+ if (!userId)
712
+ throw new Error('"actor" recipients need a manual trigger (a person started it)');
713
+ return { userId };
714
+ }
715
+ if ("userId" in recipient) return { userId: recipient.userId };
716
+ if (!record) {
717
+ throw new Error(
718
+ `A ${event.trigger} run has no trigger record, so ${JSON.stringify(recipient)} cannot be resolved`,
719
+ );
720
+ }
721
+ const ref = { object: record.object, id: record.id };
722
+ return "field" in recipient
723
+ ? { field: recipient.field, record: ref }
724
+ : { managerOf: recipient.managerOf, record: ref };
725
+ });
726
+ const title = record?.title ?? "the record";
727
+ const fill = (text: string) => text.replaceAll("{record}", title);
728
+ const wanted = message.link ?? (record ? "record" : undefined);
729
+ const link =
730
+ wanted === "run"
731
+ ? { kind: "automationRun" as const, automationId: event.automation, runId: event.runId }
732
+ : wanted === "record" && record
733
+ ? { kind: "record" as const, object: record.object, id: record.id }
734
+ : undefined;
735
+ return {
736
+ to: resolved,
737
+ type: "automation.message",
738
+ title: fill(message.title).slice(0, 200),
739
+ ...(message.body === undefined ? {} : { body: fill(message.body) }),
740
+ ...(link ? { link } : {}),
741
+ dedupeKey: `${event.runId}:${key}`.slice(0, 200),
742
+ };
743
+ }