@cogover/sdk 0.5.0 → 0.7.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.
@@ -8,7 +8,7 @@ configured for the project.
8
8
  ## `defineScript`
9
9
 
10
10
  `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
11
- the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, and `locks`, awaits the handler,
11
+ the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`, and `push`, awaits the handler,
12
12
  and serializes its result.
13
13
 
14
14
  ```typescript
@@ -39,6 +39,7 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
39
39
  readonly response: ResponseApi;
40
40
  readonly state: ProjectState;
41
41
  readonly locks: DistributedLocks;
42
+ readonly push: PushApi<Schema>;
42
43
  }
43
44
  ```
44
45
 
@@ -49,7 +50,7 @@ Returning `null` produces a null handler result; returning `undefined` is invali
49
50
  ## HTTP routers and request context
50
51
 
51
52
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
52
- `log`, `state`, and `locks` to both script and route handlers. `input` preserves the invocation
53
+ `log`, `state`, `locks`, and `push` to both script and route handlers. `input` preserves the invocation
53
54
  input. Prefer `request.body` for business data: it excludes invocation metadata and
54
55
  transport/authentication fields removed by Cogover.
55
56
 
@@ -250,6 +251,434 @@ the transport envelope directly. A redirect location must be non-empty, at most
250
251
  4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
251
252
  `response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
252
253
 
254
+ ## Record triggers
255
+
256
+ A record trigger runs project code when records of one Object are created, updated,
257
+ or deleted. Declare each trigger with `defineTrigger` and list the results in the
258
+ project's named `triggers` export. The default export is still the HTTP handler and
259
+ is optional in a project that only declares triggers.
260
+
261
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
262
+ fields used below.
263
+
264
+ ```typescript
265
+ import { defineTrigger } from "@cogover/sdk";
266
+
267
+ export const triggers = [
268
+ defineTrigger({
269
+ key: "order_credit_check",
270
+ object: "order",
271
+ timing: "beforeChange",
272
+ operations: ["create", "update"],
273
+ fields: ["status", "amount", "customer"],
274
+ changedFields: ["status", "amount"],
275
+ when: { op: "=", field: "status", params: "confirmed" },
276
+ writableFields: ["approval_level"],
277
+ }, async ({ records }) => {
278
+ for (const record of records) {
279
+ if ((record.new.amount ?? 0) > 1_000_000_000) {
280
+ record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
281
+ continue;
282
+ }
283
+ record.new.approval_level = "high";
284
+ }
285
+ }),
286
+ ];
287
+ ```
288
+
289
+ A trigger has one of two timings. A **before-change** trigger runs before the change
290
+ is saved: it can reject records and adjust the values that will be saved. An
291
+ **after-change** trigger runs asynchronously after the change has been saved: it
292
+ cannot reject or modify that change, but it may write records and call `fetch`. See
293
+ [Before-change execution rules](#before-change-execution-rules) and
294
+ [After-change execution rules](#after-change-execution-rules).
295
+
296
+ Cogover reads the trigger configuration when a project version is published and
297
+ applies it while that version is active. Deactivating the project removes its
298
+ triggers. A project can declare at most 50 triggers, and an Object can have at most
299
+ 20 active before-change triggers.
300
+
301
+ ### `defineTrigger(config, handler): TriggerDefinition`
302
+
303
+ ```typescript
304
+ function defineTrigger<
305
+ ObjectSlug extends keyof Schema & string,
306
+ Operation extends TriggerOperation,
307
+ Schema extends object = EffectiveWorkspaceObjects,
308
+ >(
309
+ config: TriggerConfig<ObjectSlug, Operation, Schema>,
310
+ handler: TriggerHandler<ObjectSlug, Operation, Schema>,
311
+ ): TriggerDefinition;
312
+ ```
313
+
314
+ The type arguments are inferred from `config.object` and `config.operations`.
315
+ With a generated `workspace.d.ts`, the object slug, every field slug in the
316
+ configuration, and the values of `record.new` and `record.old` are checked against
317
+ the declared Object. Without Workspace declarations, slugs are strings and field
318
+ values are `unknown`.
319
+
320
+ `defineTrigger` validates the configuration immediately and throws `ValidationError`
321
+ for any violation, for an unknown configuration key, or for a handler that is not a
322
+ function. It returns a frozen `TriggerDefinition`.
323
+
324
+ ```typescript
325
+ type TriggerTiming = "beforeChange" | "afterChange";
326
+ type TriggerOperation = "create" | "update" | "delete";
327
+ type TriggerRunWhen = "always" | "onEnter";
328
+
329
+ interface TriggerConfig<
330
+ ObjectSlug extends string = string,
331
+ Operation extends TriggerOperation = TriggerOperation,
332
+ Schema extends object = EffectiveWorkspaceObjects,
333
+ > {
334
+ readonly key: string;
335
+ readonly name?: string;
336
+ readonly object: ObjectSlug;
337
+ readonly timing: TriggerTiming;
338
+ readonly operations: readonly Operation[];
339
+ readonly fields: readonly FieldSlug[]; // field slugs of the Object
340
+ readonly changedFields?: readonly FieldSlug[];
341
+ readonly when?: TriggerFilter;
342
+ readonly runWhen?: TriggerRunWhen;
343
+ readonly writableFields?: readonly FieldSlug[];
344
+ readonly order?: number;
345
+ readonly timeoutMs?: number;
346
+ }
347
+ ```
348
+
349
+ | Option | Required | Rules and meaning |
350
+ |---|---|---|
351
+ | `key` | Yes | Identifies the trigger inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters. Keep it stable between versions: a new key is a different trigger. |
352
+ | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
353
+ | `object` | Yes | Slug of the Object whose records run the trigger. |
354
+ | `timing` | Yes | `"beforeChange"` runs before the change is saved and can reject or adjust it. `"afterChange"` runs asynchronously after the change has been saved. |
355
+ | `operations` | Yes | Non-empty list of `"create"`, `"update"`, and `"delete"` without duplicates. |
356
+ | `fields` | Yes | 1–200 unique field slugs. `record.new` and `record.old` contain only these fields and `id`. |
357
+ | `changedFields` | No | 1–200 unique field slugs; requires the `"update"` operation. An update runs the trigger only when at least one of these fields changed. Creates and deletes are not affected. |
358
+ | `when` | No | A `TriggerFilter`. Only matching records run the trigger. |
359
+ | `runWhen` | No | `"always"` (default) or `"onEnter"`. `"onEnter"` requires `when`. |
360
+ | `writableFields` | No | At most 100 unique field slugs that the handler may change. Only for `"beforeChange"`; must be empty when `"delete"` is the only operation. Defaults to `[]`. |
361
+ | `order` | No | Integer from 1000 through 8999; defaults to `5000`. Triggers of an Object run in ascending order. Other values are reserved for Cogover. Do not rely on the relative order of triggers that share a value. |
362
+ | `timeoutMs` | No | Integer from 100 through 3000; defaults to `2000`. Time budget of one handler call. |
363
+
364
+ Object and field slugs start with an ASCII letter or `_`, contain letters, digits,
365
+ or `_`, and are at most 355 characters. `changedFields` and `writableFields` do not
366
+ have to be listed in `fields`.
367
+
368
+ ### Trigger filters
369
+
370
+ ```typescript
371
+ interface TriggerFilterCondition {
372
+ readonly op: FilterOperator;
373
+ readonly field: string;
374
+ readonly params?: unknown;
375
+ }
376
+
377
+ interface TriggerFilterGroup {
378
+ readonly op: "and" | "or";
379
+ readonly conditions: readonly TriggerFilter[];
380
+ }
381
+
382
+ type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
383
+ ```
384
+
385
+ ```typescript
386
+ when: {
387
+ op: "and",
388
+ conditions: [
389
+ { op: "=", field: "status", params: "confirmed" },
390
+ { op: "or", conditions: [
391
+ { op: ">=", field: "amount", params: 1_000_000 },
392
+ { op: "in", field: "priority", params: ["high", "urgent"] },
393
+ ] },
394
+ ],
395
+ }
396
+ ```
397
+
398
+ A condition compares one field using a `FilterOperator`. `params` is the JSON
399
+ comparison value: it is required for every operator except `"is null"` and
400
+ `"not null"`, which take none. `"in"` and `"not in"` take a non-empty array and
401
+ `"between"` takes exactly two values. A group combines a non-empty list of
402
+ filters. A filter is nested at most 8 levels deep and contains at most 50
403
+ conditions. Trigger filters are plain objects: expressions built with `and()`,
404
+ `or()`, or field references are for `records.list` and are rejected here.
405
+
406
+ `when` is evaluated on the new values, or on the old values when a record is
407
+ deleted. With `runWhen: "onEnter"` the trigger runs only when the record did not
408
+ match `when` before the change and matches after it; a record that is being created
409
+ counts as not matching before, and `runWhen` is ignored for deletes.
410
+
411
+ Cogover decides which triggers run once, before the first trigger of a change, from
412
+ the values submitted by the writer together with field defaults. A value changed by
413
+ an earlier trigger does not change which triggers run, but later triggers see it in
414
+ `record.new`.
415
+
416
+ ### `TriggerDefinition` and `TriggerManifest`
417
+
418
+ ```typescript
419
+ interface TriggerManifest {
420
+ readonly key: string;
421
+ readonly name?: string;
422
+ readonly object: string;
423
+ readonly timing: TriggerTiming;
424
+ readonly operations: readonly TriggerOperation[];
425
+ readonly fields: readonly string[];
426
+ readonly changedFields?: readonly string[];
427
+ readonly when?: TriggerFilter;
428
+ readonly runWhen: TriggerRunWhen;
429
+ readonly writableFields: readonly string[];
430
+ readonly order: number;
431
+ readonly timeoutMs: number;
432
+ }
433
+
434
+ type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
435
+
436
+ interface TriggerDefinition {
437
+ readonly key: string;
438
+ readonly config: TriggerManifest;
439
+ readonly __cogoverTriggerHandler: TriggerSandboxHandler;
440
+ }
441
+ ```
442
+
443
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
444
+ default applied: `runWhen: "always"`, `writableFields: []`, `order: 5000`, and
445
+ `timeoutMs: 2000`. Optional settings that were not provided are absent. It is
446
+ detached from the object passed to `defineTrigger`, so later edits of that object
447
+ have no effect. `__cogoverTriggerHandler` is reserved for Cogover; project code
448
+ does not call it.
449
+
450
+ ### Trigger handler context
451
+
452
+ ```typescript
453
+ type TriggerHandler<
454
+ ObjectSlug extends string = string,
455
+ Operation extends TriggerOperation = TriggerOperation,
456
+ Schema extends object = EffectiveWorkspaceObjects,
457
+ > = (context: TriggerContext<ObjectSlug, Operation, Schema>) => void | Promise<void>;
458
+
459
+ interface TriggerContext<
460
+ ObjectSlug extends string = string,
461
+ Operation extends TriggerOperation = TriggerOperation,
462
+ Schema extends object = EffectiveWorkspaceObjects,
463
+ > {
464
+ readonly records: readonly TriggerRecord<Fields, Operation>[]; // Fields of ObjectSlug
465
+ readonly trigger: TriggerInfo<Operation>;
466
+ readonly invocation: InvocationContext;
467
+ readonly data: DataApi<Schema>;
468
+ readonly schema: SchemaApi<Schema>;
469
+ readonly log: ScriptLogger;
470
+ readonly push: PushApi<Schema>;
471
+ }
472
+
473
+ interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
474
+ readonly id: string;
475
+ readonly key: string;
476
+ readonly timing: TriggerTiming;
477
+ readonly operation: Operation;
478
+ readonly objectSlug: string;
479
+ readonly changeId: string;
480
+ }
481
+
482
+ interface TriggerRecord<Fields = Record<string, unknown>, Operation extends TriggerOperation = TriggerOperation> {
483
+ readonly key: string;
484
+ readonly id: CogoverRecordId | null;
485
+ readonly new: TriggerNewValues<Fields> | null;
486
+ readonly old: TriggerOldValues<Fields> | null;
487
+ readonly changedFields: readonly (keyof Fields & string)[];
488
+ addError(field: (keyof Fields & string) | null, code: string, message?: string): void;
489
+ }
490
+
491
+ type TriggerNewValues<Fields> = {
492
+ -readonly [K in keyof Fields]?: Fields[K] | UpdateFields<Fields>[K];
493
+ };
494
+
495
+ type TriggerOldValues<Fields> = {
496
+ readonly [K in keyof Fields]?: Fields[K];
497
+ };
498
+ ```
499
+
500
+ A handler may be synchronous or asynchronous; its return value is ignored. One call
501
+ receives all records of the same change that run the trigger, up to 200 records and
502
+ 200 KiB, so a batch write or an import calls the handler once per chunk instead of
503
+ once per record. Keep `fields` short, and read related data for the whole list with
504
+ one `records.getMany` call rather than one read per record.
505
+
506
+ `data`, `schema`, `log`, `push`, and `invocation` are the same APIs that scripts receive.
507
+ A trigger context has no `input`, `request`, `response`, `state`, or `locks`; `push` is
508
+ refused in a before-change trigger.
509
+ `trigger.operation` is the operation of the current call, `trigger.id` identifies the
510
+ trigger registration, and `trigger.changeId` identifies the record change that caused
511
+ the call.
512
+
513
+ Each `TriggerRecord` describes one record:
514
+
515
+ - `key` correlates the record with its result. It is not a record ID.
516
+ - `id` is the record ID, or `null` while a record that is being created has no ID yet.
517
+ In an after-change trigger it is always set.
518
+ - `new` holds the values after the change as a plain, mutable object. It is `null`
519
+ when the record is deleted.
520
+ - `old` holds the values before the change and is deeply frozen. It is `null` when the
521
+ record is created.
522
+ - `changedFields` is a frozen list of the field slugs that changed. For a created
523
+ record it lists every field that has a value.
524
+
525
+ The declared `operations` narrow these types: `new` is never `null` unless
526
+ `"delete"` is declared, `old` is never `null` unless `"create"` is declared, and a
527
+ trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
528
+ `TriggerOldValues` make every field optional because a field that is not listed in
529
+ `fields`, or that has no value, is `undefined`.
530
+
531
+ ### Validating and changing records
532
+
533
+ This section applies to before-change triggers. In an after-change trigger the
534
+ change is already saved: `addError` only reports to the project log and
535
+ `record.new` must not be changed (see
536
+ [After-change execution rules](#after-change-execution-rules)).
537
+
538
+ `record.addError(field, code, message?)` rejects the record. `field` is a field slug,
539
+ or `null` for an error about the whole record. `code` starts with an upper-case ASCII
540
+ letter and contains upper-case letters, digits, or `_`; at most 64 characters, for
541
+ example `AMOUNT_TOO_LARGE`. `message` is an optional English text of at most 500
542
+ characters that Cogover shows to the end user when it has no translation for the
543
+ code; an empty message is ignored. Invalid arguments throw `ValidationError`. A
544
+ record may collect several errors.
545
+
546
+ A rejected record is not saved, and any change the handler made to it is discarded.
547
+ The writer receives HTTP 400 with `msg: "BEFORE_CHANGE_TRIGGER_REJECTED"`, the error
548
+ codes in `meta` keyed by field slug (`$record` for an error about the whole record),
549
+ and the optional texts in `messages` keyed by code. A rejected single-record write
550
+ stops at the first trigger that reports an error. In a batch write only the rejected
551
+ rows fail, and a rejected row is not passed to later triggers.
552
+
553
+ To change the values that will be saved, assign fields of `record.new`:
554
+
555
+ ```typescript
556
+ record.new.approval_level = "high";
557
+ record.new.customer = "ACC-1"; // same format as records.update() input
558
+ record.new.note = null; // clears the field
559
+ ```
560
+
561
+ - Only fields listed in `writableFields` may change. When the handler returns, the
562
+ SDK compares every top-level field of `record.new` with a snapshot taken before the
563
+ handler ran, using a deep JSON comparison. Changing any other field, including
564
+ `id`, throws `ValidationError` naming the field, and the write fails.
565
+ - Assigned values use the same format as `records.update` input and must be JSON
566
+ data. `NaN`, functions, `Map`, `Set`, and class instances are rejected; a `Date` is
567
+ stored as its ISO string. Assigning `null` clears a field; assigning `undefined` or
568
+ deleting the field has the same effect.
569
+ - A change inside an array or object value is detected and sends the whole field value.
570
+ - `record.new` itself cannot be replaced, and a record that is being deleted has
571
+ nothing to change.
572
+ - Cogover validates the final values again before saving, including field types and
573
+ required, unique, and duplicate rules. For the fields a trigger changed, the
574
+ field's manual create/modify setting and the writer's field edit permission are
575
+ not applied. Read-only fields such as formulas, auto numbers, and rollups, and
576
+ system fields, are always refused.
577
+
578
+ ### Before-change execution rules
579
+
580
+ A before-change trigger runs for every source of a write: the Cogover web
581
+ application, API keys, imports, automation processes, other Custom Backend Modules,
582
+ and writes made through `data.asUser()` or `data.asSystem()`. Maintenance writes
583
+ made by Cogover itself — recalculating formula and rollup fields, background record
584
+ merges, and cascading deletes — do not run before-change triggers, and neither does
585
+ a request that only validates input without saving.
586
+
587
+ - **Read-only.** A before-change trigger may read records and schema, but every
588
+ record write, `fetch`, lock, state write, and push message is refused with
589
+ `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
590
+ applies to every identity, including `data.asSystem()`.
591
+ - **Identity.** `data.object()` acts as the user who made the change, with that
592
+ user's permissions, and `invocation` describes the same user. When a change has
593
+ no user, `invocation.identity` is `"system"` and `data.object()` works only if the
594
+ project's approved identity policy sets `allowInternalSystem: true`; otherwise its
595
+ calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`
596
+ while the handler still receives `records`. `data.asUser()` and `data.asSystem()`
597
+ follow the project's identity policy as usual.
598
+ - **Fail closed.** When a handler throws, exceeds `timeoutMs`, exceeds a runtime
599
+ limit, or cannot be run, the write is rejected and nothing is saved. The writer
600
+ receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
601
+ - **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
602
+ one write share a total budget of 8 seconds.
603
+
604
+ ### After-change execution rules
605
+
606
+ An after-change trigger (`timing: "afterChange"`) runs asynchronously, shortly after
607
+ the change has been saved. Use it for follow-up work such as creating or updating
608
+ related records or notifying another system. It runs for the same sources of a
609
+ write as a before-change trigger, with the same exceptions.
610
+
611
+ ```typescript
612
+ import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
613
+
614
+ export const triggers = [
615
+ defineTrigger({
616
+ key: "order_confirmed_notify",
617
+ object: "order",
618
+ timing: "afterChange",
619
+ operations: ["create", "update"],
620
+ fields: ["status", "amount"],
621
+ changedFields: ["status"],
622
+ when: { op: "=", field: "status", params: "confirmed" },
623
+ runWhen: "onEnter",
624
+ }, async ({ records, trigger }) => {
625
+ for (const record of records) {
626
+ const response = await fetch("https://erp.example.com/orders", {
627
+ method: "POST",
628
+ headers: {
629
+ "content-type": "application/json",
630
+ // The same change of the same record always produces the same key.
631
+ "idempotency-key": `${trigger.changeId}:${record.id}`,
632
+ },
633
+ body: JSON.stringify({ id: record.id, amount: record.new.amount }),
634
+ });
635
+ if (response.status >= 500) {
636
+ throw new RetryableError("The ERP is temporarily unavailable");
637
+ }
638
+ }
639
+ }),
640
+ ];
641
+ ```
642
+
643
+ - **Cannot block or change the saved record.** The writer has already received its
644
+ response. `writableFields` is not allowed, and changing `record.new` makes the call
645
+ fail with `ValidationError`. `record.addError()` rejects nothing: the reported
646
+ errors are only written to the project log. To change the record, call
647
+ `records.update`; that is a new write and runs triggers again.
648
+ - **Saved values.** `record.id` is always set. `record.new` holds the values as they
649
+ were saved, including the record ID and values assigned while saving, such as an
650
+ auto number. For a deleted record `record.new` is `null` and `record.old` holds the
651
+ last values.
652
+ - **May write and call out.** Record writes and `fetch` work as they do in a script,
653
+ within the same runtime limits. `data.object()` acts as the user who made the
654
+ change, and the other identity rules of before-change triggers apply. The trigger
655
+ context has no `state` or `locks`; `push` is available and is the usual way to
656
+ refresh the records the handler changed for everyone who has them open.
657
+ - **Best-effort delivery.** Cogover does not guarantee that an after-change handler
658
+ runs exactly once. It may occasionally run more than once for the same change, or
659
+ not at all. Make every handler idempotent: `trigger.changeId` together with
660
+ `record.id` identifies one change of one record. Never make an after-change
661
+ trigger the only guarantee of a critical rule; enforce such rules in a
662
+ before-change trigger.
663
+ - **Retries.** Throw `RetryableError` when a handler fails for a temporary reason,
664
+ such as an external service that is unavailable. Cogover runs the handler again
665
+ later: by default up to 5 more times, waiting longer before each attempt, from
666
+ about one second to about ten minutes. A call that exceeds `timeoutMs`, or that
667
+ Cogover could not run for a temporary reason, is retried the same way. Any other
668
+ error is not retried: the failure is logged and the handler does not run again for
669
+ that change. When the retries are used up, the handler does not run again for that
670
+ change either.
671
+ - **Loops end.** A write made by a trigger runs triggers again, possibly including
672
+ the same trigger. Cogover limits such chains: every automated write uses one step
673
+ of a fixed budget (10 steps for a change made directly by a user or an API
674
+ client), and after-change triggers no longer run once the budget is used up. Use
675
+ `changedFields`, `when`, and `runWhen: "onEnter"` so that a handler's own writes
676
+ do not start it again.
677
+ - **Order and time.** Each call must finish within `timeoutMs`. After-change triggers
678
+ of one change run independently of each other: do not rely on their relative
679
+ order. A retried call may run after a later change of the same record has already
680
+ been processed, so read the current record when the latest values matter.
681
+
253
682
  ## Outbound HTTP `fetch`
254
683
 
255
684
  ```typescript
@@ -325,6 +754,7 @@ request. Use the remote API's idempotency mechanism and never retry blindly.
325
754
  ```typescript
326
755
  const orders = data.object("order");
327
756
  await orders.records.get(id, { fields });
757
+ await orders.records.getMany(ids, { fields });
328
758
  await orders.records.list({ where, orderBy, fields, limit, cursor });
329
759
  await orders.records.create(fields);
330
760
  await orders.records.update(id, fields);
@@ -376,6 +806,11 @@ interface RecordPage<Fields> {
376
806
  readonly nextCursor?: string;
377
807
  }
378
808
 
809
+ interface GetManyResult<Fields> {
810
+ readonly records: CogoverRecord<Fields>[];
811
+ readonly missingIds: CogoverRecordId[];
812
+ }
813
+
379
814
  interface DeleteResult {
380
815
  readonly deleted: CogoverRecordId[];
381
816
  readonly notDeleted: CogoverRecordId[];
@@ -420,6 +855,10 @@ interface GetRecordOptions<Fields> {
420
855
  readonly fields?: readonly (keyof Fields & string)[];
421
856
  }
422
857
 
858
+ interface GetManyOptions<Fields> {
859
+ readonly fields: readonly (keyof Fields & string)[];
860
+ }
861
+
423
862
  interface ListOptions<Fields> {
424
863
  readonly where?: FilterExpression;
425
864
  readonly orderBy?: readonly SortExpression[];
@@ -442,6 +881,7 @@ interface RecordWritesApi<Fields> {
442
881
 
443
882
  interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
444
883
  get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
884
+ getMany(ids: readonly string[], options: GetManyOptions<Fields>): Promise<GetManyResult<Fields>>;
445
885
  list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
446
886
  }
447
887
 
@@ -470,6 +910,25 @@ interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
470
910
  `nextCursor`. A `CogoverRecord<T>` has `id`, business `fields`, and a separate
471
911
  `system` object containing creation/update metadata.
472
912
 
913
+ `getMany(ids, { fields })` reads up to 200 records by ID with a single capability
914
+ call. `fields` is required and must be a non-empty list of field slugs. IDs are
915
+ trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
916
+ ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
917
+ An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
918
+ The result contains the readable `records` and `missingIds`: every requested ID that
919
+ could not be read, because the record does not exist or the identity in use cannot
920
+ see it. IDs are never dropped silently. The order of `records` is not guaranteed to
921
+ follow `ids`, so index them by `id`:
922
+
923
+ ```typescript
924
+ const accounts = data.object("account");
925
+ const { records, missingIds } = await accounts.records.getMany(accountIds, { fields: ["credit_limit"] });
926
+ const accountById = new Map(records.map(record => [record.id, record]));
927
+ ```
928
+
929
+ Use `getMany` instead of calling `get` in a loop. Every capability call counts
930
+ towards the project's limits, and a record trigger can receive 200 records at once.
931
+
473
932
  Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
474
933
  responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
475
934
  `RecordReference` and send only the ID to Cogover.
@@ -571,7 +1030,7 @@ invocation this is the caller; a system invocation keeps system access.
571
1030
  Returns a new immutable client for reads and writes as the specified personnel ID (not an
572
1031
  account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
573
1032
  value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
574
- whose `records: RecordsApi<TFields>` exposes `get`, `list`, `create`, `update`, and
1033
+ whose `records: RecordsApi<TFields>` exposes `get`, `getMany`, `list`, `create`, `update`, and
575
1034
  `deleteMany` as well as batch insert, batch update, and business upsert, with the
576
1035
  same argument and return types as the default record API.
577
1036
 
@@ -594,7 +1053,7 @@ const page = await delegatedOrders.records.list({
594
1053
  ### `data.asSystem(): DataApi<TSchema>`
595
1054
 
596
1055
  Returns a new immutable client for system record access, including during an
597
- authenticated public invocation. It supports `get`, `list`, `create`, `update`, and
1056
+ authenticated public invocation. It supports `get`, `getMany`, `list`, `create`, `update`, and
598
1057
  `deleteMany`, including batch writes and business upsert. System access does not
599
1058
  apply the caller's record permissions; approved project restrictions, field
600
1059
  validation, workspace boundaries, and runtime limits still apply. It neither
@@ -755,6 +1214,115 @@ system supports it, store/check `fencingToken` and reject stale tokens. Locks do
755
1214
  replace idempotency, provide exactly-once execution, or combine Record API and state
756
1215
  operations into a transaction.
757
1216
 
1217
+ ## Push messages
1218
+
1219
+ `push` sends messages to the web clients of the workspace: a request to reload
1220
+ records, a toast, or a background message the client handles silently. It is the
1221
+ same mechanism as the Workflow "Push Message" action, so the standard record pages
1222
+ react without custom client code. Delivery is best-effort: a call resolves once the
1223
+ messages are handed to Cogover, never when a client receives them.
1224
+
1225
+ ```typescript
1226
+ type PushRecipients = "viewers" | readonly string[];
1227
+
1228
+ interface PushOptions {
1229
+ readonly recipients?: PushRecipients;
1230
+ readonly exclude?: readonly string[];
1231
+ }
1232
+
1233
+ type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT"
1234
+ | "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
1235
+ type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
1236
+
1237
+ interface ToastLink {
1238
+ readonly label: string;
1239
+ readonly url: string;
1240
+ }
1241
+
1242
+ interface ToastMessage<ObjectSlug extends string = string> {
1243
+ readonly title?: string;
1244
+ readonly content?: string;
1245
+ readonly links?: readonly ToastLink[];
1246
+ readonly position?: ToastPosition;
1247
+ readonly size?: ToastSize;
1248
+ readonly durationSeconds?: number;
1249
+ readonly object?: ObjectSlug;
1250
+ readonly recordIds?: readonly string[];
1251
+ }
1252
+
1253
+ type BackgroundContentType = "text" | "template";
1254
+
1255
+ interface BackgroundMessage<ObjectSlug extends string = string> {
1256
+ readonly content: string;
1257
+ readonly contentType?: BackgroundContentType;
1258
+ readonly object?: ObjectSlug;
1259
+ readonly recordIds?: readonly string[];
1260
+ }
1261
+
1262
+ interface PushApi<Schema extends object = EffectiveWorkspaceObjects> {
1263
+ refreshRecords(object: StringKeyOf<Schema>, recordIds: readonly string[],
1264
+ options?: PushOptions): Promise<void>;
1265
+ toast(message: ToastMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
1266
+ message(message: BackgroundMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
1267
+ }
1268
+ ```
1269
+
1270
+ ```typescript
1271
+ // After-change trigger: the handler changed the records, so everyone who has them
1272
+ // open must reload, including the user whose save started the trigger.
1273
+ await data.object("order").records.batchUpdate(items);
1274
+ await push.refreshRecords("order", items.map(item => item.id));
1275
+ ```
1276
+
1277
+ ### Recipients
1278
+
1279
+ Every method accepts the same `options`. `recipients` defaults to `"viewers"`:
1280
+ everyone who currently has one of the target records open receives the message, so
1281
+ `object` and `recordIds` are required. A list of personnel IDs delivers to those
1282
+ people wherever they are in the workspace; `object` and `recordIds` are then
1283
+ optional for `toast` and `message` and, when given, tell the client which records
1284
+ the message is about. `exclude` lists personnel IDs that never receive the message;
1285
+ the special value `"actor"` is the user whose action started the current execution
1286
+ (the caller of an HTTP script, the user whose save ran a trigger). A system
1287
+ execution has no actor, so `"actor"` excludes nobody. Personnel without a user
1288
+ account are skipped silently; an unknown personnel ID or object slug throws
1289
+ `NotFoundError` before anything is sent. A call accepts at most 200 record IDs and
1290
+ 200 personnel IDs; duplicates are removed.
1291
+
1292
+ ### `push.refreshRecords(object, recordIds, options?): Promise<void>`
1293
+
1294
+ Asks the clients that show these records to reload them. The record page of the
1295
+ web app handles the request itself. `recordIds` accepts 1 to 200 IDs.
1296
+
1297
+ ### `push.toast(message, options?): Promise<void>`
1298
+
1299
+ Shows a short notification. At least one of `title` (up to 200 characters) and
1300
+ `content` (up to 4,000 characters) is required. `links` holds up to 5 entries whose
1301
+ `url` is an absolute `http` or `https` URL. `position` defaults to `"TOP_RIGHT"`,
1302
+ `size` to `"MEDIUM"` and `durationSeconds` to 5 (1 to 60). When `object` and
1303
+ `recordIds` are given, the client shows the toast only while one of those records
1304
+ is open.
1305
+
1306
+ ### `push.message(message, options?): Promise<void>`
1307
+
1308
+ Sends a message the client handles without a visible notification, for example a
1309
+ custom component listening for it. `content` is required (up to 16,384 characters);
1310
+ `contentType` is `"text"` (default) or `"template"`.
1311
+
1312
+ ### Rules
1313
+
1314
+ - Each call costs one capability call regardless of the number of records or
1315
+ recipients; when the recipients are `"viewers"`, one message is sent per record.
1316
+ - Inputs are validated by the SDK and again by Cogover; invalid input throws
1317
+ `ValidationError` before any message is sent.
1318
+ - `push` is available in scripts, routes, after-change triggers and Development
1319
+ Sessions. A before-change trigger is read-only and receives `PermissionDeniedError`
1320
+ with reason `TRIGGER_READ_ONLY`; a read-only Development Session refuses it too.
1321
+ - When push messages are switched off for the deployment, every call throws
1322
+ `CogoverApiError` with code `PUSH_DISABLED`.
1323
+ - A sent message cannot be recalled, and retrying a failed execution may send it
1324
+ again.
1325
+
758
1326
  ## Schema API
759
1327
 
760
1328
  `SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
@@ -839,6 +1407,10 @@ class RateLimitError extends CogoverApiError {
839
1407
  constructor(message: string, details?: unknown);
840
1408
  }
841
1409
 
1410
+ class RetryableError extends CogoverApiError {
1411
+ constructor(message: string, details?: unknown);
1412
+ }
1413
+
842
1414
  class StateConflictError extends CogoverApiError {
843
1415
  constructor(message: string, details?: unknown);
844
1416
  }
@@ -857,6 +1429,13 @@ result in `error.r` (also retained in `error.details.r`). `r` is `undefined` whe
857
1429
  there was no server response, such as local SDK validation. The original message
858
1430
  remains in `error.message`.
859
1431
 
1432
+ `RetryableError` (`code: "RETRYABLE"`) is thrown by project code, never by the SDK.
1433
+ An after-change trigger handler throws it to report a temporary failure, and Cogover
1434
+ runs the handler again later (see
1435
+ [After-change execution rules](#after-change-execution-rules)). Anywhere else it
1436
+ has no special meaning: a script that lets it escape returns HTTP 422, and a
1437
+ before-change trigger that throws it rejects the write like any other failure.
1438
+
860
1439
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
861
1440
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
862
1441
  the original code or message. A script's returned JSON remains its own response
@@ -898,6 +1477,7 @@ For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
898
1477
  | `FETCH_TIMEOUT` | 504 |
899
1478
  | `FETCH_FAILED` | 502 |
900
1479
  | `COGOVER_API_ERROR` | 422 |
1480
+ | `RETRYABLE` | 422 |
901
1481
 
902
1482
  Missing approval for an explicit identity adds `reason: "IDENTITY_NOT_GRANTED"`;
903
1483
  it does not mean the selected user was denied access to a particular record.