@cogover/sdk 0.14.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.
@@ -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,144 @@ 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
+ - 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
+
580
720
  ## Send notifications and email
581
721
 
582
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.14.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,