@cogover/sdk 0.10.0 → 0.12.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.
@@ -9,7 +9,8 @@ configured for the project.
9
9
 
10
10
  `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
11
11
  the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
12
- `push`, `jobs`, `secrets`, and `crypto`, awaits the handler, and serializes its result.
12
+ `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
13
+ result.
13
14
 
14
15
  ```typescript
15
16
  function defineScript<
@@ -40,9 +41,12 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
40
41
  readonly state: ProjectState;
41
42
  readonly locks: DistributedLocks;
42
43
  readonly push: PushApi<Schema>;
44
+ readonly notifications: NotificationsApi;
45
+ readonly email: EmailApi<Schema>;
43
46
  readonly jobs: JobsApi;
44
47
  readonly secrets: SecretsApi;
45
48
  readonly crypto: CryptoApi;
49
+ readonly org: OrgApi;
46
50
  }
47
51
  ```
48
52
 
@@ -53,7 +57,8 @@ Returning `null` produces a null handler result; returning `undefined` is invali
53
57
  ## HTTP routers and request context
54
58
 
55
59
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
56
- `log`, `state`, `locks`, `push`, `jobs`, `secrets`, and `crypto` to both script and route handlers. `input`
60
+ `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
61
+ and route handlers. `input`
57
62
  preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
58
63
  metadata and transport/authentication fields removed by Cogover.
59
64
 
@@ -537,9 +542,12 @@ interface TriggerContext<
537
542
  readonly schema: SchemaApi<Schema>;
538
543
  readonly log: ScriptLogger;
539
544
  readonly push: PushApi<Schema>;
545
+ readonly notifications: NotificationsApi;
546
+ readonly email: EmailApi<Schema>;
540
547
  readonly jobs: JobsApi;
541
548
  readonly secrets: SecretsApi;
542
549
  readonly crypto: CryptoApi;
550
+ readonly org: OrgApi;
543
551
  }
544
552
 
545
553
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -575,9 +583,10 @@ receives all records of the same change that run the trigger, up to 200 records
575
583
  once per record. Keep `fields` short, and read related data for the whole list with
576
584
  one `records.getMany` call rather than one read per record.
577
585
 
578
- `data`, `schema`, `log`, `invocation`, `push`, `jobs`, `secrets`, and `crypto` are the
579
- same APIs that scripts receive. A trigger context has no `input`, `request`, `response`,
580
- `state`, or `locks`; `push` is refused in a before-change trigger. `trigger.operation` is
586
+ `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
587
+ `crypto`, and `org` are the same APIs that scripts receive. A trigger context has no `input`,
588
+ `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
589
+ before-change trigger. `trigger.operation` is
581
590
  the operation of the current call, `trigger.id` identifies the trigger registration, and
582
591
  `trigger.changeId` identifies the record change that caused the call.
583
592
 
@@ -656,12 +665,14 @@ merges, and cascading deletes — do not run before-change triggers, and neither
656
665
  a request that only validates input without saving.
657
666
 
658
667
  - **Read-only.** A before-change trigger may read records and schema, but every
659
- record write, `fetch`, lock, state write, push message, `jobs.enqueue`, `secrets.get`,
660
- and every `crypto` operation with a `{ secret }` key is refused with
668
+ record write, `fetch`, lock, state write, push message, notification, email (including
669
+ `email.senders()`), `jobs.enqueue`, `secrets.get`, and every `crypto` operation with a
670
+ `{ secret }` key is refused with
661
671
  `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
662
672
  applies to every identity, including `data.asSystem()`. Every `crypto` operation
663
673
  with a key given in the call remains available, as do `crypto.sha256`,
664
- `crypto.randomBytes`, `crypto.randomUUID`, and `crypto.timingSafeEqual`.
674
+ `crypto.randomBytes`, `crypto.randomUUID`, `crypto.timingSafeEqual`, and every
675
+ [`org`](#organization-structure) read.
665
676
  - **Identity.** `data.object()` acts as the user who made the change, with that
666
677
  user's permissions, and `invocation` describes the same user. When a change has
667
678
  no user, `invocation.identity` is `"system"` and `data.object()` works only if the
@@ -723,9 +734,9 @@ export const triggers = [
723
734
  were saved, including the record ID and values assigned while saving, such as an
724
735
  auto number. For a deleted record `record.new` is `null` and `record.old` holds the
725
736
  last values.
726
- - **May write and call out.** Record writes, `fetch`, `push`, `jobs.enqueue`,
727
- `secrets.get`, and `crypto` work as they do in a script, within the same runtime
728
- limits. `data.object()` acts as the user who made the change, and the other identity
737
+ - **May write and call out.** Record writes, `fetch`, `push`, `notifications`, `email`,
738
+ `jobs.enqueue`, `secrets.get`, and `crypto` work as they do in a script, within the
739
+ same runtime limits. `data.object()` acts as the user who made the change, and the other identity
729
740
  rules of before-change triggers apply. The trigger context has no `state` or `locks`;
730
741
  `push` is the usual way to refresh the records the handler changed for everyone who
731
742
  has them open, and longer work, or work that needs `state` or `locks`, belongs in a
@@ -908,9 +919,12 @@ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspa
908
919
  readonly log: ScriptLogger;
909
920
  readonly state: ProjectState;
910
921
  readonly locks: DistributedLocks;
922
+ readonly notifications: NotificationsApi;
923
+ readonly email: EmailApi<Schema>;
911
924
  readonly jobs: JobsApi;
912
925
  readonly secrets: SecretsApi;
913
926
  readonly crypto: CryptoApi;
927
+ readonly org: OrgApi;
914
928
  }
915
929
 
916
930
  interface JobInfo {
@@ -925,9 +939,9 @@ interface JobInfo {
925
939
  ```
926
940
 
927
941
  A handler may be synchronous or asynchronous; its return value is ignored. `data`,
928
- `schema`, `log`, `invocation`, `state`, `locks`, `jobs`, `secrets`, and `crypto`
929
- are the same APIs that scripts receive. A job context has no `input`, `request`, or
930
- `response`.
942
+ `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
943
+ `secrets`, `crypto`, and `org` are the same APIs that scripts receive. A job context has
944
+ no `input`, `request`, `response`, or `push`.
931
945
 
932
946
  - `job.id` identifies the run and stays the same across its attempts; use it as the
933
947
  idempotency key of external calls. `job.attempt` starts at 1.
@@ -993,9 +1007,9 @@ Workspace, the error is `CogoverApiError` with `code: "JOBS_DISABLED"`.
993
1007
  policy sets `allowInternalSystem: true`; otherwise its calls throw
994
1008
  `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
995
1009
  `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
996
- - **Capabilities.** A job may do everything a script can: read and write records,
997
- call `fetch`, use `state` and `locks`, enqueue jobs, read secrets, and use
998
- `crypto`, within the runtime limits of the job lane.
1010
+ - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
1011
+ `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
1012
+ within the runtime limits of the job lane.
999
1013
  - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
1000
1014
  split: process one page, save the cursor, and enqueue the same job again with the
1001
1015
  cursor in the payload, as in the example above.
@@ -2102,6 +2116,612 @@ custom component listening for it. `content` is required (up to 16,384 character
2102
2116
  - A sent message cannot be recalled, and retrying a failed execution may send it
2103
2117
  again.
2104
2118
 
2119
+ ## Notifications
2120
+
2121
+ `notifications` saves a notification in the notification list (the bell) of each
2122
+ recipient and delivers it in the web app, by web push, by mobile push, and as an
2123
+ email copy, as the workspace's notification channels decide. Unlike a
2124
+ [push message](#push-messages), a notification stays in the list after it was
2125
+ delivered, so it suits something a person must act on later, such as an approval
2126
+ request. Delivery is asynchronous and best-effort: a call resolves once Cogover has
2127
+ accepted the notification, never when it reaches a device or an inbox.
2128
+
2129
+ ```typescript
2130
+ type NotificationContentType = "text" | "html";
2131
+ type NotificationDisplay = "SIMPLE" | "FULL";
2132
+ type NotificationSender = "workspace" | "actor";
2133
+ type NotificationLinkTarget = "SAME_TAB" | "NEW_TAB";
2134
+
2135
+ interface NotificationLink {
2136
+ readonly url: string;
2137
+ readonly openIn?: NotificationLinkTarget;
2138
+ }
2139
+
2140
+ interface NotificationMessage {
2141
+ readonly to: readonly string[];
2142
+ readonly exclude?: readonly string[];
2143
+ readonly title: string;
2144
+ readonly content: string;
2145
+ readonly contentType?: NotificationContentType;
2146
+ readonly subtitle?: string;
2147
+ readonly display?: NotificationDisplay;
2148
+ readonly link?: NotificationLink;
2149
+ readonly sender?: NotificationSender;
2150
+ readonly channel?: string;
2151
+ readonly email?: boolean;
2152
+ readonly idempotencyKey?: string;
2153
+ }
2154
+
2155
+ interface NotificationResult {
2156
+ readonly requestId: string;
2157
+ readonly notified: number;
2158
+ readonly skippedPersonnelIds: readonly string[];
2159
+ readonly duplicate: boolean;
2160
+ }
2161
+
2162
+ interface NotificationsApi {
2163
+ send(message: NotificationMessage): Promise<NotificationResult>;
2164
+ }
2165
+ ```
2166
+
2167
+ ```typescript
2168
+ const result = await notifications.send({
2169
+ to: approverIds,
2170
+ exclude: ["actor"],
2171
+ title: "Leave request waiting for your approval",
2172
+ content: "A leave request of 3 days was submitted and needs your decision.",
2173
+ link: { url: `/app/leave_request/${recordId}` },
2174
+ channel: approvalChannelId,
2175
+ idempotencyKey: `leave-approval:${recordId}`,
2176
+ });
2177
+ // result.notified: accounts addressed; result.skippedPersonnelIds: personnel without an account
2178
+ ```
2179
+
2180
+ ### `notifications.send(message): Promise<NotificationResult>`
2181
+
2182
+ **Recipients.** `to` lists 1 to 200 personnel IDs; duplicates are removed. The
2183
+ notification goes to the user account of each personnel. Personnel without a user
2184
+ account are skipped and returned in `skippedPersonnelIds`, and `notified` is the
2185
+ number of accounts the notification was addressed to after exclusions. `exclude`
2186
+ lists personnel IDs that never receive it; the special value `"actor"` is the user
2187
+ whose action started the current execution (the caller of an HTTP route, the user
2188
+ whose save ran a trigger, the user whose call enqueued a job run). An execution
2189
+ without a user has no actor, so `"actor"` excludes nobody. A personnel ID in `to`
2190
+ that does not exist throws `NotFoundError` with `resource` `"personnel"` before
2191
+ anything is sent. When every recipient is excluded or skipped, nothing is sent and
2192
+ `notified` is `0`.
2193
+
2194
+ **Content and appearance.**
2195
+
2196
+ - `title` (required, at most 200 characters) is the heading of the notification and
2197
+ the subject of its email copy.
2198
+ - `content` (required, at most 16,384 characters) is the body. With
2199
+ `contentType: "text"`, the default, it is plain text. With `"html"` it is reduced
2200
+ to basic formatting before it is stored — paragraphs, headings, lists, tables,
2201
+ links, and emphasis; scripts, styles, and images are removed — and it must still
2202
+ contain visible text, otherwise `ValidationError` is thrown.
2203
+ - `subtitle` (at most 200 characters) is shown only in the `"FULL"` display.
2204
+ `display` defaults to `"FULL"` when a subtitle is given and to `"SIMPLE"`
2205
+ otherwise; a subtitle together with `display: "SIMPLE"` throws `ValidationError`.
2206
+ - `link` is the page opened when the recipient clicks the notification. `url` is a
2207
+ path of the Cogover web app starting with `/`, or an absolute `http` or `https`
2208
+ URL, at most 2,048 characters. `openIn` is `"SAME_TAB"` or `"NEW_TAB"`; it defaults
2209
+ to `"SAME_TAB"` for a path and to `"NEW_TAB"` for an absolute URL.
2210
+ - `sender` is `"workspace"`, the default, or `"actor"`, which shows the name and
2211
+ avatar of the user whose action started the execution. `"actor"` in an execution
2212
+ without a user throws `ValidationError`.
2213
+
2214
+ **Channels and the email copy.** `channel` is the record ID of one of the
2215
+ workspace's notification channels. The channel decides which deliveries are enabled
2216
+ — in the web app, web push, mobile push, and email — and each user may override that
2217
+ choice in their own notification settings. Without `channel`, every delivery is
2218
+ enabled. An unknown channel throws `NotFoundError` with `resource`
2219
+ `"notificationChannel"`; a workspace in which notifications are not set up throws
2220
+ `NotFoundError` with `resource` `"object"` and `resourceId` `"notification_channel"`.
2221
+
2222
+ `email: false` leaves out the email copy even when the channel enables email. The
2223
+ copy uses `title` as its subject and `content` as its body, is sent from a Cogover
2224
+ notification address rather than from a workspace mailbox, and counts against the
2225
+ daily notification-email limit of the workspace's plan. To send an email from a
2226
+ workspace mailbox, use [`email.send`](#email).
2227
+
2228
+ **Idempotency.** `idempotencyKey` starts with a letter or digit and contains at most
2229
+ 128 letters, digits, `.`, `_`, `:`, or `-`. A call whose key the project already
2230
+ used for a notification in the last 7 days sends nothing and returns the first
2231
+ call's result with `duplicate: true`. A call made while the first call with the same
2232
+ key is still sending throws `CogoverApiError` with `code: "DUPLICATE_IN_PROGRESS"`;
2233
+ retry it a moment later. A call that failed does not keep its key, so it can be
2234
+ retried. Keys belong to the project and are separate from the keys of `email.send`.
2235
+ In an after-change trigger or a job, which may run more than once, derive the key
2236
+ from `trigger.changeId` and `record.id`, or from `job.id` or a business key.
2237
+
2238
+ ### Rules
2239
+
2240
+ - `notifications` is available in scripts, routes, after-change triggers, background
2241
+ jobs, inbound webhook calls, and Development Sessions with write permission. A
2242
+ before-change trigger is read-only and receives `PermissionDeniedError` with
2243
+ `details.reason` `"TRIGGER_READ_ONLY"`; a read-only preview and a read-only
2244
+ Development Session refuse it too.
2245
+ - Notifications need no grant in the identity policy: a project may notify any
2246
+ personnel of the workspace.
2247
+ - A project may address at most 5,000 recipients per hour by default. A call that
2248
+ would exceed this throws `RateLimitError` and sends nothing.
2249
+ - Inputs are validated by the SDK and again by Cogover; invalid input throws
2250
+ `ValidationError` before anything is sent. Each call counts as one capability call.
2251
+ - When notifications are switched off for the deployment, every call throws
2252
+ `CogoverApiError` with code `NOTIFICATIONS_DISABLED`.
2253
+ - A sent notification cannot be recalled. Retrying a failed execution may notify
2254
+ again unless the call uses an `idempotencyKey`.
2255
+
2256
+ ## Email
2257
+
2258
+ `email` sends email from the workspace's mailboxes: a shared workspace mailbox, or
2259
+ the default personal mailbox of the user whose action started the execution. The
2260
+ Project's approved identity policy decides which mailboxes a project may use. With
2261
+ `record`, the email is also logged as an email activity on that record's timeline,
2262
+ like an email sent from the record page. Sending is asynchronous: a call resolves
2263
+ once Cogover has accepted the email for delivery, and a delivery failure after that
2264
+ is not reported back to the script.
2265
+
2266
+ ```typescript
2267
+ type EmailSender = { readonly mailbox: string } | "actor";
2268
+
2269
+ type EmailRecipient =
2270
+ | string
2271
+ | { readonly email: string; readonly name?: string }
2272
+ | { readonly personnelId: string };
2273
+
2274
+ interface EmailRecordLink<ObjectSlug extends string = string> {
2275
+ readonly object: ObjectSlug;
2276
+ readonly recordId: string;
2277
+ }
2278
+
2279
+ interface EmailAttachment<ObjectSlug extends string = string> {
2280
+ readonly object: ObjectSlug;
2281
+ readonly recordId: string;
2282
+ readonly field: string;
2283
+ }
2284
+
2285
+ type EmailMessage<ObjectSlug extends string = string> = {
2286
+ readonly from: EmailSender;
2287
+ readonly to?: readonly EmailRecipient[];
2288
+ readonly cc?: readonly EmailRecipient[];
2289
+ readonly bcc?: readonly EmailRecipient[];
2290
+ readonly subject: string;
2291
+ readonly record?: EmailRecordLink<ObjectSlug>;
2292
+ readonly recordEmailFields?: readonly string[];
2293
+ readonly attachments?: readonly EmailAttachment<ObjectSlug>[];
2294
+ readonly appendSignature?: boolean;
2295
+ readonly idempotencyKey?: string;
2296
+ } & (
2297
+ | { readonly html: string; readonly text?: never }
2298
+ | { readonly text: string; readonly html?: never }
2299
+ );
2300
+
2301
+ type EmailDelivery = "activity" | "direct";
2302
+
2303
+ interface EmailSendResult {
2304
+ readonly requestId: string;
2305
+ readonly delivery: EmailDelivery;
2306
+ readonly recipients: number;
2307
+ readonly duplicate: boolean;
2308
+ }
2309
+
2310
+ type EmailSenderKind = "workspace" | "actor";
2311
+
2312
+ interface EmailSenderInfo {
2313
+ readonly id: string;
2314
+ readonly kind: EmailSenderKind;
2315
+ readonly email: string;
2316
+ readonly displayName: string;
2317
+ }
2318
+
2319
+ interface EmailApi<Schema extends object = EffectiveWorkspaceObjects> {
2320
+ send(message: EmailMessage<StringKeyOf<Schema>>): Promise<EmailSendResult>;
2321
+ senders(): Promise<readonly EmailSenderInfo[]>;
2322
+ }
2323
+ ```
2324
+
2325
+ ```typescript
2326
+ const result = await email.send({
2327
+ from: { mailbox: "EMWXXXXXXXXXXXX" },
2328
+ bcc: ["sales-archive@example.com"],
2329
+ subject: `Quote ${quote.fields.code}`,
2330
+ html: "<p>Dear customer,</p><p>Please find our quote attached.</p>",
2331
+ record: { object: "quote", recordId: quote.id },
2332
+ recordEmailFields: ["contact_email"],
2333
+ attachments: [{ object: "quote", recordId: quote.id, field: "quote_pdf" }],
2334
+ idempotencyKey: `quote-email:${quote.id}`,
2335
+ });
2336
+ // result.delivery === "activity": the email appears on the quote's timeline.
2337
+ ```
2338
+
2339
+ ### `email.send(message): Promise<EmailSendResult>`
2340
+
2341
+ **Sender.** `from: { mailbox: id }` sends from a shared workspace mailbox;
2342
+ `from: "actor"` sends from the default personal mailbox of the user whose action
2343
+ started the execution. The sender must be allowed by the `email` section of the
2344
+ Project's approved identity policy: `workspaceMailboxIds` lists the shared mailboxes
2345
+ and `allowActorMailbox` allows `"actor"`. Like the rest of the policy, the section
2346
+ applies only to the callers selected by `callerPersonnelIds`, and to executions
2347
+ without a user only when the policy sets `allowInternalSystem: true`. A project
2348
+ whose policy has no `email` section cannot send email. A sender that is not allowed
2349
+ throws `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`;
2350
+ this check comes before anything else is looked up. A mailbox that does not exist or
2351
+ is deactivated, and an actor without an active personal mailbox, throw
2352
+ `NotFoundError` with `resource` `"mailbox"`. `"actor"` in an execution without a
2353
+ user throws `ValidationError`.
2354
+
2355
+ **Recipients.**
2356
+
2357
+ - `to`, `cc`, and `bcc` accept an address string, `{ email, name? }`, or
2358
+ `{ personnelId }`. A personnel is resolved to their work email, or to the email of
2359
+ their user account when there is no work email; a personnel with neither throws
2360
+ `ValidationError`, and an unknown personnel throws `NotFoundError` with `resource`
2361
+ `"personnel"`.
2362
+ - Duplicates are removed within each list, ignoring case. The three lists together
2363
+ accept at most 50 recipients. A `name` is a single line of at most 200 characters.
2364
+ - `to` must name at least one recipient unless `recordEmailFields` is given.
2365
+
2366
+ **Content.** `subject` is required: a single line of at most 255 characters. Provide
2367
+ exactly one of `html` and `text`; the body is at most 192 KB (196,608 bytes) in
2368
+ UTF-8.
2369
+
2370
+ **Record.** `record: { object, recordId }` logs the email as an email activity on
2371
+ that record's timeline: Cogover tracks opens and link clicks and threads replies
2372
+ with it, and `result.delivery` is `"activity"`. The record must be readable by the
2373
+ default identity of the execution, otherwise `NotFoundError` with `resource`
2374
+ `"record"` is thrown. Without `record`, the email is only sent from the mailbox and
2375
+ `delivery` is `"direct"`. The following options require `record`; without it they
2376
+ throw `ValidationError`:
2377
+
2378
+ - `recordEmailFields` lists up to 20 email fields of that record whose addresses are
2379
+ added to `to`. A field that is not an email field throws `ValidationError`.
2380
+ - `attachments` attaches every file stored in the file field `field` of each listed
2381
+ record: at most 10 files and 20 MB in total. The records must be readable by the
2382
+ default identity; a field that is not a file field throws `ValidationError`.
2383
+ - `appendSignature: true` appends the sender's default email signature. It requires a
2384
+ personal mailbox, that is `from: "actor"`; otherwise `ValidationError` is thrown.
2385
+
2386
+ **Result.** `requestId` identifies the send. `recipients` counts the addresses in
2387
+ `to`, `cc`, and `bcc` after duplicates were removed; the addresses of
2388
+ `recordEmailFields` are resolved later and are not counted. `duplicate` is `true`
2389
+ when an earlier call with the same `idempotencyKey` already sent the email.
2390
+
2391
+ **Idempotency.** `idempotencyKey` follows the same rules as for
2392
+ [notifications](#notifications): a retry with the same key within 7 days returns
2393
+ the first result with `duplicate: true` instead of sending again, and a retry while
2394
+ the first call is still sending throws `CogoverApiError` with
2395
+ `code: "DUPLICATE_IN_PROGRESS"`. Email keys are separate from notification keys.
2396
+
2397
+ ### `email.senders(): Promise<readonly EmailSenderInfo[]>`
2398
+
2399
+ Returns the active mailboxes this execution may send from: one `kind: "workspace"`
2400
+ entry for each active shared mailbox that the applicable policy lists in
2401
+ `workspaceMailboxIds`, to be used as `{ mailbox: id }`, and, when the policy sets
2402
+ `allowActorMailbox` and the actor has an active personal mailbox, at most one
2403
+ `kind: "actor"` entry describing the mailbox that `from: "actor"` uses. The list is
2404
+ empty when the policy grants this execution no sender. Use it to show the available
2405
+ senders or to pick one by `email` address instead of hard-coding an ID. It sends
2406
+ nothing, so it also works in a read-only preview and a read-only Development
2407
+ Session.
2408
+
2409
+ ### Rules
2410
+
2411
+ - `email` is available in scripts, routes, after-change triggers, background jobs,
2412
+ inbound webhook calls, and Development Sessions. A before-change trigger receives
2413
+ `PermissionDeniedError` with `details.reason` `"TRIGGER_READ_ONLY"` for both
2414
+ methods; a read-only preview and a read-only Development Session refuse
2415
+ `email.send`.
2416
+ - A project may send at most 500 emails per hour by default; beyond that,
2417
+ `RateLimitError` is thrown and nothing is sent. One call is one email, however many
2418
+ recipients it has.
2419
+ - Inputs are validated by the SDK and again by Cogover; invalid input throws
2420
+ `ValidationError` before anything is sent. Each call counts as one capability call.
2421
+ - When email is switched off for the deployment, every call throws
2422
+ `CogoverApiError` with code `EMAIL_DISABLED`.
2423
+ - A sent email cannot be recalled. Retrying a failed execution may send it again
2424
+ unless the call uses an `idempotencyKey`.
2425
+
2426
+ ## Organization structure
2427
+
2428
+ `org` reads the departments, positions and personnel of the workspace: who works in
2429
+ which department, which positions apply where, and who manages whom. Every method is
2430
+ a read. Structure answers are served from a cached copy of the organization, so they
2431
+ are fast; a change made in Cogover is visible within a few seconds. Add
2432
+ `withDisplay: true` to also receive department and position names in a language and,
2433
+ for personnel, their display name, email, avatar and code. Other personnel fields,
2434
+ such as phone numbers or custom fields, are read with `data.object("personnel")`,
2435
+ which applies record permissions.
2436
+
2437
+ ```typescript
2438
+ interface OrgApi {
2439
+ readonly personnel: OrgPersonnelApi;
2440
+ readonly departments: OrgDepartmentsApi;
2441
+ readonly positions: OrgPositionsApi;
2442
+ me(options?: OrgReadOptions): Promise<OrgPersonnel | null>;
2443
+ isInDepartment(personnelId: string, departmentId: string,
2444
+ options?: OrgIsInDepartmentOptions): Promise<boolean>;
2445
+ isManagerOf(managerId: string, personnelId: string,
2446
+ options?: OrgIsManagerOfOptions): Promise<boolean>;
2447
+ }
2448
+
2449
+ interface OrgPersonnelApi {
2450
+ get(id: string, options?: OrgReadOptions): Promise<OrgPersonnel | null>;
2451
+ getMany(ids: readonly string[], options?: OrgReadOptions):
2452
+ Promise<OrgGetManyResult<OrgPersonnel>>;
2453
+ managerChain(id: string, options?: OrgPersonnelChainOptions):
2454
+ Promise<readonly OrgManagerChain[]>;
2455
+ }
2456
+
2457
+ interface OrgDepartmentsApi {
2458
+ get(id: string, options?: OrgReadOptions): Promise<OrgDepartment | null>;
2459
+ tree(options?: OrgTreeOptions): Promise<readonly OrgDepartmentNode[]>;
2460
+ ancestors(id: string, options?: OrgReadOptions): Promise<readonly OrgDepartment[]>;
2461
+ members(id: string, options?: OrgDepartmentMembersOptions): Promise<OrgPage<OrgMember>>;
2462
+ managers(id: string, options?: OrgManagerOptions): Promise<readonly OrgManagerTier[]>;
2463
+ managerChain(id: string, options?: OrgManagerOptions): Promise<OrgManagerChain>;
2464
+ }
2465
+
2466
+ interface OrgPositionsApi {
2467
+ list(options?: OrgReadOptions): Promise<readonly OrgPosition[]>;
2468
+ get(id: string, options?: OrgReadOptions): Promise<OrgPosition | null>;
2469
+ members(id: string, options?: OrgPositionMembersOptions): Promise<OrgPage<OrgMember>>;
2470
+ }
2471
+ ```
2472
+
2473
+ Every method that returns data has a second overload: when `options.withDisplay` is
2474
+ the literal `true`, the result type is the `<true>` variant of the types below, whose
2475
+ display fields are always present. Without it, the display fields do not exist on the
2476
+ type.
2477
+
2478
+ ```typescript
2479
+ interface OrgReadOptions {
2480
+ readonly withDisplay?: boolean;
2481
+ readonly language?: string; // such as "vi-VN"; defaults to the invocation language
2482
+ }
2483
+
2484
+ interface OrgPageOptions extends OrgReadOptions {
2485
+ readonly includeSubDepartments?: boolean;
2486
+ readonly accountOnly?: boolean;
2487
+ readonly limit?: number; // default 500, at most 2000; 200 with withDisplay
2488
+ readonly cursor?: string;
2489
+ }
2490
+ interface OrgDepartmentMembersOptions extends OrgPageOptions { readonly positionId?: string; }
2491
+ interface OrgPositionMembersOptions extends OrgPageOptions { readonly departmentId?: string; }
2492
+ interface OrgManagerOptions extends OrgReadOptions { readonly accountOnly?: boolean; }
2493
+ interface OrgPersonnelChainOptions extends OrgManagerOptions { readonly departmentId?: string; }
2494
+ interface OrgTreeOptions extends OrgReadOptions {
2495
+ readonly rootId?: string;
2496
+ readonly depth?: number; // 1 to 100; defaults to every level
2497
+ }
2498
+ interface OrgIsInDepartmentOptions { readonly includeSubDepartments?: boolean; }
2499
+ interface OrgIsManagerOfOptions {
2500
+ readonly departmentId?: string;
2501
+ readonly directOnly?: boolean;
2502
+ }
2503
+
2504
+ interface OrgPersonnelDisplay {
2505
+ readonly name: string;
2506
+ readonly email: string | null;
2507
+ readonly avatar: string | null; // public URL
2508
+ readonly code: string | null;
2509
+ }
2510
+ interface OrgNameDisplay { readonly name: string; }
2511
+
2512
+ type OrgMembership<D extends boolean = false> = {
2513
+ readonly personnelId: string;
2514
+ readonly departmentId: string;
2515
+ readonly positionId: string | null;
2516
+ readonly level: number; // 0 staff, 1 highest manager level, 2 next, ...
2517
+ readonly primary: boolean;
2518
+ } & (D extends true
2519
+ ? { readonly departmentName: string | null; readonly positionName: string | null }
2520
+ : {});
2521
+
2522
+ type OrgPersonnel<D extends boolean = false> = {
2523
+ readonly id: string;
2524
+ readonly accountId: string | null; // null: no workspace account
2525
+ readonly memberships: readonly OrgMembership<D>[];
2526
+ } & (D extends true ? { readonly display: OrgPersonnelDisplay | null } : {});
2527
+
2528
+ type OrgMember<D extends boolean = false> = OrgMembership<D> & {
2529
+ readonly accountId: string | null;
2530
+ } & (D extends true ? { readonly display: OrgPersonnelDisplay | null } : {});
2531
+
2532
+ type OrgDepartment<D extends boolean = false> = {
2533
+ readonly id: string;
2534
+ readonly parentId: string | null;
2535
+ readonly level: number; // 1 for a root department
2536
+ readonly childIds: readonly string[];
2537
+ readonly positionIds: readonly string[];
2538
+ } & (D extends true ? { readonly display: OrgNameDisplay | null } : {});
2539
+
2540
+ type OrgDepartmentNode<D extends boolean = false> = OrgDepartment<D> & {
2541
+ readonly children: readonly OrgDepartmentNode<D>[];
2542
+ };
2543
+
2544
+ type OrgPosition<D extends boolean = false> = {
2545
+ readonly id: string;
2546
+ readonly departmentOnly: boolean;
2547
+ readonly departmentIds: readonly string[];
2548
+ readonly excludedDepartmentIds: readonly string[];
2549
+ } & (D extends true ? { readonly display: OrgNameDisplay | null } : {});
2550
+
2551
+ type OrgManagerTier<D extends boolean = false> = {
2552
+ readonly departmentId: string;
2553
+ readonly level: number;
2554
+ readonly distance: number; // 0 starting department, 1 its parent, ...
2555
+ readonly personnelIds: readonly string[];
2556
+ } & (D extends true ? {
2557
+ readonly departmentName: string | null;
2558
+ readonly personnel: readonly { readonly id: string; readonly display: OrgPersonnelDisplay | null }[];
2559
+ } : {});
2560
+
2561
+ interface OrgManagerChain<D extends boolean = false> {
2562
+ readonly fromDepartmentId: string;
2563
+ readonly personnelLevel: number;
2564
+ readonly tiers: readonly OrgManagerTier<D>[];
2565
+ readonly vacantDepartmentIds: readonly string[];
2566
+ readonly truncated: boolean;
2567
+ }
2568
+
2569
+ interface OrgPage<T> {
2570
+ readonly items: readonly T[];
2571
+ readonly total: number;
2572
+ readonly nextCursor?: string;
2573
+ }
2574
+
2575
+ interface OrgGetManyResult<T> {
2576
+ readonly items: readonly T[];
2577
+ readonly missingIds: readonly string[];
2578
+ }
2579
+ ```
2580
+
2581
+ ```typescript
2582
+ export default defineScript(async ({ org, input }) => {
2583
+ const order = input as { ownerId: string; departmentId: string };
2584
+ // Structure only: answered without reading records.
2585
+ const [chain] = await org.personnel.managerChain(order.ownerId, {
2586
+ departmentId: order.departmentId,
2587
+ accountOnly: true,
2588
+ });
2589
+ const approverIds = chain?.tiers[0]?.personnelIds ?? [];
2590
+
2591
+ // Names for a screen: one extra read per kind of data.
2592
+ const me = await org.me({ withDisplay: true });
2593
+ return {
2594
+ approverIds,
2595
+ greeting: me?.display?.name,
2596
+ departments: me?.memberships.map(m => m.departmentName) ?? [],
2597
+ };
2598
+ });
2599
+ ```
2600
+
2601
+ ### Display data
2602
+
2603
+ - `withDisplay` adds `display` to personnel, departments and positions, and
2604
+ `departmentName`/`positionName` to memberships. A value is `null` when the record
2605
+ behind it cannot be read, for example because it was deleted a moment ago.
2606
+ - `language` selects the translation of department and position names, such as
2607
+ `"vi-VN"` or `"en-US"`; a tag without a region (`"vi"`) matches the first
2608
+ translation of that language. It defaults to the language of the invocation's user
2609
+ membership, then of the user, then of the workspace, and falls back to the stored
2610
+ name when there is no matching translation.
2611
+ - A personnel `name` is the full name the workspace shows; `email` is the account
2612
+ email, else the work email; `avatar` is a public image URL.
2613
+ - Display data is limited to these fields and is readable by every member of the
2614
+ workspace, as in user pickers. It costs at most one read per kind of data and per
2615
+ 200 IDs, and recently read values are cached.
2616
+
2617
+ ### `org.me(options?)`
2618
+
2619
+ Returns the personnel of the invocation's user, or `null` for a `system` or
2620
+ `inbound` invocation. It is `org.personnel.get` with
2621
+ `invocation.user.membership.personnelId`.
2622
+
2623
+ ### `org.personnel.get(id, options?)` and `org.personnel.getMany(ids, options?)`
2624
+
2625
+ `get` returns an active personnel with every department membership, primary
2626
+ department first, or `null` when the ID is not an active personnel of the workspace.
2627
+ `getMany` reads up to 200 IDs in one call: duplicates are removed, `items` follows
2628
+ the request order, and unknown IDs are listed in `missingIds`. A personnel without a
2629
+ workspace account has `accountId: null`; people who left the workspace are not
2630
+ returned.
2631
+
2632
+ ### `org.departments.get(id, options?)`, `tree(options?)` and `ancestors(id, options?)`
2633
+
2634
+ - `get` returns one active department or `null`. `childIds` are in display order;
2635
+ `positionIds` are the positions that apply to the department.
2636
+ - `tree` returns the root departments (or `rootId` alone) with their sub-departments.
2637
+ `depth: 1` returns only the roots; below the requested depth `children` is empty
2638
+ while `childIds` still lists the sub-departments. A tree of more than 5000
2639
+ departments throws `ValidationError`; narrow it with `rootId` or `depth`.
2640
+ - `ancestors` returns the parent first and the root last.
2641
+ - A department whose parent is inactive or deleted is returned as a root
2642
+ (`parentId: null`).
2643
+
2644
+ ### `org.departments.members(id, options?)` and `org.positions.members(id, options?)`
2645
+
2646
+ Return one page of memberships: managers first by level, then staff. A personnel who
2647
+ belongs to several listed departments appears once per department.
2648
+ `includeSubDepartments` adds every sub-department in tree order, `positionId` keeps
2649
+ only the holders of a position, `departmentId` limits position holders to a
2650
+ department, and `accountOnly` keeps only personnel with a workspace account. Pass
2651
+ `nextCursor` as `cursor` to read the next page; `total` counts every page. The page
2652
+ size is 500 by default and at most 2000, or at most 200 with `withDisplay`.
2653
+
2654
+ ### `org.positions.list(options?)` and `org.positions.get(id, options?)`
2655
+
2656
+ Return active positions, oldest first. A department-only position applies to
2657
+ `departmentIds`; any other position applies to every department except
2658
+ `excludedDepartmentIds`.
2659
+
2660
+ ### Managers and manager chains
2661
+
2662
+ A membership's `level` marks managers: `0` is staff, `1` the highest manager level of
2663
+ the department, `2` the next one, and so on. Several people may share a level.
2664
+
2665
+ - `org.departments.managers(id, options?)` returns the managers of that department
2666
+ only, one tier per level, level `1` first.
2667
+ - `org.departments.managerChain(id, options?)` returns the managers above a staff
2668
+ member of the department, nearest first, up to the root department.
2669
+ - `org.personnel.managerChain(id, options?)` returns one chain per department of the
2670
+ personnel, primary department first; `departmentId` keeps only the chain that
2671
+ starts in that department. The result is empty for an unknown personnel.
2672
+
2673
+ A chain is built with these rules:
2674
+
2675
+ 1. In the starting department, the managers of the personnel are those with a lower
2676
+ level number than the personnel's own level (every manager for staff), nearest
2677
+ first: level `3`, then `2`, then `1`. A department head has none there.
2678
+ 2. Then every parent department up to the root adds all its managers, largest level
2679
+ number first. Every manager of a parent department ranks above every manager of
2680
+ its sub-departments.
2681
+ 3. A personnel is listed once, at the nearest tier, and the starting personnel is
2682
+ never listed.
2683
+ 4. `accountOnly: true` skips personnel without a workspace account, for example when
2684
+ the chain lists approvers.
2685
+ 5. `vacantDepartmentIds` lists the departments passed without any eligible manager;
2686
+ the chain continues with their parent. A department head's own department is not
2687
+ vacant.
2688
+ 6. `truncated` is `true` when a parent department is inactive, so the chain stops
2689
+ before the real root.
2690
+
2691
+ For example, with a company board (CEO level `1`, deputy CEO level `2`), an
2692
+ Engineering department under it (director level `1`), and a Testing department under
2693
+ Engineering (head `1`, deputy `2`, team lead `3`), the chain of a tester is: team lead,
2694
+ deputy, head, director, deputy CEO, CEO. The chain of the Testing deputy is: head,
2695
+ director, deputy CEO, CEO.
2696
+
2697
+ ### `org.isInDepartment(personnelId, departmentId, options?)` and `org.isManagerOf(managerId, personnelId, options?)`
2698
+
2699
+ `isInDepartment` tells whether the personnel belongs to the department, or to one of
2700
+ its sub-departments with `includeSubDepartments`. `isManagerOf` tells whether
2701
+ `managerId` appears in a manager chain of `personnelId`; `departmentId` considers
2702
+ only the chain that starts there and `directOnly` only its nearest tier. Both return
2703
+ `false` for unknown IDs.
2704
+
2705
+ ### Rules
2706
+
2707
+ - `org` is available in scripts, routes, record triggers of both timings, background
2708
+ jobs and Development Sessions.
2709
+ - It follows the default identity of the execution: an execution with a user or a
2710
+ system identity may read it. An execution without a user (a background job, an
2711
+ inbound webhook, or a record trigger started by a system write) may read it only
2712
+ when the project's approved identity policy sets `allowInternalSystem: true`;
2713
+ otherwise every call throws `PermissionDeniedError` with `details.reason`
2714
+ `"IDENTITY_NOT_GRANTED"`.
2715
+ - All calls of one execution read the same version of the structure.
2716
+ - IDs are validated by the SDK and again by Cogover; an invalid ID or option throws
2717
+ `ValidationError`. `get` methods return `null` for an unknown ID; `members`,
2718
+ `managers`, `managerChain`, `ancestors` and `tree({ rootId })` throw
2719
+ `NotFoundError` with `resource` `"department"` or `"position"`.
2720
+ - When the structure cannot be read, the call throws `CogoverApiError` with code
2721
+ `ORGANIZATION_UNAVAILABLE`.
2722
+ - Call `getMany` or `members` instead of calling `get` in a loop: each call is one
2723
+ capability call.
2724
+
2105
2725
  ## Schema API
2106
2726
 
2107
2727
  `SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
@@ -2223,6 +2843,14 @@ the feature is not enabled for the Workspace. `crypto.aesDecrypt` and
2223
2843
  `crypto.rsaDecrypt` throw `CogoverApiError` with `code: "DECRYPTION_FAILED"` when
2224
2844
  the ciphertext cannot be decrypted.
2225
2845
 
2846
+ `notifications.send` and `email.send` fail with `ValidationError`, `NotFoundError`,
2847
+ `PermissionDeniedError`, or `RateLimitError` as described in their sections, with
2848
+ `CogoverApiError` whose `code` is `NOTIFICATIONS_DISABLED` or `EMAIL_DISABLED` when
2849
+ the feature is switched off, and with `CogoverApiError` whose `code` is
2850
+ `DUPLICATE_IN_PROGRESS` while an earlier call with the same `idempotencyKey` is
2851
+ still sending. A sender mailbox that the Project policy does not allow is reported
2852
+ as `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`.
2853
+
2226
2854
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
2227
2855
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
2228
2856
  the original code or message. A script's returned JSON remains its own response
@@ -2257,6 +2885,7 @@ For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
2257
2885
  | `LOCK_LOST` | 409 |
2258
2886
  | `STATE_SERVICE_UNAVAILABLE` | 503 |
2259
2887
  | `LOCK_SERVICE_UNAVAILABLE` | 503 |
2888
+ | `ORGANIZATION_UNAVAILABLE` | 503 |
2260
2889
  | `FETCH_DISABLED` | 503 |
2261
2890
  | `FETCH_BLOCKED` | 400 |
2262
2891
  | `FETCH_REQUEST_TOO_LARGE` | 413 |