@cogover/sdk 0.13.0 → 0.15.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.
Files changed (40) hide show
  1. package/README.md +63 -5
  2. package/dist/action-schema.d.ts +86 -0
  3. package/dist/action-schema.js +52 -0
  4. package/dist/actions.d.ts +129 -0
  5. package/dist/actions.js +11 -0
  6. package/dist/agents.d.ts +75 -0
  7. package/dist/agents.js +1 -0
  8. package/dist/index.d.ts +8 -0
  9. package/dist/index.js +3 -0
  10. package/dist/internal/action-config.js +94 -0
  11. package/dist/internal/action-runtime.js +143 -0
  12. package/dist/internal/action-schema-rules.js +33 -0
  13. package/dist/internal/agents-api.js +163 -0
  14. package/dist/internal/job-runtime.js +9 -2
  15. package/dist/internal/local-invocation.js +8 -0
  16. package/dist/internal/processes-api.js +74 -0
  17. package/dist/internal/schema-nodes.js +179 -0
  18. package/dist/internal/start-options.js +52 -0
  19. package/dist/internal/trigger-runtime.js +10 -2
  20. package/dist/jobs.d.ts +7 -0
  21. package/dist/limits.d.ts +33 -0
  22. package/dist/limits.js +51 -0
  23. package/dist/processes.d.ts +52 -0
  24. package/dist/processes.js +1 -0
  25. package/dist/router.js +3 -0
  26. package/dist/script.d.ts +7 -0
  27. package/dist/script.js +9 -2
  28. package/dist/trigger.d.ts +9 -0
  29. package/docs/en/api-reference/actions.md +403 -0
  30. package/docs/en/api-reference/background-jobs.md +24 -12
  31. package/docs/en/api-reference/cryptography.md +3 -2
  32. package/docs/en/api-reference/fetch-and-secrets.md +5 -5
  33. package/docs/en/api-reference/organization-structure.md +4 -3
  34. package/docs/en/api-reference/overview.md +124 -15
  35. package/docs/en/api-reference/processes-and-agents.md +357 -0
  36. package/docs/en/api-reference/record-triggers.md +10 -5
  37. package/docs/en/api-reference/records.md +23 -16
  38. package/docs/en/api-reference/scripts-and-routes.md +10 -4
  39. package/docs/en/usage-guide.md +159 -7
  40. package/package.json +1 -1
@@ -320,8 +320,10 @@ const { records, missingIds } = await accounts.records.getMany(accountIds, { fie
320
320
  const accountById = new Map(records.map(record => [record.id, record]));
321
321
  ```
322
322
 
323
- Use `getMany` instead of calling `get` in a loop. Every capability call counts
324
- towards the project's limits, and a record trigger can receive 200 records at once.
323
+ Use `getMany` instead of calling `get` in a loop. Every capability call and every record
324
+ read counts towards the budgets of the execution (see
325
+ [Execution limits](overview.md#execution-limits)), and a record trigger can receive 200
326
+ records at once.
325
327
 
326
328
  Service `0`/`1` booleans are normalized to JavaScript booleans. A lookup or reference
327
329
  value is a `RecordReference` with `id`, `name`, and `objectSlug`. Its `name` is `""`
@@ -351,9 +353,10 @@ field as its UTC day. Other text for these fields throws `ValidationError` with
351
353
  costs no more than what the script uses. `fields` is required and is one of:
352
354
 
353
355
  - a non-empty list of field slugs, trimmed and deduplicated in their original order;
354
- - the string `"*"` on its own: every field that the identity in use may read and the
355
- project's identity policy grants. When the policy grants only some fields, `"*"`
356
- means those fields, not every field of the Object.
356
+ - the string `"*"` on its own: every field that the identity in use may read. With
357
+ `data.asUser()` or `data.asSystem()` it is limited to the fields that the project's
358
+ identity policy grants: when the policy grants only some fields, `"*"` means those
359
+ fields, not every field of the Object.
357
360
 
358
361
  Leaving `fields` out, or passing `null`, an empty list, `["*"]`, or a value that is not
359
362
  a field slug, throws `ValidationError` before any request is sent, with this message:
@@ -368,9 +371,11 @@ and publish it again.
368
371
 
369
372
  The system slugs `id`, `created`, `updated`, and `created_by` may be listed; their
370
373
  values are always returned in `id` and `system`, not in `fields`. `where` and `orderBy`
371
- may use fields that are not in `fields`. Every field of `fields`, `where`, and
372
- `orderBy` must be granted by the project's identity policy, otherwise the read throws
373
- `PermissionDeniedError`; a slug that the Object does not have throws `ValidationError`.
374
+ may use fields that are not in `fields`. With `data.asUser()` or `data.asSystem()`,
375
+ every field of `fields`, `where`, and `orderBy` must be granted by the project's identity
376
+ policy, otherwise the read throws `PermissionDeniedError`; reads through `data.object()`
377
+ need no policy and follow the permissions of the identity in use. A slug that the Object
378
+ does not have throws `ValidationError`.
374
379
 
375
380
  The result type follows `fields`. With workspace declarations, `fields: ["code",
376
381
  "amount"]` returns `CogoverRecord<Pick<Fields, "code" | "amount">>`, so reading a field
@@ -429,8 +434,9 @@ person's full name; for display names, use
429
434
  with `withDisplay: true`.
430
435
 
431
436
  Linked records are read with the same identity as the read itself: the caller,
432
- `data.asUser()`, or `data.asSystem()`. The project's identity policy must grant reading
433
- the linked Object:
437
+ `data.asUser()`, or `data.asSystem()`. With `data.object()` the linked records follow
438
+ the permissions of the identity in use. With `data.asUser()` or `data.asSystem()`, the
439
+ project's identity policy must also grant reading the linked Object:
434
440
 
435
441
  - With `true` or `"*"`, only the linked fields that the policy grants are returned.
436
442
  When the policy does not grant reading the linked Object, its values stay
@@ -485,7 +491,7 @@ letters, digits, or underscores, and each metric is exactly one of:
485
491
  | Metric | Field | Value |
486
492
  |---|---|---|
487
493
  | `{ count: "id" }` | | number of matching records |
488
- | `{ count: field }` | any field except `reference`, `file`, and `url` | number of matching records with a value in the field |
494
+ | `{ count: field }` | number, date, choice, `boolean`, `lookup_normal`, text, `email`, `phone`, and `auto_number` fields; not `reference`, `file`, `url`, `formula`, or `rollup_summary` | number of matching records with a value in the field |
489
495
  | `{ countDistinct: field }` | the fields that `count` accepts | number of distinct values, approximate on large sets |
490
496
  | `{ sum: field }` | `numeric`, `decimal`, `currency`, `percent` | sum |
491
497
  | `{ avg: field }` | the number types above | average; `null` when no matching record has a value |
@@ -509,9 +515,10 @@ group.
509
515
  1,000 when it is left out. `truncated` is `true` when there were more groups and only
510
516
  the first `limit` are returned.
511
517
 
512
- Every field of `where`, `groupBy`, and `metrics`, except `"id"`, must be granted by the
513
- project's identity policy, otherwise the call throws `PermissionDeniedError`. Only the
514
- records that the identity in use can see are counted.
518
+ With `data.asUser()` or `data.asSystem()`, every field of `where`, `groupBy`, and
519
+ `metrics`, except `"id"`, must be granted by the project's identity policy, otherwise the
520
+ call throws `PermissionDeniedError`. Only the records that the identity in use can see are
521
+ counted.
515
522
 
516
523
  A client from `data.asUser()` has narrower limits:
517
524
 
@@ -524,8 +531,8 @@ A client from `data.asUser()` has narrower limits:
524
531
  avg, min and max on number fields; use the caller or asSystem()`).
525
532
 
526
533
  The same limits apply to `data.object()` when the execution reads as a user who is not
527
- an HTTP caller: in a record trigger for a change made by a user, or in a job run that
528
- has a user. Grouping
534
+ an HTTP caller: in a record trigger for a change made by a user, in a job run that has
535
+ a user, or in a local Development Session started by `cogover-dev run`. Grouping
529
536
  there throws `ValidationError` (`aggregate with groupBy is not supported for the default
530
537
  identity of this invocation, which reads as a delegated user; use asSystem()`). Use
531
538
  `data.asSystem()` there, or the caller in an HTTP route, for groups and the other
@@ -6,8 +6,9 @@ This page is part of the [`@cogover/sdk` API reference](overview.md).
6
6
 
7
7
  `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
8
8
  the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
9
- `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
10
- result.
9
+ `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, `limits`, `processes`, and `agents`,
10
+ awaits the handler, and
11
+ serializes its result.
11
12
 
12
13
  ```typescript
13
14
  function defineScript<
@@ -44,6 +45,9 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
44
45
  readonly secrets: SecretsApi;
45
46
  readonly crypto: CryptoApi;
46
47
  readonly org: OrgApi;
48
+ readonly limits: LimitsApi;
49
+ readonly processes: ProcessesApi;
50
+ readonly agents: AgentsApi;
47
51
  }
48
52
  ```
49
53
 
@@ -54,8 +58,10 @@ Returning `null` produces a null handler result; returning `undefined` is invali
54
58
  ## HTTP routers and request context
55
59
 
56
60
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
57
- `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
58
- and route handlers. `input`
61
+ `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, `limits`,
62
+ `processes`, and `agents` to both script and route handlers. `limits` reads the budgets of the execution (see
63
+ [Reading limits in code](overview.md#reading-limits-in-code)), and `processes` and `agents` start Processes and
64
+ AI Agents (see [Processes and AI Agents](processes-and-agents.md)). `input`
59
65
  preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
60
66
  metadata and transport/authentication fields removed by Cogover.
61
67
 
@@ -11,7 +11,8 @@ interface.
11
11
  Custom Backend Modules are written in TypeScript. `@cogover/sdk` supplies the
12
12
  types and APIs for the current invocation, workspace data, schema metadata,
13
13
  logging, outbound HTTPS requests, state, distributed locks, push messages to web
14
- clients, background jobs, secrets, cryptography, and inbound webhooks. Cogover
14
+ clients, background jobs, secrets, cryptography, inbound webhooks, Processes and AI
15
+ Agents, and actions that Processes and AI Agents call. Cogover
15
16
  executes the module with the permissions and resource limits configured for the
16
17
  project.
17
18
 
@@ -175,7 +176,8 @@ const approvers = chain?.tiers.flatMap(tier =>
175
176
  ## Choose the fields to read
176
177
 
177
178
  Every read names its fields: the slugs the script uses, or `"*"` for every field that
178
- the identity in use and the project's identity policy may read. A read without
179
+ the identity in use may read (with `data.asUser()` or `data.asSystem()`, only the fields
180
+ that the project's identity policy grants). A read without
179
181
  `fields` throws `ValidationError` (`fields is required: pass field slugs or "*"
180
182
  (@cogover/sdk 0.13.0+)`) before anything is sent.
181
183
 
@@ -225,7 +227,8 @@ if (missingIds.length > 0) log.warn("Accounts could not be read", { missingIds }
225
227
 
226
228
  Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
227
229
  `ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
228
- every capability call counts towards the project's limits.
230
+ every capability call and every record read counts towards the budgets of the
231
+ execution.
229
232
 
230
233
  ## Read linked records
231
234
 
@@ -265,8 +268,9 @@ for (const group of byStatus.groups) {
265
268
  ```
266
269
 
267
270
  Without `groupBy` the result is `{ values }`. A client from `data.asUser()`, like
268
- `data.object()` in a trigger or a job that runs as a user, cannot group and supports
269
- only counts and number metrics; use `data.asSystem()` there. Aggregates follow record writes after about one second,
271
+ `data.object()` in a trigger or a job that runs as a user or in a local Development
272
+ Session started by `cogover-dev run`, cannot group and supports only counts and number
273
+ metrics; use `data.asSystem()` there, or try grouping on a published version. Aggregates follow record writes after about one second,
270
274
  so a record saved just before may not be counted yet. See
271
275
  [Aggregates](api-reference/records.md#aggregates) for every metric and limit.
272
276
 
@@ -406,7 +410,16 @@ and the JWT algorithm names.
406
410
  - Cogover authentication credentials are never exposed to module code. Access is
407
411
  limited to the configured Objects, operations, and fields.
408
412
  - TypeScript types do not replace runtime validation of business input.
409
- - Cogover limits capability calls, request and response sizes, and execution time.
413
+ - Cogover limits, for each execution, the capability calls, the local calls (`crypto`,
414
+ `org` without display data), the records read and written, request and response
415
+ sizes, and execution time. An HTTP route may make 100 capability calls and read
416
+ 10,000 records; a background job 1,000 calls and 50,000 records. A call that would go
417
+ over a budget throws `RateLimitError` with `details.budget`; waiting does not help.
418
+ - `limits.usage()` (also `context.limits`) tells how much of each budget the execution
419
+ has used, without a capability call. Use it to hand the rest of a long task to a
420
+ background job before a budget runs out.
421
+ - Totals and counts do not need to read records: `records.aggregate` is one capability
422
+ call whatever the number of records.
410
423
  - Do not automatically retry writes after a timeout because the commit outcome may
411
424
  be unknown.
412
425
 
@@ -543,7 +556,8 @@ router.post("/recalculate", async ({ jobs, response }) => {
543
556
 
544
557
  - A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
545
558
  to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
546
- `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` APIs as a script.
559
+ `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, `processes`, and `agents` APIs
560
+ as a script.
547
561
  Its return value is ignored.
548
562
  - A run enqueued from a route or trigger acts as the user of that call. A scheduled
549
563
  run has no user: `data.object()` works only when the identity policy allows the
@@ -565,6 +579,144 @@ router.post("/recalculate", async ({ jobs, response }) => {
565
579
  See the [background job reference](api-reference/background-jobs.md#background-jobs) for every
566
580
  option and rule.
567
581
 
582
+ ## Let Processes and AI Agents call your code
583
+
584
+ A **Custom Module Action** is a short operation of the module that a Process or an
585
+ AI Agent calls: a **Custom Module Action** node in Process Builder, or a tool of the
586
+ **Custom Module** category in AI Agent Builder. Declare actions with `defineAction`
587
+ and list them in the named `actions` export. Describe the input and output with the
588
+ `s` schema builder: the same declaration types the handler, lets Cogover check the
589
+ data, and tells the builders and the AI Agent what the action needs.
590
+
591
+ ```typescript
592
+ import { defineAction, s } from "@cogover/sdk";
593
+
594
+ export const actions = [
595
+ defineAction({
596
+ key: "check_credit",
597
+ label: "Check customer credit",
598
+ description: "Returns whether an account can buy the given amount on credit, and its remaining credit.",
599
+ exposeTo: ["process", "agent"],
600
+ effect: "read",
601
+ input: s.object({
602
+ accountId: s.recordId("account").describe("ID of the customer account"),
603
+ amount: s.number({ minimum: 0 }).describe("Order amount in the account currency"),
604
+ }),
605
+ output: s.object({
606
+ allowed: s.boolean(),
607
+ remaining: s.number(),
608
+ reason: s.enum(["ok", "limit_exceeded", "account_not_found"]),
609
+ }),
610
+ async handler({ data }, input) {
611
+ const account = await data.object("account").records.get(input.accountId, {
612
+ fields: ["credit_limit", "credit_used"],
613
+ });
614
+ if (!account) return { allowed: false, remaining: 0, reason: "account_not_found" };
615
+ const remaining = Number(account.fields.credit_limit ?? 0) - Number(account.fields.credit_used ?? 0);
616
+ const allowed = input.amount <= remaining;
617
+ return { allowed, remaining, reason: allowed ? "ok" : "limit_exceeded" };
618
+ },
619
+ }),
620
+ ];
621
+ ```
622
+
623
+ - Publish and activate the version: the action then appears in Process Builder and in
624
+ AI Agent Builder. They call the active version, so keep `key` stable.
625
+ - `exposeTo` chooses where the action is offered. An action for AI Agents needs a
626
+ `description`, and the `describe` texts help the agent fill the input correctly.
627
+ - `effect: "read"` runs the action read-only. A `"write"` action may change data, and
628
+ an AI Agent tool for it asks a person for approval by default.
629
+ - Cogover checks the input before the handler runs and the output after it returns.
630
+ A Process or an agent only receives the code of an error the handler throws, so
631
+ report expected outcomes in the output, like `reason` above.
632
+ - The Process node or the agent decides who the action runs as: the Process starter, a
633
+ chosen personnel, the person the agent acts for, or no user. Without a user, the
634
+ approved identity policy must set `allowInternalSystem: true`.
635
+ - An action has the budgets of an HTTP route and at most 8 seconds (`timeoutMs`). Hand
636
+ longer work to a background job with `jobs.enqueue`, using `action.runId` as the
637
+ idempotency key: a caller that retries sends the same `runId`.
638
+
639
+ See the [Custom Module Action reference](api-reference/actions.md#custom-module-actions)
640
+ for every option, the schema rules, and the errors callers receive.
641
+
642
+ ## Start Processes and AI Agents from code
643
+
644
+ `processes.start` starts a Cogover Process and `agents.start` runs an AI Agent from a
645
+ route, an after-change trigger, a job, or an action. Both return as soon as the run is
646
+ created; the outcome is delivered to a background job named in `onComplete` or
647
+ `onResult`. The project's identity policy must allow the Processes and agents in its
648
+ `processes` and `agents` sections.
649
+
650
+ ```typescript
651
+ import { createRouter, defineJob, s } from "@cogover/sdk";
652
+ import type { AgentResultJobPayload, CogoverRecordId, ProcessCompletionJobPayload } from "@cogover/sdk";
653
+
654
+ const router = createRouter();
655
+
656
+ // Starts the approval Process of a quote; the job below receives its outcome.
657
+ router.post("/quotes/:id/submit", async ({ request, processes, response }) => {
658
+ const quoteId = request.params.id;
659
+ const { instanceId } = await processes.start("PIXXXXXXXXXXXX", {
660
+ input: { quote_id: quoteId },
661
+ idempotencyKey: `quote-approval:${quoteId}`,
662
+ onComplete: { job: "quote_approved", payload: { quoteId } },
663
+ });
664
+ return response.json({ instanceId }, { status: 202 });
665
+ });
666
+
667
+ // Asks an AI Agent to classify a support ticket and stores the answer.
668
+ router.post("/tickets/:id/classify", async ({ request, agents, response }) => {
669
+ const ticketId = request.params.id;
670
+ const { runId } = await agents.start("AGXXXXXXXXXXXX", {
671
+ instruction: "Classify this support ticket by product area and urgency.",
672
+ records: [{ objectSlug: "ticket", recordId: ticketId }],
673
+ resultSchema: s.object({
674
+ area: s.enum(["billing", "shipping", "product"]),
675
+ urgent: s.boolean(),
676
+ }),
677
+ idempotencyKey: `classify:${ticketId}`,
678
+ onResult: { job: "ticket_classified", payload: { ticketId } },
679
+ });
680
+ return response.json({ runId }, { status: 202 });
681
+ });
682
+
683
+ export default router.toHandler();
684
+
685
+ export const jobs = [
686
+ defineJob<ProcessCompletionJobPayload<{ quoteId: CogoverRecordId }>>({ key: "quote_approved" }, async ({ payload, data }) => {
687
+ if (payload?.payload == null || payload.process.state !== "COMPLETED") return;
688
+ await data.object("quote").records.update(payload.payload.quoteId, { status: "approved" });
689
+ }),
690
+ defineJob<AgentResultJobPayload<{ ticketId: CogoverRecordId }, { area: string; urgent: boolean }>>(
691
+ { key: "ticket_classified" },
692
+ async ({ payload, data }) => {
693
+ const result = payload?.agentRun.result;
694
+ if (payload?.payload == null || result == null) return;
695
+ await data.object("ticket").records.update(payload.payload.ticketId, {
696
+ area: result.area,
697
+ urgent: result.urgent,
698
+ });
699
+ },
700
+ ),
701
+ ];
702
+ ```
703
+
704
+ - The Process or agent runs as the user of the call and Cogover checks that user's
705
+ own permission; a call without a user needs `allowSystem` in the policy section,
706
+ and an agent then uses `runAs: "agent"`.
707
+ - Pass `idempotencyKey`: a repeated start returns the first run with
708
+ `duplicate: true`, and after `RetryableError` a retry with the same key cannot start
709
+ a second one.
710
+ - One execution may start at most 20 Processes and 5 agent runs, and each project has
711
+ a daily limit of agent runs (`maxRunsPerDay`, 200 by default).
712
+ - `processes.get` and `agents.get` read the current state of a run the project
713
+ started. Do not wait for the result inside a route: use the job.
714
+ - With Cogover Dev CLI, starts are real, but `onComplete` and `onResult` are refused
715
+ with `NOT_SUPPORTED`; test the job after publishing.
716
+
717
+ See the [Process and AI Agent reference](api-reference/processes-and-agents.md#processes-and-ai-agents)
718
+ for every option, limit, and error.
719
+
568
720
  ## Send notifications and email
569
721
 
570
722
  `notifications.send` puts a notification in people's notification list (the bell)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,