@cogover/sdk 0.14.0 → 0.16.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.
@@ -227,6 +227,8 @@ interface TriggerContext<
227
227
  readonly crypto: CryptoApi;
228
228
  readonly org: OrgApi;
229
229
  readonly limits: LimitsApi;
230
+ readonly processes: ProcessesApi;
231
+ readonly agents: AgentsApi;
230
232
  }
231
233
 
232
234
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -263,10 +265,11 @@ once per record. Keep `fields` short, and read related data for the whole list w
263
265
  one `records.getMany` call rather than one read per record.
264
266
 
265
267
  `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
266
- `crypto`, `org`, and `limits` are the same APIs that scripts receive; a before-change trigger has
267
- smaller budgets (see [Execution limits](overview.md#execution-limits)). A trigger context has no `input`,
268
- `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
269
- before-change trigger. `trigger.operation` is
268
+ `crypto`, `org`, `limits`, `processes`, and `agents` are the same APIs that scripts receive; a
269
+ before-change trigger has smaller budgets (see [Execution limits](overview.md#execution-limits)). A trigger
270
+ context has no `input`, `request`, `response`, `state`, or `locks`; `push`, `notifications`, `email`,
271
+ `processes`, and `agents` are refused in a before-change trigger (see
272
+ [Processes and AI Agents](processes-and-agents.md)). `trigger.operation` is
270
273
  the operation of the current call, `trigger.id` identifies the trigger registration, and
271
274
  `trigger.changeId` identifies the record change that caused the call.
272
275
 
@@ -378,8 +381,8 @@ a request that only validates input without saving.
378
381
 
379
382
  - **Read-only.** A before-change trigger may read records and schema, but every
380
383
  record write, `fetch`, lock, state write, push message, notification, email (including
381
- `email.senders()`), `jobs.enqueue`, `secrets.get`, and every `crypto` operation with a
382
- `{ secret }` key is refused with
384
+ `email.senders()`), `jobs.enqueue`, `secrets.get`, every `processes` and `agents` call, and
385
+ every `crypto` operation with a `{ secret }` key is refused with
383
386
  `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
384
387
  applies to every identity, including `data.asSystem()`. Every `crypto` operation
385
388
  with a key given in the call remains available, as do `crypto.sha256`,
@@ -6,7 +6,8 @@ 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`, `org`, and `limits`, awaits the handler, and
9
+ `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, `limits`, `processes`, and `agents`,
10
+ awaits the handler, and
10
11
  serializes its result.
11
12
 
12
13
  ```typescript
@@ -45,6 +46,8 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
45
46
  readonly crypto: CryptoApi;
46
47
  readonly org: OrgApi;
47
48
  readonly limits: LimitsApi;
49
+ readonly processes: ProcessesApi;
50
+ readonly agents: AgentsApi;
48
51
  }
49
52
  ```
50
53
 
@@ -55,9 +58,10 @@ Returning `null` produces a null handler result; returning `undefined` is invali
55
58
  ## HTTP routers and request context
56
59
 
57
60
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
58
- `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, and `limits` to
59
- both script and route handlers. `limits` reads the budgets of the execution (see
60
- [Reading limits in code](overview.md#reading-limits-in-code)). `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`
61
65
  preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
62
66
  metadata and transport/authentication fields removed by Cogover.
63
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
 
@@ -555,7 +556,8 @@ router.post("/recalculate", async ({ jobs, response }) => {
555
556
 
556
557
  - A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
557
558
  to `enqueue` (or `null`), and the same `data`, `schema`, `log`, `state`, `locks`,
558
- `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.
559
561
  Its return value is ignored.
560
562
  - A run enqueued from a route or trigger acts as the user of that call. A scheduled
561
563
  run has no user: `data.object()` works only when the identity policy allows the
@@ -577,6 +579,152 @@ router.post("/recalculate", async ({ jobs, response }) => {
577
579
  See the [background job reference](api-reference/background-jobs.md#background-jobs) for every
578
580
  option and rule.
579
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
+ - To let an agent write to a person on its own, add
715
+ `deliverTo: { personnelId, conversation: "new" | "latest" }` to `agents.start`. The agent
716
+ can then send a chat message to that personnel in the AI chat of the agent, and the run
717
+ reports the outcome as `delivery` (`SENT`, `NOT_SENT`, `BLOCKED`, or `FAILED`) in
718
+ `agents.get` and in the `onResult` job. The recipient must be allowed to use the agent
719
+ and have an AI Agent seat; otherwise `start` throws `CogoverApiError` with a
720
+ `RECIPIENT_...` code.
721
+ - With Cogover Dev CLI, starts are real, and so is a message sent through `deliverTo`,
722
+ but `onComplete` and `onResult` are refused with `NOT_SUPPORTED`; test the job after
723
+ publishing.
724
+
725
+ See the [Process and AI Agent reference](api-reference/processes-and-agents.md#processes-and-ai-agents)
726
+ for every option, limit, and error.
727
+
580
728
  ## Send notifications and email
581
729
 
582
730
  `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.14.0",
3
+ "version": "0.16.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,