@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.
@@ -165,6 +165,8 @@ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspa
165
165
  readonly crypto: CryptoApi;
166
166
  readonly org: OrgApi;
167
167
  readonly limits: LimitsApi;
168
+ readonly processes: ProcessesApi;
169
+ readonly agents: AgentsApi;
168
170
  }
169
171
 
170
172
  interface JobInfo {
@@ -180,14 +182,15 @@ interface JobInfo {
180
182
 
181
183
  A handler may be synchronous or asynchronous; its return value is ignored. `data`,
182
184
  `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
183
- `secrets`, `crypto`, `org`, and `limits` are the same APIs that scripts receive; `limits`
184
- reports the larger budgets of a job (see [Execution limits](overview.md#execution-limits)).
185
+ `secrets`, `crypto`, `org`, `limits`, `processes`, and `agents` are the same APIs that scripts
186
+ receive; `limits` reports the larger budgets of a job (see [Execution limits](overview.md#execution-limits)).
185
187
  A job context has no `input`, `request`, `response`, or `push`.
186
188
 
187
189
  - `job.id` identifies the run and stays the same across its attempts; use it as the
188
190
  idempotency key of external calls. `job.attempt` starts at 1.
189
- - `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
190
- administrator and `"schedule"` for a run created by the job's schedule. `job.runAt`
191
+ - `job.source` is `"enqueue"` for a run created by `jobs.enqueue`, by an
192
+ administrator, or for the outcome of a Process or AI Agent, and `"schedule"` for a run
193
+ created by the job's schedule. `job.runAt`
191
194
  is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
192
195
  milliseconds, and `enqueuedAt` is absent for a scheduled run.
193
196
  - `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
@@ -231,8 +234,9 @@ both. `idempotencyKey` starts with a letter or digit, contains letters, digits,
231
234
  with the same key while the earlier run is still kept returns that run with
232
235
  `duplicate: true` instead of creating another. Run history is kept for 7 days.
233
236
 
234
- `enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
235
- webhook calls. A before-change trigger is refused with `PermissionDeniedError`
237
+ `enqueue` works in scripts and routes, after-change triggers, jobs, inbound
238
+ webhook calls, and Custom Module Actions whose `effect` is `"write"`. A before-change
239
+ trigger is refused with `PermissionDeniedError`
236
240
  (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
237
241
  without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
238
242
  enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
@@ -257,8 +261,15 @@ not enabled for the Workspace, the error is
257
261
  `data.asUser()`; use `data.asSystem()` to group (see
258
262
  [Aggregates](records.md#aggregates)).
259
263
  - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
260
- `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
261
- within the runtime limits of the job lane.
264
+ `locks`, send notifications and email, enqueue jobs, read secrets, use `crypto`, and
265
+ start Processes and AI Agents, within the runtime limits of the job lane.
266
+ - **Outcome of a Process or AI Agent.** A run created by `onComplete` of
267
+ `processes.start` or `onResult` of `agents.start` receives a
268
+ `ProcessCompletionJobPayload` or an `AgentResultJobPayload` as its `payload`, runs as
269
+ the user of the execution that called `start`, and is listed in the run history with
270
+ `enqueuedBy` `process:<instanceId>` or `agent:<runId>` (see
271
+ [Completion jobs](processes-and-agents.md#completion-jobs)). A run enqueued from a
272
+ Custom Module Action runs as the identity of that action call.
262
273
  - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
263
274
  split: process one page, save the cursor, and enqueue the same job again with the
264
275
  cursor in the payload, as in the example above.
@@ -22,6 +22,8 @@ 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
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
 
@@ -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,24 @@ 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.
129
+ `agents.start` also fails with `CogoverApiError` whose `code` is `INSUFFICIENT_CREDITS`,
130
+ `AI_SUBSCRIPTION_REQUIRED`, `AI_SEAT_REQUIRED`, `AGENT_CREDIT_LIMIT_EXCEEDED`, or
131
+ `MODEL_NOT_PRICED` when the AI Agent service refuses the run for AI credit billing. A Process
132
+ node or an AI Agent that calls a Custom Module Action receives the errors described in
133
+ [Errors seen by the caller](actions.md#errors-seen-by-the-caller).
134
+
113
135
  Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
114
136
  error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
115
137
  the original code or message. A script's returned JSON remains its own response
@@ -160,8 +182,8 @@ Raw error messages, stack traces and arbitrary details are not returned.
160
182
  `writesMayHaveCompleted` is true if the execution sent any call that can change
161
183
  something outside it, even if a later operation failed: a record write, `state.set` or
162
184
  `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`.
185
+ message, `notifications.send`, `email.send`, `jobs.enqueue`, `processes.start`,
186
+ `agents.start`, or a `fetch` whose method is not `GET` or `HEAD`. A `LockUnavailableError` that escapes a script therefore always reports `true`.
165
187
  It is a conservative warning, not confirmation of a successful write.
166
188
  Unknown errors and resource-limit failures retain the generic HTTP 422 response.
167
189
  These responses do not roll back earlier writes; do not retry writes automatically.
@@ -179,8 +201,8 @@ set by the platform and may differ between environments.
179
201
  | Records written (`recordsWritten`) | 10,000 | — | 10,000 | 50,000 |
180
202
 
181
203
  - **Capability calls.** Every call to `data`, `schema`, `state`, `locks`, `push`,
182
- `notifications`, `email`, `jobs`, `secrets`, or `fetch`, and every `org` read with
183
- `withDisplay: true`, counts once.
204
+ `notifications`, `email`, `jobs`, `secrets`, `fetch`, `processes`, or `agents`, and
205
+ every `org` read with `withDisplay: true`, counts once.
184
206
  - **Local calls.** `crypto` calls and `org` reads without `withDisplay` are handled by
185
207
  Cogover itself, so they count against their own budget instead. A `crypto` key given as
186
208
  `{ secret: name }` is still a secret read (see its quota below).
@@ -202,7 +224,8 @@ set by the platform and may differ between environments.
202
224
  - An HTTP route has 8 seconds of wall-clock time, counted from when its handler
203
225
  starts, including the time spent waiting for capability calls, a lock, or a remote
204
226
  server. A record trigger has its own `timeoutMs`, and a background job its
205
- `timeoutMs`. Exceeding the time ends the whole execution: the script cannot catch it,
227
+ `timeoutMs`. A Custom Module Action has the budgets of an HTTP route and its own
228
+ `timeoutMs`, at most 8 seconds. Exceeding the time ends the whole execution: the script cannot catch it,
206
229
  and an HTTP route returns the generic HTTP 422 response. Capability calls of one
207
230
  execution run one after another, also when they are started together with
208
231
  `Promise.all`.
@@ -217,8 +240,9 @@ set by the platform and may differ between environments.
217
240
  refused with HTTP 429 and `code: "RATE_LIMITED"` before anything runs; retry it later.
218
241
  This refusal has no `details.budget`.
219
242
 
220
- Some APIs also keep their own quota per execution, such as 20 `fetch` calls or 20
221
- secret reads. Going over one is reported as `RateLimitError` too.
243
+ Some APIs also keep their own quota per execution, such as 20 `fetch` calls, 20
244
+ secret reads, 20 `processes.start` calls, or 5 `agents.start` calls. Going over one is
245
+ reported as `RateLimitError` too.
222
246
 
223
247
  ## Reading limits in code
224
248
 
@@ -246,7 +270,7 @@ interface LimitCounter {
246
270
  ```
247
271
 
248
272
  `limits` is exported by the package and is also the `limits` member of the context of
249
- a script, a route, a record trigger, and a background job. `limits.usage()` returns the
273
+ a script, a route, a record trigger, a background job, and a Custom Module Action. `limits.usage()` returns the
250
274
  budgets of the current execution as of its last Cogover call: reading them is not a
251
275
  capability call. `remaining` is `limit - used` and never below 0. `elapsedMs` is the
252
276
  time since the handler started, as of that last call, and `timeLimitMs` is the
@@ -0,0 +1,502 @@
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
+ readonly deliverTo?: AgentDeliveryTarget;
187
+ }
188
+
189
+ interface AgentRecordReference {
190
+ readonly objectSlug: string;
191
+ readonly recordId: string;
192
+ readonly withActivities?: boolean;
193
+ }
194
+
195
+ interface AgentResultCompletion {
196
+ readonly job: string;
197
+ readonly payload?: unknown;
198
+ }
199
+
200
+ interface AgentDeliveryTarget {
201
+ readonly personnelId: string;
202
+ readonly conversation?: "new" | "latest";
203
+ readonly title?: string;
204
+ }
205
+
206
+ interface AgentStartResult {
207
+ readonly runId: string;
208
+ readonly duplicate: boolean;
209
+ }
210
+ ```
211
+
212
+ ```typescript
213
+ const { runId } = await agents.start("AGXXXXXXXXXXXX", {
214
+ instruction: "Classify this email as a sales or a support request.",
215
+ variables: { subject: message.subject, body: message.body },
216
+ records: [{ objectSlug: "lead", recordId: leadId, withActivities: true }],
217
+ resultSchema: s.object({ category: s.enum(["sales", "support"]) }),
218
+ idempotencyKey: `classify:${message.id}`,
219
+ onResult: { job: "save_classification", payload: { messageId: message.id } },
220
+ });
221
+ ```
222
+
223
+ `agentId` is the ID of an AI Agent: 1 to 64 letters, digits, `_`, or `-`. Each run
224
+ works in a new session of its own, which no person sees; `deliverTo` is how a run
225
+ reaches a person.
226
+
227
+ | Option | Rules and meaning |
228
+ |---|---|
229
+ | `instruction` | Required. What the agent must do, 1 to 20,000 characters, not blank. |
230
+ | `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. |
231
+ | `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. |
232
+ | `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. |
233
+ | `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"`. |
234
+ | `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"`. |
235
+ | `timeoutSeconds` | Integer from 10 through 1800; defaults to `300`. Time limit of the run. |
236
+ | `idempotencyKey` | Same rules as for `processes.start`. |
237
+ | `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. |
238
+ | `deliverTo` | Lets the agent send a chat message to one personnel during the run; see [Sending a chat message to a personnel](#sending-a-chat-message-to-a-personnel). |
239
+
240
+ The result is the `runId` of the new run, and `duplicate: true` when an earlier start
241
+ with the same `idempotencyKey` returned that run instead. Invalid arguments throw
242
+ `ValidationError` before anything is sent.
243
+
244
+ #### Sending a chat message to a personnel
245
+
246
+ ```typescript
247
+ const { runId } = await agents.start("AGXXXXXXXXXXXX", {
248
+ instruction: "Check the overdue invoices of this account. If any are overdue, "
249
+ + "tell the account owner which ones and what to do next.",
250
+ records: [{ objectSlug: "account", recordId: accountId }],
251
+ runAs: "agent",
252
+ deliverTo: { personnelId: ownerPersonnelId, conversation: "latest", title: "Overdue invoices" },
253
+ idempotencyKey: `overdue:${accountId}:${today}`,
254
+ onResult: { job: "after_reminder", payload: { accountId } },
255
+ });
256
+ ```
257
+
258
+ With `deliverTo`, the agent can open a chat with a personnel on its own: the message
259
+ arrives in the AI chat of that agent and that personnel, who gets the usual notification
260
+ and can answer there.
261
+
262
+ | Member | Rules and meaning |
263
+ |---|---|
264
+ | `personnelId` | Required. Personnel ID of the recipient: 1 to 128 letters, digits, `_`, or `-`. |
265
+ | `conversation` | `"new"` (default): the message always opens a new conversation. `"latest"`: it continues the most recent conversation of the agent and the recipient, and opens a new one when there is none, when that conversation is busy with another run, or when the recipient deleted it. |
266
+ | `title` | Name of a conversation the run opens: one line of 1 to 80 characters, not blank, without control characters. Defaults to the start of the message. |
267
+
268
+ - The agent writes the message and decides whether to send one, so say in `instruction`
269
+ what the recipient needs to know and when a message is worth sending. The agent's final
270
+ answer (`text`) and `result` still come back only to your code; they are not sent to
271
+ the recipient.
272
+ - The run reports what happened as `delivery` (see
273
+ [`agents.get`](#agentsgetrunid-promiseagentrunstate)). The run's `status` does not
274
+ depend on it: a run can be `COMPLETED` while its message was not sent.
275
+ - The recipient must exist in the Workspace, may use the agent, and has an AI Agent seat.
276
+ Cogover checks this when the run starts and throws `CogoverApiError` with `code`
277
+ `RECIPIENT_NOT_FOUND`, `RECIPIENT_ACCESS_DENIED`, or `RECIPIENT_AI_SEAT_REQUIRED`
278
+ otherwise (see [Errors](#errors)): no run is created and nothing is sent. The identity
279
+ policy needs no entry for recipients, and an execution without a user may use
280
+ `deliverTo`.
281
+ - The recipient's conversation is separate from the run. It receives the message and a
282
+ note the agent leaves for itself about why it wrote. When the recipient answers, the
283
+ agent runs as the recipient, with the recipient's permissions, not with those of the run
284
+ that sent the message.
285
+ - Cogover limits how many messages an agent may send to one personnel in a run and per
286
+ day. A message over the limit is not sent, and `delivery` reports `BLOCKED` with
287
+ `RECIPIENT_RATE_LIMITED`.
288
+ - In local development with Cogover Dev CLI, a run started with `deliverTo` sends a real
289
+ message to a real person. Use a recipient who expects it.
290
+
291
+ ### `agents.get(runId): Promise<AgentRunState>`
292
+
293
+ ```typescript
294
+ interface AgentRunState<TResult = unknown> {
295
+ readonly runId: string;
296
+ readonly status: string;
297
+ readonly text: string | null;
298
+ readonly result: TResult | null;
299
+ readonly error: { readonly code: string; readonly message: string } | null;
300
+ readonly delivery: AgentDelivery | null;
301
+ }
302
+
303
+ interface AgentDelivery {
304
+ readonly status: "SENT" | "NOT_SENT" | "BLOCKED" | "FAILED";
305
+ readonly errorCode: string | null;
306
+ readonly chatSessionId: string | null;
307
+ readonly conversationId: string | null;
308
+ readonly newConversation: boolean;
309
+ }
310
+ ```
311
+
312
+ `status` is `QUEUED` or `RUNNING` while the run is in progress, then a final status
313
+ such as `COMPLETED`, `FAILED`, `TIMEOUT`, or `CANCELLED`. `text` is the agent's answer
314
+ (at most 32 KiB), `result` the structured result that matches `resultSchema`, and
315
+ `error` the reason of a failed run; each is `null` when absent. `error.code` is one of
316
+ `RESULT_SCHEMA_MISMATCH`, `TIMEOUT`, `CALLER_TIMEOUT`, `CANCELLED`, `MAX_TURNS`,
317
+ `GUARDRAIL_REJECTED`, `APPROVAL_DENIED`, `SERVER_RESTARTED`, `SESSION_BUSY`,
318
+ `SESSION_EVICTED`, `AGENT_INACTIVE`, `AGENT_ACCESS_DENIED`, `AGENT_CONFIG_INVALID`,
319
+ `CONFIG_LOAD_FAILED`, `LLM_HTTP_ERROR`, `LLM_NETWORK`, `LLM_RESPONSE_FAILED`, `LLM_PARSE`,
320
+ `OUTPUT_TRUNCATED`, `INTERNAL_ERROR`, one of the AI credit billing codes
321
+ `INSUFFICIENT_CREDITS`, `AI_SUBSCRIPTION_REQUIRED`, `AI_SEAT_REQUIRED`,
322
+ `AGENT_CREDIT_LIMIT_EXCEEDED`, or `MODEL_NOT_PRICED` (described in [Errors](#errors)) when
323
+ billing stopped the run, or `AGENT_ERROR` for any other reason, and
324
+ `error.message` is a fixed English description of that code: the text of the AI model
325
+ provider is never passed on. The `onResult` job receives the same `error`. A run that
326
+ this project did not start throws `NotFoundError`.
327
+
328
+ `delivery` is the outcome of `deliverTo`, and `null` for a run started without it. Read
329
+ it once the run has a final status: while the run is in progress it is not final and can
330
+ still be `null`. The `onResult` job receives the same value.
331
+
332
+ | `delivery.status` | Meaning |
333
+ |---|---|
334
+ | `SENT` | The recipient received at least one message. `chatSessionId` and `conversationId` identify the conversation, and `newConversation` is `true` when the run opened it. |
335
+ | `NOT_SENT` | The agent sent no message, for example because it found nothing to report. |
336
+ | `BLOCKED` | The agent tried to send, and the message was refused. `errorCode` says why. |
337
+ | `FAILED` | The agent tried to send, and sending failed. `errorCode` says why. |
338
+
339
+ `delivery.errorCode` is `null` for `SENT` and `NOT_SENT`. Otherwise it is one of:
340
+
341
+ | `delivery.errorCode` | Meaning |
342
+ |---|---|
343
+ | `RECIPIENT_NOT_FOUND` | The recipient is no longer a personnel of the Workspace. |
344
+ | `RECIPIENT_ACCESS_DENIED` | The recipient may not use the agent. |
345
+ | `RECIPIENT_AI_SEAT_REQUIRED` | The recipient has not been assigned an AI Agent seat. |
346
+ | `RECIPIENT_RATE_LIMITED` | The agent already sent as many messages to this recipient as one run or one day allows. |
347
+ | `INVALID_DELIVERY` | The message was empty or too long, or the agent is not active. |
348
+ | `NOT_ALLOWED_IN_CUSTOMER_CHAT` | The run belongs to a conversation with an external customer, from which personnel cannot be messaged. |
349
+ | `CHAT_SERVER_ERROR` | The conversation could not be opened or the message could not be sent. |
350
+ | `DELIVERY_UNAVAILABLE` | A temporary failure while checking the recipient or saving the conversation. |
351
+ | `INSUFFICIENT_CREDITS`, `AI_SUBSCRIPTION_REQUIRED`, `AGENT_CREDIT_LIMIT_EXCEEDED`, `MODEL_NOT_PRICED` | AI credit billing stopped the message (described in [Errors](#errors)). |
352
+ | `DELIVERY_ERROR` | Any other reason. |
353
+
354
+ `chatSessionId` and `conversationId` are `null` unless a message was sent.
355
+
356
+ ### Agent result job
357
+
358
+ ```typescript
359
+ interface AgentResultJobPayload<TPayload = unknown, TResult = unknown> {
360
+ readonly payload: TPayload | null;
361
+ readonly agentRun: {
362
+ readonly runId: string;
363
+ readonly status: string;
364
+ readonly text: string | null;
365
+ readonly result: TResult | null;
366
+ readonly error: { readonly code: string; readonly message: string } | null;
367
+ readonly usage: Record<string, unknown> | null;
368
+ readonly delivery: AgentDelivery | null;
369
+ };
370
+ }
371
+ ```
372
+
373
+ When a run started with `onResult` ends, Cogover enqueues one run of the job with this
374
+ value as its `payload`: `payload` is `onResult.payload` (or `null`), `agentRun.text` is
375
+ cut to 32 KiB, `agentRun.result` is `null` when it takes more than 16 KiB,
376
+ `agentRun.usage` reports `inputTokens`, `outputTokens`, `iterations`, and `durationMs`,
377
+ and `agentRun.delivery` is the outcome of `deliverTo` as `agents.get` reports it (`null`
378
+ for a run started without it).
379
+
380
+ ```typescript
381
+ defineJob<AgentResultJobPayload<{ accountId: string }>>({ key: "after_reminder" }, async ({ payload, log }) => {
382
+ const delivery = payload?.agentRun.delivery;
383
+ if (delivery?.status === "SENT") {
384
+ log.info("Owner reminded", { conversationId: delivery.conversationId });
385
+ } else if (delivery !== null && delivery !== undefined && delivery.status !== "NOT_SENT") {
386
+ log.warn("Reminder not delivered", { status: delivery.status, errorCode: delivery.errorCode });
387
+ }
388
+ });
389
+ ```
390
+
391
+ ### Completion jobs
392
+
393
+ - The job named by `onComplete` or `onResult` runs like any enqueued job (see
394
+ [Job execution rules](background-jobs.md#job-execution-rules)): `job.source` is
395
+ `"enqueue"`, it is delivered at least once, and it retries on `RetryableError`. The run
396
+ history lists it with `enqueuedBy` `process:<instanceId>` or `agent:<runId>`.
397
+ - It runs as the user of the execution that called `start` (or without a user when that
398
+ execution had none). It gets two steps less of the automation budget than that
399
+ execution had (one for reaching the Process or agent, one for coming back), and it
400
+ continues that execution's chain of jobs, so a job whose Process or agent ends by
401
+ starting the same job again stops like a job that enqueues itself. When no step would
402
+ be left, or the chain is too long, the outcome is not delivered.
403
+ - The job must be declared by the active version when `start` is called; otherwise
404
+ `start` throws `ValidationError`. If the active version no longer declares it when the
405
+ instance or run ends, or the project already has 10,000 job runs waiting, the outcome
406
+ is not delivered.
407
+
408
+ ### Idempotency and retries
409
+
410
+ - Without `idempotencyKey`, every `start` creates a new instance or run.
411
+ - With one, a second `start` with the same key in the same project returns the first
412
+ instance or run with `duplicate: true`. Cogover keeps the key while the instance or run
413
+ is active and for 7 days after it ends. Using the key again for another Process or
414
+ agent throws `ValidationError`. The key belongs to the identity that used it first:
415
+ another user of the project, or an execution without a user, that sends the same key
416
+ receives `CogoverApiError` with `code: "IDEMPOTENCY_CONFLICT"`, never the other
417
+ identity's instance or run. Include the user in keys that users may share.
418
+ - The key names the first run whatever its other options were: a second `agents.start`
419
+ with the same key and another `deliverTo` returns the first run with `duplicate: true`
420
+ and sends nothing to the other recipient. Include the recipient in the key when one
421
+ piece of work messages several people.
422
+ - `RetryableError` reports a temporary failure. When `details.writesMayHaveCompleted` is
423
+ `false`, nothing was started. When it is `true`, the instance or run may have been
424
+ created: retry later with the same `idempotencyKey`, and Cogover completes that start
425
+ instead of creating a second one; a retry that comes too soon may throw
426
+ `RetryableError` again. After a definite refusal, such as `ValidationError`,
427
+ `PermissionDeniedError`, an AI credit billing code, or a code about the recipient of
428
+ `deliverTo`, the key can be used again.
429
+ - In a job, a key derived from the job's `payload` or `job.id`, and in an action from
430
+ `action.runId`, keeps a retried handler from starting the same work twice.
431
+
432
+ ### Limits
433
+
434
+ - Every `processes` and `agents` call is one capability call (see
435
+ [Execution limits](overview.md#execution-limits)).
436
+ - One execution may call `processes.start` at most 20 times and `agents.start` at most
437
+ 5 times. Going over throws `RateLimitError` without `details.budget`.
438
+ - `agents.start` also counts against `maxRunsPerDay` of the identity policy, and the AI
439
+ Agent service may apply its own quota; both throw `RateLimitError`. A project may also
440
+ start at most 1,000 Processes per UTC day. A start that the Process or AI Agent service
441
+ refuses does not count.
442
+ - Starting a Process or an AI Agent run uses one step of the automation budget that also
443
+ limits chains of record triggers. When no step would be left, `start` throws
444
+ `CogoverApiError` with `code: "MAX_HOP_EXCEEDED"`.
445
+ - AI Agents that start one another, through actions or completion jobs, may go at most
446
+ 3 levels deep; one level deeper, `agents.start` throws `CogoverApiError` with
447
+ `code: "AGENT_DEPTH_EXCEEDED"`.
448
+ - A `"read"` action and a read-only local development session can call `get` but not
449
+ `start`: `start` throws `PermissionDeniedError`.
450
+ - Cogover limits how many messages a run may send to the recipient of `deliverTo`, in
451
+ the run and per day (see
452
+ [Sending a chat message to a personnel](#sending-a-chat-message-to-a-personnel)).
453
+
454
+ ### Errors
455
+
456
+ | Error | `code` | When |
457
+ |---|---|---|
458
+ | `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). |
459
+ | `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. |
460
+ | `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. |
461
+ | `RateLimitError` | `RATE_LIMITED` | A per-execution limit, `maxRunsPerDay`, the daily Process start limit, or a quota of the AI Agent service. |
462
+ | `RetryableError` | `RETRYABLE` | A temporary failure; see [Idempotency and retries](#idempotency-and-retries). |
463
+ | `CogoverApiError` | `MAX_HOP_EXCEEDED` | The automation budget is used up. |
464
+ | `CogoverApiError` | `IDEMPOTENCY_CONFLICT` | Another identity of the project already used this `idempotencyKey`. |
465
+ | `CogoverApiError` | `AGENT_DEPTH_EXCEEDED` | AI Agents would call one another more than 3 levels deep. |
466
+ | `CogoverApiError` | `INSUFFICIENT_CREDITS` | The Workspace has run out of AI credits. |
467
+ | `CogoverApiError` | `AI_SUBSCRIPTION_REQUIRED` | The Workspace has no paid AI Agent plan or trial. |
468
+ | `CogoverApiError` | `AI_SEAT_REQUIRED` | The user has not been assigned an AI Agent seat. |
469
+ | `CogoverApiError` | `AGENT_CREDIT_LIMIT_EXCEEDED` | The agent has used up its monthly AI credit limit. |
470
+ | `CogoverApiError` | `MODEL_NOT_PRICED` | The agent's AI model has no price or is disabled. |
471
+ | `CogoverApiError` | `RECIPIENT_NOT_FOUND` | The recipient of `deliverTo` is not a personnel of the Workspace. |
472
+ | `CogoverApiError` | `RECIPIENT_ACCESS_DENIED` | The recipient of `deliverTo` may not use the agent. |
473
+ | `CogoverApiError` | `RECIPIENT_AI_SEAT_REQUIRED` | The recipient of `deliverTo` has not been assigned an AI Agent seat. |
474
+ | `CogoverApiError` | `DELIVERY_UNAVAILABLE` | The recipient of `deliverTo` could not be checked right now; try again later. |
475
+ | `CogoverApiError` | `NOT_SUPPORTED` | `onComplete` or `onResult` in a local development session. |
476
+ | `CogoverApiError` | `PROCESSES_DISABLED`, `AGENTS_DISABLED` | The feature is not available in this environment. |
477
+
478
+ The five AI credit billing codes (`INSUFFICIENT_CREDITS` through `MODEL_NOT_PRICED`) are
479
+ thrown only by `agents.start`, when the AI Agent service refuses the run: no run is
480
+ created, `details.upstreamCode` holds the same code, and `details.writesMayHaveCompleted`
481
+ is `false`. Tell the user what to do (buy credits, subscribe, assign a seat, raise the
482
+ agent's limit, or choose another model) instead of retrying right away. A run that already
483
+ started and is stopped for the same reason ends with that code as `error.code`.
484
+
485
+ The four codes about the recipient (`RECIPIENT_NOT_FOUND` through `DELIVERY_UNAVAILABLE`)
486
+ are thrown only by `agents.start` with `deliverTo`: no run is created, nothing is sent, and
487
+ `details.upstreamCode` holds the same code. They are about the recipient, never about the
488
+ user of the execution, whose own refusals are `AI_SEAT_REQUIRED` and `PermissionDeniedError`
489
+ with `AGENT_RUN_DENIED`. `DELIVERY_UNAVAILABLE` is temporary and worth a later retry; the
490
+ other three need a change in the Workspace first. When the same problem appears only
491
+ while the run is sending, the run still ends normally and `delivery.errorCode` holds the
492
+ code.
493
+
494
+ ### Local development
495
+
496
+ When code runs locally with Cogover Dev CLI, `start` creates real Process instances and
497
+ agent runs, as the user of the Project key, and a read-only session refuses it. A run
498
+ started with `deliverTo` sends a real chat message to the recipient, exactly as a
499
+ published version does.
500
+ `onComplete` and `onResult` are refused with `CogoverApiError` `code: "NOT_SUPPORTED"`,
501
+ because their job runs only in a published version: test the start without them and
502
+ read the outcome with `get`, then publish the project to test the job.