@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
@@ -22,8 +22,10 @@ The reference is split into the following pages. Each page covers one area of th
22
22
  | [Push messages](push-messages.md) | Push messages |
23
23
  | [Notifications and email](notifications-and-email.md) | Notifications; Email |
24
24
  | [Organization structure](organization-structure.md) | Organization structure |
25
+ | [Custom Module Actions](actions.md) | Custom Module Actions; Schema builder |
26
+ | [Processes and AI Agents](processes-and-agents.md) | Processes and AI Agents |
25
27
 
26
- The sections below apply to every area: the errors every API can throw, the limits of one execution, and the compatibility helper.
28
+ The sections below apply to every area: the errors every API can throw, the limits of one execution, reading those limits in code, and the compatibility helper.
27
29
 
28
30
  ## Errors
29
31
 
@@ -81,8 +83,10 @@ remains in `error.message`.
81
83
 
82
84
  `RetryableError` (`code: "RETRYABLE"`) reports a temporary failure. The SDK throws it
83
85
  for a record write that a before-change trigger could not check (`details.reason`
84
- `"TRIGGER_FAILED"`, see [Record triggers](record-triggers.md#validating-and-changing-records)),
85
- and project code throws it itself. An after-change trigger handler or a job handler
86
+ `"TRIGGER_FAILED"`, see [Record triggers](record-triggers.md#validating-and-changing-records))
87
+ and for a Process or AI Agent start that failed temporarily (see
88
+ [Processes and AI Agents](processes-and-agents.md#idempotency-and-retries)), and project code
89
+ throws it itself. An after-change trigger handler or a job handler
86
90
  throws it to report a temporary failure, and Cogover runs the handler again later (see
87
91
  [After-change execution rules](record-triggers.md#after-change-execution-rules) and
88
92
  [Job execution rules](background-jobs.md#job-execution-rules)). Anywhere else it has no special
@@ -110,6 +114,21 @@ the feature is switched off, and with `CogoverApiError` whose `code` is
110
114
  still sending. A sender mailbox that the Project policy does not allow is reported
111
115
  as `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`.
112
116
 
117
+ `processes` and `agents` fail with `ValidationError`, `NotFoundError`,
118
+ `PermissionDeniedError`, `RateLimitError`, or `RetryableError` as described in
119
+ [Processes and AI Agents](processes-and-agents.md#errors). A Process or agent that the
120
+ Project policy does not allow is reported as `PermissionDeniedError` with
121
+ `details.reason` `"PROCESSES_NOT_ALLOWED"` or `"AGENTS_NOT_ALLOWED"`, and an
122
+ `approvalPolicy: "autoApprove"` it does not allow with `"AGENT_AUTO_APPROVE_NOT_ALLOWED"`.
123
+ They also fail with `CogoverApiError` whose `code` is `MAX_HOP_EXCEEDED` when the
124
+ automation budget is used up, `IDEMPOTENCY_CONFLICT` when another identity of the
125
+ project already used the `idempotencyKey`, `AGENT_DEPTH_EXCEEDED` when AI Agents would
126
+ start one another too deeply,
127
+ `NOT_SUPPORTED` for `onComplete` or `onResult` in a local development session, and
128
+ `PROCESSES_DISABLED` or `AGENTS_DISABLED` when the feature is not available. A Process
129
+ node or an AI Agent that calls a Custom Module Action receives the errors described in
130
+ [Errors seen by the caller](actions.md#errors-seen-by-the-caller).
131
+
113
132
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
114
133
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
115
134
  the original code or message. A script's returned JSON remains its own response
@@ -160,8 +179,8 @@ Raw error messages, stack traces and arbitrary details are not returned.
160
179
  `writesMayHaveCompleted` is true if the execution sent any call that can change
161
180
  something outside it, even if a later operation failed: a record write, `state.set` or
162
181
  `state.delete`, any `locks` call (including an `acquire` that returned `null`), a push
163
- message, `notifications.send`, `email.send`, or a `fetch` whose method is not `GET` or
164
- `HEAD`. A `LockUnavailableError` that escapes a script therefore always reports `true`.
182
+ message, `notifications.send`, `email.send`, `jobs.enqueue`, `processes.start`,
183
+ `agents.start`, or a `fetch` whose method is not `GET` or `HEAD`. A `LockUnavailableError` that escapes a script therefore always reports `true`.
165
184
  It is a conservative warning, not confirmation of a successful write.
166
185
  Unknown errors and resource-limit failures retain the generic HTTP 422 response.
167
186
  These responses do not roll back earlier writes; do not retry writes automatically.
@@ -171,16 +190,42 @@ These responses do not roll back earlier writes; do not retry writes automatical
171
190
  Every execution runs within platform limits. These are the default values; they are
172
191
  set by the platform and may differ between environments.
173
192
 
174
- - An HTTP route and a record trigger may make at most 20 capability calls. Every call
175
- to `data`, `schema`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`,
176
- `secrets`, `crypto`, `org`, or `fetch` counts once. A background job may make 200.
177
- The call over the budget, and every call after it, throws `RateLimitError`
178
- (`details.limit` is the budget) without being sent, so a script can catch it.
193
+ | Budget of one execution | HTTP route | Before-change trigger | After-change trigger | Background job |
194
+ |---|---|---|---|---|
195
+ | Capability calls (`capabilityCalls`) | 100 | 20 | 100 | 1,000 |
196
+ | Local calls (`localCalls`) | 200 | 50 | 200 | 1,000 |
197
+ | Records read (`recordsRead`) | 10,000 | 4,000 | 10,000 | 50,000 |
198
+ | Records written (`recordsWritten`) | 10,000 | — | 10,000 | 50,000 |
199
+
200
+ - **Capability calls.** Every call to `data`, `schema`, `state`, `locks`, `push`,
201
+ `notifications`, `email`, `jobs`, `secrets`, `fetch`, `processes`, or `agents`, and
202
+ every `org` read with `withDisplay: true`, counts once.
203
+ - **Local calls.** `crypto` calls and `org` reads without `withDisplay` are handled by
204
+ Cogover itself, so they count against their own budget instead. A `crypto` key given as
205
+ `{ secret: name }` is still a secret read (see its quota below).
206
+ - **Records read.** The records returned by `records.get`, `records.getMany`, and
207
+ `records.list`, and the linked records that `expandLookups` reads. A read is refused
208
+ before it is sent when it could go over the budget: `records.get` counts 1,
209
+ `records.getMany` the number of IDs, and `records.list` its `limit` (20 by default).
210
+ `records.aggregate` returns no records and does not count.
211
+ - **Records written.** 1 for `create`, `update`, and `upsertByUniqueField`, the number of
212
+ records for `batchInsert` and `batchUpdate`, and the number of IDs for `deleteMany`,
213
+ counted when the call is sent. A before-change trigger cannot write records.
214
+ - A call that would go over a budget, and every later call against that budget, throws
215
+ `RateLimitError` without being sent, so a script can catch it. `details.budget` names
216
+ the budget, `details.limit` is its size, `details.used` is what the execution had used,
217
+ and for records `details.requested` is what the call asked for. Waiting does not help:
218
+ the budget belongs to the execution. Read fewer records, use `records.aggregate` for
219
+ totals, or move the work to a background job. An execution that keeps calling after
220
+ 1,000 refused calls is ended with `code: "RATE_LIMITED"`; the script cannot catch that.
179
221
  - An HTTP route has 8 seconds of wall-clock time, counted from when its handler
180
222
  starts, including the time spent waiting for capability calls, a lock, or a remote
181
223
  server. A record trigger has its own `timeoutMs`, and a background job its
182
- `timeoutMs`. Exceeding the time ends the whole execution: the script cannot catch it,
183
- and an HTTP route returns the generic HTTP 422 response.
224
+ `timeoutMs`. A Custom Module Action has the budgets of an HTTP route and its own
225
+ `timeoutMs`, at most 8 seconds. Exceeding the time ends the whole execution: the script cannot catch it,
226
+ and an HTTP route returns the generic HTTP 422 response. Capability calls of one
227
+ execution run one after another, also when they are started together with
228
+ `Promise.all`.
184
229
  - A single capability request, JSON-encoded with its arguments, must not exceed
185
230
  262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
186
231
  or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
@@ -190,10 +235,74 @@ set by the platform and may differ between environments.
190
235
  operation itself did run, so a write may have completed.
191
236
  - When the Workspace already has too many executions waiting, a new HTTP call is
192
237
  refused with HTTP 429 and `code: "RATE_LIMITED"` before anything runs; retry it later.
238
+ This refusal has no `details.budget`.
239
+
240
+ Some APIs also keep their own quota per execution, such as 20 `fetch` calls, 20
241
+ secret reads, 20 `processes.start` calls, or 5 `agents.start` calls. Going over one is
242
+ reported as `RateLimitError` too.
243
+
244
+ ## Reading limits in code
245
+
246
+ ```typescript
247
+ const limits: LimitsApi;
248
+
249
+ interface LimitsApi {
250
+ usage(): LimitUsage;
251
+ }
252
+
253
+ interface LimitUsage {
254
+ readonly capabilityCalls: LimitCounter;
255
+ readonly localCalls: LimitCounter;
256
+ readonly recordsRead: LimitCounter;
257
+ readonly recordsWritten: LimitCounter;
258
+ readonly elapsedMs: number;
259
+ readonly timeLimitMs: number;
260
+ }
261
+
262
+ interface LimitCounter {
263
+ readonly used: number;
264
+ readonly limit: number;
265
+ readonly remaining: number;
266
+ }
267
+ ```
268
+
269
+ `limits` is exported by the package and is also the `limits` member of the context of
270
+ a script, a route, a record trigger, a background job, and a Custom Module Action. `limits.usage()` returns the
271
+ budgets of the current execution as of its last Cogover call: reading them is not a
272
+ capability call. `remaining` is `limit - used` and never below 0. `elapsedMs` is the
273
+ time since the handler started, as of that last call, and `timeLimitMs` is the
274
+ wall-clock time the execution may take. Called outside a handler, for example while the
275
+ module loads or in a test that runs outside Cogover, `usage()` throws `CogoverApiError`
276
+ with `code: "CAPABILITY_UNAVAILABLE"`.
277
+
278
+ When code runs locally with Cogover Dev CLI, each handler gets the budgets of its kind of
279
+ execution and the same refusals; linked records read by `expandLookups` are not counted
280
+ there.
281
+
282
+ ```typescript
283
+ import { defineScript } from "@cogover/sdk";
284
+
285
+ export default defineScript(async ({ data, jobs, limits }) => {
286
+ const orders = data.object("order");
287
+ let cursor: string | undefined;
288
+ let total = 0;
289
+ do {
290
+ const page = await orders.records.list({ fields: ["amount"], limit: 200, cursor });
291
+ for (const order of page.items) total += Number(order.fields.amount ?? 0);
292
+ cursor = page.nextCursor;
293
+ const usage = limits.usage();
294
+ if (cursor !== undefined && (usage.recordsRead.remaining < 200 || usage.capabilityCalls.remaining < 2)) {
295
+ // Hand the rest to a background job, which has larger budgets.
296
+ await jobs.enqueue("sum_orders", { cursor, total });
297
+ return { total, complete: false };
298
+ }
299
+ } while (cursor !== undefined);
300
+ return { total, complete: true };
301
+ });
302
+ ```
193
303
 
194
- When an API has its own per-execution quota that is not below the call budget, such
195
- as 20 `fetch` calls or 20 secret reads, the call budget is reached first in a route
196
- or a trigger; both are reported as `RateLimitError`.
304
+ For a total like this one, `records.aggregate` is one capability call and reads no
305
+ records; page through records only when the result cannot be expressed as an aggregate.
197
306
 
198
307
  ## Compatibility helper
199
308
 
@@ -0,0 +1,357 @@
1
+ # `@cogover/sdk` API reference: Processes and AI Agents
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Processes and AI Agents
6
+
7
+ `processes` starts Cogover Processes and `agents` starts AI Agent runs from project
8
+ code. Both are members of the context of scripts and routes, after-change triggers,
9
+ background jobs, and [Custom Module Actions](actions.md). A before-change trigger is
10
+ refused with `PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`).
11
+
12
+ Both run in the background. `start` returns as soon as the Process instance or the
13
+ agent run is created, never after it finishes. To act on the outcome, name a
14
+ background job of the project in `onComplete` or `onResult`: Cogover enqueues it when
15
+ the instance or run ends. `get` reads the current state of an instance or run that the
16
+ project started.
17
+
18
+ This example assumes that `workspace.d.ts` declares the `lead` Object and the field
19
+ used below.
20
+
21
+ ```typescript
22
+ import { defineJob, defineScript } from "@cogover/sdk";
23
+ import type { CogoverRecordId, ProcessCompletionJobPayload } from "@cogover/sdk";
24
+
25
+ export default defineScript(async ({ input, processes }) => {
26
+ const { leadId } = input as { leadId: string };
27
+ const { instanceId, duplicate } = await processes.start("PIXXXXXXXXXXXX", {
28
+ input: { lead_id: leadId },
29
+ instanceName: `Approve discount ${leadId}`,
30
+ idempotencyKey: `discount:${leadId}`,
31
+ onComplete: { job: "after_approval", payload: { leadId } },
32
+ });
33
+ return { instanceId, duplicate };
34
+ });
35
+
36
+ export const jobs = [
37
+ // The job's payload is JSON: the ID sent in onComplete.payload comes back as a string.
38
+ defineJob<ProcessCompletionJobPayload<{ leadId: CogoverRecordId }>>({ key: "after_approval" }, async ({ payload, data }) => {
39
+ if (payload?.payload == null || payload.process.state !== "COMPLETED") return;
40
+ const approved = payload.process.output?.approved === true;
41
+ await data.object("lead").records.update(payload.payload.leadId, { discount_approved: approved });
42
+ }),
43
+ ];
44
+ ```
45
+
46
+ ### Permissions
47
+
48
+ The project's identity policy decides which Processes and AI Agents the project may
49
+ use; a Workspace administrator approves it like the rest of the policy. Without a
50
+ `processes` section, every `processes` call throws `PermissionDeniedError` with
51
+ `details.reason` `"PROCESSES_NOT_ALLOWED"`; without an `agents` section, every `agents`
52
+ call throws it with `"AGENTS_NOT_ALLOWED"`.
53
+
54
+ ```json
55
+ {
56
+ "processes": {
57
+ "processes": { "mode": "ONLY", "processInfoIds": ["PIXXXXXXXXXXXX"] },
58
+ "allowSystem": false
59
+ },
60
+ "agents": {
61
+ "agents": { "mode": "ALL", "agentIds": [] },
62
+ "allowSystem": false,
63
+ "maxRunsPerDay": 200,
64
+ "allowAutoApprove": false
65
+ }
66
+ }
67
+ ```
68
+
69
+ | Field | Meaning |
70
+ |---|---|
71
+ | `processes.processes` | Which Processes `processes.start` may start: `mode` `ALL`, `ALL_EXCEPT`, or `ONLY`, and the Process IDs in `processInfoIds`. |
72
+ | `processes.allowSystem` | Allows executions without a user to start the selected Processes. Defaults to `false`. |
73
+ | `agents.agents` | Which AI Agents `agents.start` may run: `mode` and the agent IDs in `agentIds`. |
74
+ | `agents.allowSystem` | Allows executions without a user to run the selected agents, which then use their own identity. Defaults to `false`. |
75
+ | `agents.maxRunsPerDay` | Maximum `agents.start` calls of the project per UTC day, 1 to 10000. Defaults to `200`. |
76
+ | `agents.allowAutoApprove` | Allows `agents.start` with `approvalPolicy: "autoApprove"`. Defaults to `false`; an execution without a user can never use it. |
77
+
78
+ - An execution with a user starts the Process or runs the agent as that user, and
79
+ Cogover still checks that the user may start that Process or run that agent; a
80
+ refusal throws `PermissionDeniedError` with `details.reason` `"PROCESS_START_DENIED"`
81
+ or `"AGENT_RUN_DENIED"`. A user without a Workspace account cannot start a Process.
82
+ - An execution without a user, such as a scheduled job or an inbound webhook call,
83
+ needs `allowSystem: true` in the section. A Process started this way has no starter.
84
+ - `get` needs the section too, but not the selection: it reads only instances and runs
85
+ that the project itself started.
86
+
87
+ ### `processes.start(processInfoId, options?): Promise<ProcessStartResult>`
88
+
89
+ ```typescript
90
+ interface ProcessesApi {
91
+ start(processInfoId: string, options?: ProcessStartOptions): Promise<ProcessStartResult>;
92
+ get(instanceId: string): Promise<ProcessInstanceState>;
93
+ }
94
+
95
+ interface ProcessStartOptions {
96
+ readonly input?: Record<string, unknown>;
97
+ readonly instanceName?: string;
98
+ readonly idempotencyKey?: string;
99
+ readonly onComplete?: ProcessCompletion;
100
+ }
101
+
102
+ interface ProcessCompletion {
103
+ readonly job: string;
104
+ readonly payload?: unknown;
105
+ }
106
+
107
+ interface ProcessStartResult {
108
+ readonly instanceId: string;
109
+ readonly duplicate: boolean;
110
+ }
111
+ ```
112
+
113
+ `processInfoId` is the ID of a Process, the ID that the identity policy lists, not of
114
+ one of its versions or runs: 1 to 64 letters, digits, `_`, or `-`. Cogover starts the
115
+ activated, published version of that Process, which must be a Normal flow Process.
116
+
117
+ | Option | Rules and meaning |
118
+ |---|---|
119
+ | `input` | JSON object of at most 65,536 UTF-8 bytes: the values of the Process variables marked as input, by variable name. |
120
+ | `instanceName` | Name of the new instance, 1 to 255 characters. |
121
+ | `idempotencyKey` | Starts with a letter or digit and contains at most 200 letters, digits, `.`, `_`, `:`, or `-`. See [Idempotency and retries](#idempotency-and-retries). |
122
+ | `onComplete` | `job` is the key of a job declared by the active version; `payload` is an optional JSON value of at most 8,192 UTF-8 bytes handed to that job. |
123
+
124
+ The result is the `instanceId` of the new instance, and `duplicate: true` when an
125
+ earlier start with the same `idempotencyKey` returned that instance instead. Invalid
126
+ arguments throw `ValidationError` before anything is sent.
127
+
128
+ ### `processes.get(instanceId): Promise<ProcessInstanceState>`
129
+
130
+ ```typescript
131
+ interface ProcessInstanceState {
132
+ readonly instanceId: string;
133
+ readonly processId: string;
134
+ readonly processInfoId: string;
135
+ readonly state: string;
136
+ readonly startedAt: number | null;
137
+ readonly finishedAt: number | null;
138
+ }
139
+ ```
140
+
141
+ `state` is `NOT_STARTED`, `RUNNING`, `PAUSED`, `COMPLETED`, `FAILED` (the run stopped
142
+ on an error), `CANCELED`, or `DELETED`. `startedAt` and `finishedAt` are Unix
143
+ milliseconds, or `null` before the instance starts and while it runs. An instance
144
+ that this project did not start throws `NotFoundError`.
145
+
146
+ ### Process completion job
147
+
148
+ ```typescript
149
+ interface ProcessCompletionJobPayload<TPayload = unknown> {
150
+ readonly payload: TPayload | null;
151
+ readonly process: {
152
+ readonly instanceId: string;
153
+ readonly processId: string;
154
+ readonly processInfoId: string;
155
+ readonly state: "COMPLETED" | "CANCELED" | "DELETED" | "FAILED";
156
+ readonly output: Record<string, unknown> | null;
157
+ readonly finishedAt: number | null;
158
+ };
159
+ }
160
+ ```
161
+
162
+ When an instance started with `onComplete` ends, Cogover enqueues one run of the job
163
+ with this value as its `payload`: `payload` is `onComplete.payload` (or `null`), and
164
+ `process.output` holds the values of the Process variables marked as output, or `null`
165
+ when there are none or they take more than 48 KiB. See
166
+ [Completion jobs](#completion-jobs) for how the job runs.
167
+
168
+ ### `agents.start(agentId, options): Promise<AgentStartResult>`
169
+
170
+ ```typescript
171
+ interface AgentsApi {
172
+ start(agentId: string, options: AgentStartOptions): Promise<AgentStartResult>;
173
+ get<TResult = unknown>(runId: string): Promise<AgentRunState<TResult>>;
174
+ }
175
+
176
+ interface AgentStartOptions {
177
+ readonly instruction: string;
178
+ readonly variables?: Readonly<Record<string, string | number | boolean>>;
179
+ readonly records?: readonly AgentRecordReference[];
180
+ readonly resultSchema?: ObjectSchema<ObjectShape, false>;
181
+ readonly runAs?: "caller" | "agent";
182
+ readonly approvalPolicy?: "deny" | "autoApprove";
183
+ readonly timeoutSeconds?: number;
184
+ readonly idempotencyKey?: string;
185
+ readonly onResult?: AgentResultCompletion;
186
+ }
187
+
188
+ interface AgentRecordReference {
189
+ readonly objectSlug: string;
190
+ readonly recordId: string;
191
+ readonly withActivities?: boolean;
192
+ }
193
+
194
+ interface AgentResultCompletion {
195
+ readonly job: string;
196
+ readonly payload?: unknown;
197
+ }
198
+
199
+ interface AgentStartResult {
200
+ readonly runId: string;
201
+ readonly duplicate: boolean;
202
+ }
203
+ ```
204
+
205
+ ```typescript
206
+ const { runId } = await agents.start("AGXXXXXXXXXXXX", {
207
+ instruction: "Classify this email as a sales or a support request.",
208
+ variables: { subject: message.subject, body: message.body },
209
+ records: [{ objectSlug: "lead", recordId: leadId, withActivities: true }],
210
+ resultSchema: s.object({ category: s.enum(["sales", "support"]) }),
211
+ idempotencyKey: `classify:${message.id}`,
212
+ onResult: { job: "save_classification", payload: { messageId: message.id } },
213
+ });
214
+ ```
215
+
216
+ `agentId` is the ID of an AI Agent: 1 to 64 letters, digits, `_`, or `-`. Each run
217
+ starts a new conversation of the agent.
218
+
219
+ | Option | Rules and meaning |
220
+ |---|---|
221
+ | `instruction` | Required. What the agent must do, 1 to 20,000 characters, not blank. |
222
+ | `variables` | At most 50 named values the agent can use; names start with a letter and contain at most 64 letters, digits, or `_`; a value is a string of at most 4,000 characters, a finite number, or a boolean. |
223
+ | `records` | At most 20 records the agent reads as context. `objectSlug` is an Object slug, `recordId` has 1 to 128 letters, digits, `_`, or `-`, and `withActivities: true` also gives the agent the record's activities. |
224
+ | `resultSchema` | Shape of a structured result, created with `s.object` (see [Schema builder](actions.md#schema-builder-s)). The agent must return a result that matches it; otherwise the run fails. |
225
+ | `runAs` | `"caller"` (default): the agent acts as the user of this execution. `"agent"`: the agent uses its own identity, which it must have. An execution without a user must use `"agent"`. |
226
+ | `approvalPolicy` | `"deny"` (default): a tool that needs a person's approval is not run, and the agent is told so. `"autoApprove"`: such tools run without approval; it needs `allowAutoApprove: true` in the identity policy and an execution with a user, otherwise `start` throws `PermissionDeniedError` with `details.reason` `"AGENT_AUTO_APPROVE_NOT_ALLOWED"`. |
227
+ | `timeoutSeconds` | Integer from 10 through 1800; defaults to `300`. Time limit of the run. |
228
+ | `idempotencyKey` | Same rules as for `processes.start`. |
229
+ | `onResult` | `job` is the key of a job declared by the active version; `payload` is an optional JSON value of at most 8,192 UTF-8 bytes handed to that job. |
230
+
231
+ The result is the `runId` of the new run, and `duplicate: true` when an earlier start
232
+ with the same `idempotencyKey` returned that run instead. Invalid arguments throw
233
+ `ValidationError` before anything is sent.
234
+
235
+ ### `agents.get(runId): Promise<AgentRunState>`
236
+
237
+ ```typescript
238
+ interface AgentRunState<TResult = unknown> {
239
+ readonly runId: string;
240
+ readonly status: string;
241
+ readonly text: string | null;
242
+ readonly result: TResult | null;
243
+ readonly error: { readonly code: string; readonly message: string } | null;
244
+ }
245
+ ```
246
+
247
+ `status` is `QUEUED` or `RUNNING` while the run is in progress, then a final status
248
+ such as `COMPLETED`, `FAILED`, `TIMEOUT`, or `CANCELLED`. `text` is the agent's answer
249
+ (at most 32 KiB), `result` the structured result that matches `resultSchema`, and
250
+ `error` the reason of a failed run; each is `null` when absent. `error.code` is one of
251
+ `RESULT_SCHEMA_MISMATCH`, `TIMEOUT`, `CALLER_TIMEOUT`, `CANCELLED`, `MAX_TURNS`,
252
+ `GUARDRAIL_REJECTED`, `APPROVAL_DENIED`, `SERVER_RESTARTED`, `SESSION_BUSY`,
253
+ `SESSION_EVICTED`, `AGENT_INACTIVE`, `AGENT_ACCESS_DENIED`, `AGENT_CONFIG_INVALID`,
254
+ `CONFIG_LOAD_FAILED`, `LLM_HTTP_ERROR`, `LLM_NETWORK`, `LLM_RESPONSE_FAILED`, `LLM_PARSE`,
255
+ `OUTPUT_TRUNCATED`, `INTERNAL_ERROR`, or `AGENT_ERROR` for any other reason, and
256
+ `error.message` is a fixed English description of that code: the text of the AI model
257
+ provider is never passed on. The `onResult` job receives the same `error`. A run that
258
+ this project did not start throws `NotFoundError`.
259
+
260
+ ### Agent result job
261
+
262
+ ```typescript
263
+ interface AgentResultJobPayload<TPayload = unknown, TResult = unknown> {
264
+ readonly payload: TPayload | null;
265
+ readonly agentRun: {
266
+ readonly runId: string;
267
+ readonly status: string;
268
+ readonly text: string | null;
269
+ readonly result: TResult | null;
270
+ readonly error: { readonly code: string; readonly message: string } | null;
271
+ readonly usage: Record<string, unknown> | null;
272
+ };
273
+ }
274
+ ```
275
+
276
+ When a run started with `onResult` ends, Cogover enqueues one run of the job with this
277
+ value as its `payload`: `payload` is `onResult.payload` (or `null`), `agentRun.text` is
278
+ cut to 32 KiB, `agentRun.result` is `null` when it takes more than 16 KiB, and
279
+ `agentRun.usage` reports `inputTokens`, `outputTokens`, `iterations`, and `durationMs`.
280
+
281
+ ### Completion jobs
282
+
283
+ - The job named by `onComplete` or `onResult` runs like any enqueued job (see
284
+ [Job execution rules](background-jobs.md#job-execution-rules)): `job.source` is
285
+ `"enqueue"`, it is delivered at least once, and it retries on `RetryableError`. The run
286
+ history lists it with `enqueuedBy` `process:<instanceId>` or `agent:<runId>`.
287
+ - It runs as the user of the execution that called `start` (or without a user when that
288
+ execution had none). It gets two steps less of the automation budget than that
289
+ execution had (one for reaching the Process or agent, one for coming back), and it
290
+ continues that execution's chain of jobs, so a job whose Process or agent ends by
291
+ starting the same job again stops like a job that enqueues itself. When no step would
292
+ be left, or the chain is too long, the outcome is not delivered.
293
+ - The job must be declared by the active version when `start` is called; otherwise
294
+ `start` throws `ValidationError`. If the active version no longer declares it when the
295
+ instance or run ends, or the project already has 10,000 job runs waiting, the outcome
296
+ is not delivered.
297
+
298
+ ### Idempotency and retries
299
+
300
+ - Without `idempotencyKey`, every `start` creates a new instance or run.
301
+ - With one, a second `start` with the same key in the same project returns the first
302
+ instance or run with `duplicate: true`. Cogover keeps the key while the instance or run
303
+ is active and for 7 days after it ends. Using the key again for another Process or
304
+ agent throws `ValidationError`. The key belongs to the identity that used it first:
305
+ another user of the project, or an execution without a user, that sends the same key
306
+ receives `CogoverApiError` with `code: "IDEMPOTENCY_CONFLICT"`, never the other
307
+ identity's instance or run. Include the user in keys that users may share.
308
+ - `RetryableError` reports a temporary failure. When `details.writesMayHaveCompleted` is
309
+ `false`, nothing was started. When it is `true`, the instance or run may have been
310
+ created: retry later with the same `idempotencyKey`, and Cogover completes that start
311
+ instead of creating a second one; a retry that comes too soon may throw
312
+ `RetryableError` again. After a definite refusal, such as `ValidationError` or
313
+ `PermissionDeniedError`, the key can be used again.
314
+ - In a job, a key derived from the job's `payload` or `job.id`, and in an action from
315
+ `action.runId`, keeps a retried handler from starting the same work twice.
316
+
317
+ ### Limits
318
+
319
+ - Every `processes` and `agents` call is one capability call (see
320
+ [Execution limits](overview.md#execution-limits)).
321
+ - One execution may call `processes.start` at most 20 times and `agents.start` at most
322
+ 5 times. Going over throws `RateLimitError` without `details.budget`.
323
+ - `agents.start` also counts against `maxRunsPerDay` of the identity policy, and the AI
324
+ Agent service may apply its own quota; both throw `RateLimitError`. A project may also
325
+ start at most 1,000 Processes per UTC day. A start that the Process or AI Agent service
326
+ refuses does not count.
327
+ - Starting a Process or an AI Agent run uses one step of the automation budget that also
328
+ limits chains of record triggers. When no step would be left, `start` throws
329
+ `CogoverApiError` with `code: "MAX_HOP_EXCEEDED"`.
330
+ - AI Agents that start one another, through actions or completion jobs, may go at most
331
+ 3 levels deep; one level deeper, `agents.start` throws `CogoverApiError` with
332
+ `code: "AGENT_DEPTH_EXCEEDED"`.
333
+ - A `"read"` action and a read-only local development session can call `get` but not
334
+ `start`: `start` throws `PermissionDeniedError`.
335
+
336
+ ### Errors
337
+
338
+ | Error | `code` | When |
339
+ |---|---|---|
340
+ | `ValidationError` | `VALIDATION_ERROR` | An invalid argument; an `onComplete` or `onResult` job the active version does not declare; an `idempotencyKey` already used for another Process or agent; or a start the Process or AI Agent service rejected, such as an unknown input variable (`details.upstreamCode` names its reason). |
341
+ | `NotFoundError` | `NOT_FOUND` | The Process does not exist or is not active, the agent does not exist, or `get` names an instance or run this project did not start. |
342
+ | `PermissionDeniedError` | `PERMISSION_DENIED` | `details.reason` is `PROCESSES_NOT_ALLOWED`, `AGENTS_NOT_ALLOWED` or `AGENT_AUTO_APPROVE_NOT_ALLOWED` (identity policy), `PROCESS_START_DENIED` or `AGENT_RUN_DENIED` (the user may not start it), or `TRIGGER_READ_ONLY` (before-change trigger); or the execution is read-only. |
343
+ | `RateLimitError` | `RATE_LIMITED` | A per-execution limit, `maxRunsPerDay`, the daily Process start limit, or a quota of the AI Agent service. |
344
+ | `RetryableError` | `RETRYABLE` | A temporary failure; see [Idempotency and retries](#idempotency-and-retries). |
345
+ | `CogoverApiError` | `MAX_HOP_EXCEEDED` | The automation budget is used up. |
346
+ | `CogoverApiError` | `IDEMPOTENCY_CONFLICT` | Another identity of the project already used this `idempotencyKey`. |
347
+ | `CogoverApiError` | `AGENT_DEPTH_EXCEEDED` | AI Agents would call one another more than 3 levels deep. |
348
+ | `CogoverApiError` | `NOT_SUPPORTED` | `onComplete` or `onResult` in a local development session. |
349
+ | `CogoverApiError` | `PROCESSES_DISABLED`, `AGENTS_DISABLED` | The feature is not available in this environment. |
350
+
351
+ ### Local development
352
+
353
+ When code runs locally with Cogover Dev CLI, `start` creates real Process instances and
354
+ agent runs, as the user of the Project key, and a read-only session refuses it.
355
+ `onComplete` and `onResult` are refused with `CogoverApiError` `code: "NOT_SUPPORTED"`,
356
+ because their job runs only in a published version: test the start without them and
357
+ read the outcome with `get`, then publish the project to test the job.
@@ -226,6 +226,9 @@ interface TriggerContext<
226
226
  readonly secrets: SecretsApi;
227
227
  readonly crypto: CryptoApi;
228
228
  readonly org: OrgApi;
229
+ readonly limits: LimitsApi;
230
+ readonly processes: ProcessesApi;
231
+ readonly agents: AgentsApi;
229
232
  }
230
233
 
231
234
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -262,9 +265,11 @@ once per record. Keep `fields` short, and read related data for the whole list w
262
265
  one `records.getMany` call rather than one read per record.
263
266
 
264
267
  `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
265
- `crypto`, and `org` are the same APIs that scripts receive. A trigger context has no `input`,
266
- `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
267
- 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
268
273
  the operation of the current call, `trigger.id` identifies the trigger registration, and
269
274
  `trigger.changeId` identifies the record change that caused the call.
270
275
 
@@ -376,8 +381,8 @@ a request that only validates input without saving.
376
381
 
377
382
  - **Read-only.** A before-change trigger may read records and schema, but every
378
383
  record write, `fetch`, lock, state write, push message, notification, email (including
379
- `email.senders()`), `jobs.enqueue`, `secrets.get`, and every `crypto` operation with a
380
- `{ 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
381
386
  `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
382
387
  applies to every identity, including `data.asSystem()`. Every `crypto` operation
383
388
  with a key given in the call remains available, as do `crypto.sha256`,