@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
@@ -0,0 +1,403 @@
1
+ # `@cogover/sdk` API reference: Custom Module Actions
2
+
3
+ This page is part of the [`@cogover/sdk` API reference](overview.md).
4
+
5
+ ## Custom Module Actions
6
+
7
+ A Custom Module Action is a short, synchronous operation of the project that a
8
+ Process or an AI Agent can call. Process Builder offers each action exposed to
9
+ `"process"` as a **Custom Module Action** node, and AI Agent Builder offers each
10
+ action exposed to `"agent"` as a tool. Declare each action with `defineAction` and
11
+ list the results in the project's named `actions` export. The default export stays
12
+ optional in a project that only declares actions, triggers, and jobs.
13
+
14
+ This example assumes that `workspace.d.ts` declares the `lead` Object and the fields
15
+ used below.
16
+
17
+ ```typescript
18
+ import { defineAction, s } from "@cogover/sdk";
19
+
20
+ export const actions = [
21
+ defineAction({
22
+ key: "score_lead",
23
+ label: "Score lead",
24
+ description: "Scores a lead from its recent activities and returns a tier.",
25
+ exposeTo: ["process", "agent"],
26
+ effect: "read",
27
+ input: s.object({
28
+ leadId: s.recordId("lead").describe("ID of the lead to score"),
29
+ strict: s.boolean().optional(),
30
+ }),
31
+ output: s.object({
32
+ found: s.boolean(),
33
+ score: s.number(),
34
+ tier: s.enum(["A", "B", "C"]),
35
+ }),
36
+ timeoutMs: 5000,
37
+ async handler({ data, invocation, log }, input) {
38
+ const lead = await data.object("lead").records.get(input.leadId, { fields: ["rating"] });
39
+ if (!lead) return { found: false, score: 0, tier: "C" };
40
+ const score = Number(lead.fields.rating ?? 0) * (input.strict ? 8 : 10);
41
+ log.info("Lead scored", { leadId: lead.id, source: invocation.source.type });
42
+ return { found: true, score, tier: score >= 80 ? "A" : score >= 50 ? "B" : "C" };
43
+ },
44
+ }),
45
+ ];
46
+ ```
47
+
48
+ Cogover reads the action declarations when a project version is published and
49
+ offers the actions of the active version: Process nodes and AI Agent tools refer to
50
+ an action by the project slug and the action `key`, and always run the version that
51
+ is active when they call it. A version whose declarations are invalid fails to
52
+ publish with `ACTION_MANIFEST_INVALID`. Deactivating the project removes its actions
53
+ from both builders. A project can declare at most 50 actions.
54
+
55
+ The labels, descriptions, and schemas of the actions are visible to every active
56
+ member of the Workspace: do not put secrets in them.
57
+
58
+ ### `defineAction(config): ActionDefinition`
59
+
60
+ ```typescript
61
+ function defineAction<
62
+ TInput extends ObjectSchema<ObjectShape, false>,
63
+ TOutput extends ObjectSchema<ObjectShape, false>,
64
+ TSchema extends object = EffectiveWorkspaceObjects,
65
+ >(config: ActionConfig<TInput, TOutput, TSchema>): ActionDefinition;
66
+
67
+ type ActionExposure = "process" | "agent";
68
+ type ActionEffect = "read" | "write";
69
+
70
+ interface ActionConfig<
71
+ TInput extends ObjectSchema<ObjectShape, false> = ObjectSchema<ObjectShape, false>,
72
+ TOutput extends ObjectSchema<ObjectShape, false> = ObjectSchema<ObjectShape, false>,
73
+ TSchema extends object = EffectiveWorkspaceObjects,
74
+ > {
75
+ readonly key: string;
76
+ readonly label: string;
77
+ readonly description?: string;
78
+ readonly exposeTo: readonly ActionExposure[];
79
+ readonly effect: ActionEffect;
80
+ readonly input: TInput;
81
+ readonly output: TOutput;
82
+ readonly timeoutMs?: number;
83
+ readonly handler: ActionHandler<TInput, TOutput, TSchema>;
84
+ }
85
+ ```
86
+
87
+ `defineAction` validates the configuration immediately and throws `ValidationError`
88
+ for any violation, for an unknown configuration key, or for a handler that is not a
89
+ function; once the key is valid, `details.actionKey` and `details.option` name the action
90
+ and the option. It returns a frozen `ActionDefinition`. The handler's `input` parameter and return type
91
+ are inferred from the `input` and `output` schemas.
92
+
93
+ | Option | Required | Rules and meaning |
94
+ |---|---|---|
95
+ | `key` | Yes | Identifies the action inside the project: a lowercase letter followed by at most 63 lowercase letters, digits, or `_`. Unique in the project. Keep it stable between versions: Process nodes and agent tools that use the old key stop finding the action. |
96
+ | `label` | Yes | Name shown in Process Builder and AI Agent Builder, 1 to 100 characters after trimming. |
97
+ | `description` | For agents | At most 1000 characters after trimming. Required when `exposeTo` includes `"agent"`: the AI Agent reads it to decide when to call the tool. |
98
+ | `exposeTo` | Yes | Non-empty list of `"process"` and `"agent"` without duplicates: where the action can be used. |
99
+ | `effect` | Yes | `"read"`: the action runs read-only, and every write it attempts is refused with `PermissionDeniedError`. `"write"`: the action may write; AI Agent tools for it require a person's approval by default. |
100
+ | `input` | Yes | Schema of the input, created with `s.object`. |
101
+ | `output` | Yes | Schema of the output, created with `s.object`. |
102
+ | `timeoutMs` | No | Integer from 1000 through 8000; defaults to `8000`. Time limit of one call. |
103
+ | `handler` | Yes | `(context, input) => output`, synchronous or asynchronous. |
104
+
105
+ ### Schema builder `s`
106
+
107
+ `s` builds schemas that are TypeScript types and JSON Schema at the same time. An
108
+ action declares its `input` and `output` with it, and `agents.start` its
109
+ `resultSchema` (see [Processes and AI Agents](processes-and-agents.md)).
110
+
111
+ ```typescript
112
+ const s: {
113
+ string(options?: { minLength?: number; maxLength?: number }): Schema<string>;
114
+ enum<const Values extends readonly string[]>(values: Values): Schema<Values[number]>;
115
+ number(options?: { minimum?: number; maximum?: number }): Schema<number>;
116
+ integer(options?: { minimum?: number; maximum?: number }): Schema<number>;
117
+ boolean(): Schema<boolean>;
118
+ date(): Schema<string>;
119
+ dateTime(): Schema<number>;
120
+ recordId(objectSlug: string): Schema<CogoverRecordId>;
121
+ array<Item extends Schema<unknown, false>>(item: Item, options?: { maxItems?: number }): Schema<InferSchema<Item>[]>;
122
+ object<Shape extends ObjectShape>(shape: Shape): ObjectSchema<Shape>;
123
+ };
124
+
125
+ interface Schema<T = unknown, Optional extends boolean = false> {
126
+ optional(): Schema<T, true>;
127
+ describe(text: string): Schema<T, Optional>;
128
+ toJSON(): JsonSchema;
129
+ }
130
+
131
+ interface ObjectSchema<Shape extends ObjectShape = ObjectShape, Optional extends boolean = false>
132
+ extends Schema</* the object type of Shape */, Optional> {
133
+ optional(): ObjectSchema<Shape, true>;
134
+ describe(text: string): ObjectSchema<Shape, Optional>;
135
+ }
136
+
137
+ type ObjectShape = { readonly [property: string]: Schema<unknown, boolean> };
138
+ type InferSchema<T> = T extends Schema<infer Value, boolean> ? Value : never;
139
+
140
+ interface JsonSchema {
141
+ readonly [keyword: string]: null | boolean | number | string | readonly unknown[] | JsonSchema;
142
+ }
143
+ ```
144
+
145
+ | Builder | Value | JSON Schema | Process data type |
146
+ |---|---|---|---|
147
+ | `s.string({ minLength?, maxLength? })` | `string` | `{"type": "string"}` | Text |
148
+ | `s.enum(["A", "B"])` | one of the listed strings | `{"type": "string", "enum": [...]}` | Text |
149
+ | `s.number({ minimum?, maximum? })` | finite `number` | `{"type": "number"}` | Number |
150
+ | `s.integer({ minimum?, maximum? })` | safe integer | `{"type": "integer"}` | Number |
151
+ | `s.boolean()` | `boolean` | `{"type": "boolean"}` | Boolean |
152
+ | `s.date()` | `YYYY-MM-DD` string | `{"type": "string", "format": "date"}` | Date |
153
+ | `s.dateTime()` | Unix milliseconds, like a `date_time` field | `{"type": "integer", "format": "x-epoch-ms"}` | Date time |
154
+ | `s.recordId("lead")` | ID of a record of the Object, typed `CogoverRecordId` | `{"type": "string", "x-cogover-object": "lead"}` | Text |
155
+ | `s.array(item, { maxItems? })` | list of `item` values | `{"type": "array", "items": {...}}` | list of the item's type |
156
+ | `s.object({ ... })` | object with exactly these properties | `{"type": "object", "properties": {...}, "required": [...], "additionalProperties": false}` | Record, one child per property |
157
+
158
+ - Every node is immutable: `.optional()` and `.describe(text)` return a new node.
159
+ `.optional()` lets the property be left out of the object that contains it (it is
160
+ not listed in `required`); `.describe(text)` adds a `description` of 1 to 500
161
+ characters, stored trimmed, which Process Builder shows and the AI Agent reads.
162
+ - `s.string`: `maxLength` is 1 to 100000 and defaults to 10000; `minLength` is 0 to
163
+ `maxLength`. There is no `pattern` option: check a format, such as a code or an email
164
+ address, in the handler and throw `ValidationError` when it does not match.
165
+ - `s.enum`: 1 to 100 distinct strings of 1 to 200 characters.
166
+ - `s.number` and `s.integer`: `minimum` and `maximum` are finite numbers (safe
167
+ integers for `s.integer`), and `minimum` is not greater than `maximum`.
168
+ - `s.recordId`: the Object slug starts with a letter or `_` and has at most 128
169
+ letters, digits, or `_`. The value is typed `CogoverRecordId`, so the handler passes it
170
+ to `records.get` or `records.update` without a cast, and an output property built
171
+ with it takes the `id` of a record the records API returned. At runtime it is only a
172
+ string: Cogover does not check that the record exists.
173
+ - `s.array`: the item is not optional; `maxItems` is 1 to 10000 and defaults to 1000.
174
+ - `s.object`: at most 50 properties, each named like `leadId`: a letter followed by
175
+ at most 63 letters, digits, or `_`. Properties keep their declaration order.
176
+ - An action's `input` and `output`, and an agent's `resultSchema`, are a non-optional
177
+ `s.object` that nests objects and arrays at most 3 levels deep (the root object is
178
+ the first level). The JSON Schemas of an action's input and output together, and an
179
+ agent result schema, are at most 16384 UTF-8 bytes once JSON-encoded.
180
+ - Only nodes created by `s` are schemas: a hand-written JSON Schema object is
181
+ rejected with `ValidationError`. `toJSON()`, and therefore `JSON.stringify(node)`,
182
+ returns the node's JSON Schema.
183
+
184
+ `Schema` is a schema node describing values of one TypeScript type, `ObjectSchema` a
185
+ node created by `s.object`, and `ObjectShape` the map of property names to nodes that
186
+ `s.object` receives. `InferSchema` gives the TypeScript type of a node, and
187
+ `JsonSchema` is JSON Schema as plain JSON data:
188
+
189
+ ```typescript
190
+ const leadInput = s.object({ leadId: s.recordId("lead"), note: s.string().optional() });
191
+ type LeadInput = InferSchema<typeof leadInput>; // { leadId: string; note?: string }
192
+ ```
193
+
194
+ ### `ActionDefinition` and `ActionManifest`
195
+
196
+ ```typescript
197
+ interface ActionManifest {
198
+ readonly key: string;
199
+ readonly label: string;
200
+ readonly description: string;
201
+ readonly exposeTo: readonly ActionExposure[];
202
+ readonly effect: ActionEffect;
203
+ readonly timeoutMs: number;
204
+ readonly inputSchema: JsonSchema;
205
+ readonly outputSchema: JsonSchema;
206
+ }
207
+
208
+ interface ActionDefinition {
209
+ readonly key: string;
210
+ readonly config: ActionManifest;
211
+ readonly __cogoverActionHandler: (inputJson: string) => Promise<string>;
212
+ }
213
+ ```
214
+
215
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
216
+ default applied: `description` is `""` when none was given, `timeoutMs` is `8000`
217
+ unless set, and `label` and `description` are trimmed. It is what Process Builder and
218
+ AI Agent Builder show. It is detached from the object passed to `defineAction`.
219
+ `__cogoverActionHandler` is reserved for Cogover; project code does not call it.
220
+
221
+ ### Action handler context
222
+
223
+ ```typescript
224
+ type ActionHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (
225
+ context: ActionContext<TSchema>,
226
+ input: InferSchema<TInput>,
227
+ ) => InferSchema<TOutput> | Promise<InferSchema<TOutput>>;
228
+
229
+ interface ActionContext<TSchema extends object = EffectiveWorkspaceObjects> {
230
+ readonly action: ActionInfo;
231
+ readonly invocation: ActionInvocationContext;
232
+ readonly data: DataApi<TSchema>;
233
+ readonly schema: SchemaApi<TSchema>;
234
+ readonly log: ScriptLogger;
235
+ readonly state: ProjectState;
236
+ readonly locks: DistributedLocks;
237
+ readonly push: PushApi<TSchema>;
238
+ readonly notifications: NotificationsApi;
239
+ readonly email: EmailApi<TSchema>;
240
+ readonly jobs: JobsApi;
241
+ readonly secrets: SecretsApi;
242
+ readonly crypto: CryptoApi;
243
+ readonly org: OrgApi;
244
+ readonly limits: LimitsApi;
245
+ readonly processes: ProcessesApi;
246
+ readonly agents: AgentsApi;
247
+ }
248
+
249
+ interface ActionInfo {
250
+ readonly key: string;
251
+ readonly runId: string;
252
+ readonly effect: ActionEffect;
253
+ }
254
+
255
+ type ActionInvocationContext = (UserInvocationContext | SystemInvocationContext) & {
256
+ readonly executionIdentity: "user" | "system";
257
+ readonly source: ActionSource;
258
+ };
259
+
260
+ type ActionSource = ProcessActionSource | AgentActionSource;
261
+
262
+ interface ProcessActionSource {
263
+ readonly type: "process";
264
+ readonly processId: string;
265
+ readonly processInfoId: string;
266
+ readonly instanceId: string;
267
+ readonly nodeId: string;
268
+ readonly runAs: ProcessActionRunAs | null;
269
+ }
270
+
271
+ type ProcessActionRunAs = "PROCESS_STARTER" | "PERSONNEL" | "SYSTEM";
272
+
273
+ interface AgentActionSource {
274
+ readonly type: "agent";
275
+ readonly agentId: string;
276
+ readonly sessionId: string | null;
277
+ readonly runId: string | null;
278
+ readonly interactive: boolean;
279
+ readonly initiatorPersonnelId: string | null;
280
+ }
281
+ ```
282
+
283
+ `data`, `schema`, `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`,
284
+ `secrets`, `crypto`, `org`, and `limits` are the same APIs that scripts receive, and
285
+ `processes` and `agents` are described in [Processes and AI Agents](processes-and-agents.md).
286
+ An action context has no `input`, `request`, or `response`: the input is the second
287
+ argument of the handler.
288
+
289
+ - `action.key` and `action.effect` repeat the configuration. `action.runId`
290
+ identifies the call and stays the same when the caller sends the same call again
291
+ (for example a Process node retrying after a network failure); a new run of the
292
+ node or a new tool call of the agent has a new `runId`. Use it as the idempotency key
293
+ of external calls and of `jobs.enqueue` or `processes.start`.
294
+ - `invocation` is a user or system invocation context (see
295
+ [Invocation identity and workspace](scripts-and-routes.md#invocation-identity-and-workspace))
296
+ with `executionIdentity`, which repeats `invocation.identity`, and `source`.
297
+ - `invocation.source` names the caller. `ProcessActionSource` gives the Process
298
+ (`processId`), its definition (`processInfoId`), the running instance
299
+ (`instanceId`), the BPMN node (`nodeId`), and `runAs`, the `ProcessActionRunAs` the
300
+ node used to choose the identity the action runs as: `"PROCESS_STARTER"` (the person
301
+ who started the process), `"PERSONNEL"` (a person the node names, possibly from
302
+ process data), or `"SYSTEM"`; it is `null` when the caller did not say.
303
+ `AgentActionSource` gives the agent, its chat session and its run (each `null` when
304
+ the agent was not started that way), `interactive`, which is `true` when a person is
305
+ chatting with the agent, and `initiatorPersonnelId`, the personnel ID of the person
306
+ chatting with the agent or of the person who started the agent run (`null` when there
307
+ is none).
308
+ - An action called by an AI Agent runs as the agent's identity, which may differ from
309
+ the person chatting: every user of the agent gets that identity's access. When the
310
+ action must only do what the person may do, check `initiatorPersonnelId` in the
311
+ handler (for example with `data.asUser`, which the identity policy must allow) and
312
+ refuse otherwise. With `runAs: "PERSONNEL"`, the Process may have taken the person
313
+ from data a user or an external system supplied: do not treat it as proof of who
314
+ asked.
315
+
316
+ ### Input and output
317
+
318
+ - Cogover checks the input against the `input` schema before the handler runs. An
319
+ invalid input does not run the handler: the caller receives `INPUT_INVALID` with the
320
+ JSON Pointer path and a message for each problem (at most 20). The handler therefore
321
+ always receives exactly the declared properties, with values of the declared types.
322
+ - The handler returns the output. Cogover checks it against the `output` schema after
323
+ the handler returns: a value that is not JSON data, or that does not match, is
324
+ reported to the caller as `OUTPUT_INVALID`, and the writes the handler made are not
325
+ undone. Return an object; `undefined` is not a valid output.
326
+ - A Process node or an AI Agent receives only the code and a safe, fixed message of an
327
+ error the handler throws (see below), never the handler's own message. When the
328
+ caller needs to know why an expected case failed, describe it in the output, like
329
+ `found` in the example above, instead of throwing.
330
+
331
+ ### Action execution rules
332
+
333
+ - **Identity.** A Process node runs the action as the person who started the Process,
334
+ as a selected personnel, or without a user, as chosen on the node. An AI Agent runs
335
+ it as the person the agent acts for. With a user, `invocation.user` describes that
336
+ person, `data.object()` uses their permissions, and Cogover first checks that the
337
+ person is still an active member of the Workspace. Without a user,
338
+ `invocation.identity` is `"system"`, and the call is refused before it runs unless
339
+ the approved identity policy of the active version sets `allowInternalSystem: true`.
340
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual. When the
341
+ active version has no approved identity policy, an action runs like an HTTP route
342
+ does: a call with a user runs with that user's own permissions and none of the
343
+ policy's grants (`data.asSystem()`, `data.asUser()`, `email.send()`, `fetch()` to
344
+ other ports, `processes.start()` and `agents.start()` are refused), and a call
345
+ without a user is refused before it runs.
346
+ - **Effect.** A `"read"` action may read records, schema, and `state`, use `org`,
347
+ `email.senders`, and `crypto` except with a `{ secret }` key, send a `fetch` with
348
+ method `GET` or `HEAD` and no credential, and call `processes.get` and `agents.get`. Every other call,
349
+ such as a record write, `locks`, `push`, `notifications.send`, `email.send`,
350
+ `jobs.enqueue`, `secrets.get`, `processes.start`, or `agents.start`, throws
351
+ `PermissionDeniedError` with the message `This action is declared read-only`.
352
+ - **Limits.** An action has the budgets of an HTTP route (see
353
+ [Execution limits](overview.md#execution-limits)) and its own time limit,
354
+ `timeoutMs`, counted from when the handler starts. Exceeding the time ends the call
355
+ with `TIMEOUT`; the handler cannot catch it.
356
+ - **Repeated calls.** Process nodes and AI Agents send a call again with the same
357
+ `runId` when they do not receive the answer. Cogover then returns the stored result
358
+ of a finished call without running the handler again, for 7 days, and refuses the
359
+ same `runId` with a different input. If Cogover is interrupted while the handler
360
+ runs, a later retry can run the handler again, so make an action that writes
361
+ idempotent, for example with `action.runId`.
362
+ - **Loops end.** Every call carries the automation budget of the Process run or agent
363
+ that made it, and record writes of the action use it like writes of a trigger. A call
364
+ whose budget is used up is refused with `MAX_HOP_EXCEEDED` before it runs.
365
+
366
+ ### How Processes and AI Agents use an action
367
+
368
+ - **Process.** The **Custom Module Action** node lists the actions exposed to
369
+ `"process"`. The node fills each top-level input property from Process data; a
370
+ property the node leaves empty is not sent, so declare it `.optional()` unless it is
371
+ always needed. Later nodes read the node output: `status` (`COMPLETED` or `FAILED`),
372
+ `result` (the action output, with one child per output property), `errorCode`,
373
+ `errorMessage`, `runId`, and `durationMs`. A failed call stops the Process run
374
+ unless the node is set to continue on failure.
375
+ - **AI Agent.** A tool of the **Custom Module** category calls one action exposed to
376
+ `"agent"`. The agent sees the action's description and input schema, including the
377
+ `describe` texts, and generates the input; Cogover checks it like any input. The
378
+ agent receives the output as JSON, or the error code and message. A tool for a
379
+ `"write"` action requires a person's approval by default; the agent's configuration
380
+ can change that.
381
+
382
+ ### Errors seen by the caller
383
+
384
+ A call that ran reports `COMPLETED` with the output, or `FAILED` with one of these
385
+ codes:
386
+
387
+ | Code | Meaning |
388
+ |---|---|
389
+ | `INPUT_INVALID` | The input does not match the `input` schema; the handler did not run. `details.errors` lists `path` and `message` of each problem. |
390
+ | `OUTPUT_INVALID` | The handler returned a value that is not JSON data or does not match the `output` schema. |
391
+ | `SCRIPT_ERROR` | The handler threw an SDK error. `details.scriptErrorCode` is its code, such as `VALIDATION_ERROR` or `NOT_FOUND`, with the same safe message an HTTP route returns for that code. Any other error is reported with the message `The action handler failed`. |
392
+ | `TIMEOUT` | The call exceeded `timeoutMs`; `details.timeoutMs` is the limit applied. |
393
+ | `RATE_LIMITED` | The call went over a budget of the execution; `details.budget` describes it. |
394
+ | `SCRIPT_ERROR` with `details.reason` `"RESOURCE_LIMIT_EXCEEDED"` | The handler used up a sandbox resource limit: statements, memory, or stack. |
395
+ | `PERMISSION_DENIED` | The handler let a `PermissionDeniedError` escape, for example a write in a `"read"` action. While a new version is being activated, a call may briefly fail with `details.reason` `"PROJECT_POLICY_NOT_APPROVED"` before it runs; the caller's retry runs it. |
396
+ | `INTERNAL_ERROR` | Another failure. |
397
+
398
+ A call can also be refused before the action runs: the action is not found in the
399
+ active version or is not exposed to that caller, the person it would run as is no
400
+ longer an active member, a call without a user is not allowed by the identity policy,
401
+ the automation budget is used up, the same `action.runId` was already used with another
402
+ input or by another caller or identity, or Cogover is temporarily unavailable (the caller
403
+ retries).
@@ -164,6 +164,9 @@ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspa
164
164
  readonly secrets: SecretsApi;
165
165
  readonly crypto: CryptoApi;
166
166
  readonly org: OrgApi;
167
+ readonly limits: LimitsApi;
168
+ readonly processes: ProcessesApi;
169
+ readonly agents: AgentsApi;
167
170
  }
168
171
 
169
172
  interface JobInfo {
@@ -179,13 +182,15 @@ interface JobInfo {
179
182
 
180
183
  A handler may be synchronous or asynchronous; its return value is ignored. `data`,
181
184
  `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
182
- `secrets`, `crypto`, and `org` are the same APIs that scripts receive. A job context has
183
- no `input`, `request`, `response`, or `push`.
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)).
187
+ A job context has no `input`, `request`, `response`, or `push`.
184
188
 
185
189
  - `job.id` identifies the run and stays the same across its attempts; use it as the
186
190
  idempotency key of external calls. `job.attempt` starts at 1.
187
- - `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
188
- 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`
189
194
  is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
190
195
  milliseconds, and `enqueuedAt` is absent for a scheduled run.
191
196
  - `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
@@ -229,15 +234,15 @@ both. `idempotencyKey` starts with a letter or digit, contains letters, digits,
229
234
  with the same key while the earlier run is still kept returns that run with
230
235
  `duplicate: true` instead of creating another. Run history is kept for 7 days.
231
236
 
232
- `enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
233
- 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`
234
240
  (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
235
241
  without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
236
242
  enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
237
- running; beyond that `RateLimitError` is thrown. An HTTP route or a trigger reaches
238
- its budget of 20 capability calls first (see
239
- [Execution limits](overview.md#execution-limits)), so there the limit of 50 enqueues
240
- is not reached. When jobs are not enabled for the Workspace, the error is
243
+ running; beyond that `RateLimitError` is thrown. Each `enqueue` also counts as a
244
+ capability call (see [Execution limits](overview.md#execution-limits)). When jobs are
245
+ not enabled for the Workspace, the error is
241
246
  `CogoverApiError` with `code: "JOBS_DISABLED"`.
242
247
 
243
248
  ### Job execution rules
@@ -256,8 +261,15 @@ is not reached. When jobs are not enabled for the Workspace, the error is
256
261
  `data.asUser()`; use `data.asSystem()` to group (see
257
262
  [Aggregates](records.md#aggregates)).
258
263
  - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
259
- `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
260
- 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.
261
273
  - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
262
274
  split: process one page, save the cursor, and enqueue the same job again with the
263
275
  cursor in the payload, as in the example above.
@@ -310,8 +310,9 @@ base64, which is a third larger. Binary data larger than about 190 KiB, or text
310
310
  close to 256 KiB together with other arguments, therefore throws `ValidationError`
311
311
  before the call even though each value is within its own limit. The key, algorithm, and option errors that
312
312
  Cogover detects, such as a key of the wrong size or type, also throw
313
- `ValidationError`. Every operation except `timingSafeEqual` is a capability call
314
- and counts towards the invocation's limits; `randomUUID` makes one call for every
313
+ `ValidationError`. Every operation except `timingSafeEqual` is a local call and counts
314
+ towards the invocation's budget of local calls, not its capability calls (see
315
+ [Execution limits](overview.md#execution-limits)); `randomUUID` makes one call for every
315
316
  64 UUIDs.
316
317
 
317
318
  The operations work in every context, including before-change triggers, with a key
@@ -86,9 +86,9 @@ headers, time, calls, destinations, and concurrency are bounded by platform quot
86
86
  Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
87
87
  `FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
88
88
  `FETCH_FAILED`; quota failures use `RateLimitError`. One execution may make at most 20
89
- `fetch` calls; an HTTP route or a trigger reaches its budget of 20 capability calls
90
- first, which is also reported as `RateLimitError` (see
91
- [Execution limits](overview.md#execution-limits)). When POST, PUT, PATCH, or DELETE
89
+ `fetch` calls, and each one also counts against the capability-call budget of the
90
+ execution (see [Execution limits](overview.md#execution-limits)); going over either is
91
+ reported as `RateLimitError`. When POST, PUT, PATCH, or DELETE
92
92
  times out or loses its response, the remote server may already have applied the
93
93
  request. Use the remote API's idempotency mechanism and never retry blindly.
94
94
 
@@ -174,8 +174,8 @@ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
174
174
  secrets only when its administrator allowed it, otherwise the reason is
175
175
  `"SECRETS_NOT_ALLOWED"`. One invocation may read secrets at most 20 times; every
176
176
  read counts, including a repeated read of the same name and a `crypto` operation keyed
177
- by `{ secret: name }`, and the 21st throws `RateLimitError`. In an HTTP route or a
178
- trigger the budget of 20 capability calls is reached first (see
177
+ by `{ secret: name }`, and the 21st throws `RateLimitError`. `secrets.get` also counts
178
+ as a capability call, and a `crypto` operation as a local call (see
179
179
  [Execution limits](overview.md#execution-limits)). When secrets are
180
180
  not enabled for the Workspace, the error is `CogoverApiError` with
181
181
  `code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
@@ -291,7 +291,7 @@ only the chain that starts there and `directOnly` only its nearest tier. Both re
291
291
  when the project's approved identity policy sets `allowInternalSystem: true`;
292
292
  otherwise every call except `org.me()` throws `PermissionDeniedError` with
293
293
  `details.reason` `"IDENTITY_NOT_GRANTED"`. `org.me()` returns `null` there without a
294
- capability call, because the execution has no user.
294
+ call, because the execution has no user.
295
295
  - All calls of one execution read the same version of the structure.
296
296
  - IDs are validated by the SDK and again by Cogover; an invalid ID or option throws
297
297
  `ValidationError`. Every method returns a promise, and an invalid argument rejects
@@ -300,5 +300,6 @@ only the chain that starts there and `directOnly` only its nearest tier. Both re
300
300
  `NotFoundError` with `resource` `"department"` or `"position"`.
301
301
  - When the structure cannot be read, the call throws `CogoverApiError` with code
302
302
  `ORGANIZATION_UNAVAILABLE`.
303
- - Call `getMany` or `members` instead of calling `get` in a loop: each call is one
304
- capability call.
303
+ - A read without `withDisplay` is a local call; a read with `withDisplay: true` is a
304
+ capability call (see [Execution limits](overview.md#execution-limits)). Call `getMany`
305
+ or `members` instead of calling `get` in a loop: each call counts once.