@cogover/sdk 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,8 @@ import { createJobsApi } from "./jobs-api.js";
16
16
  import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
17
17
  import { TRIGGER_SLUG } from "./trigger-config.js";
18
18
  import { errorMessage, isRecord } from "./values.js";
19
+ import { createProcessesApi } from "./processes-api.js";
20
+ import { createAgentsApi } from "./agents-api.js";
19
21
  const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
20
22
  const MAX_ERROR_MESSAGE_LENGTH = 500;
21
23
  // Both spellings of a timing and an operation are accepted; project code only ever sees the SDK literals.
@@ -68,6 +70,9 @@ export function createTriggerSandboxHandler(manifest, handler) {
68
70
  crypto,
69
71
  org: createOrgApi(() => invocation ??= invocationContext(input)),
70
72
  limits,
73
+ // The host refuses processes and agents in a before-change trigger, like jobs.
74
+ processes: createProcessesApi(),
75
+ agents: createAgentsApi(),
71
76
  })));
72
77
  const results = [];
73
78
  for (const entry of entries) {
package/dist/jobs.d.ts CHANGED
@@ -12,6 +12,8 @@ import type { SandboxHandler } from "./script.js";
12
12
  import type { SecretsApi } from "./secrets.js";
13
13
  import type { ProjectState } from "./state.js";
14
14
  import type { EffectiveWorkspaceObjects } from "./workspace.js";
15
+ import type { ProcessesApi } from "./processes.js";
16
+ import type { AgentsApi } from "./agents.js";
15
17
  /** Runs a job on a cron schedule. */
16
18
  export interface JobSchedule {
17
19
  /** Five fields: minute, hour, day-of-month, month, day-of-week. */
@@ -98,6 +100,8 @@ export interface JobContext<TPayload = unknown, TSchema extends object = Effecti
98
100
  readonly org: OrgApi;
99
101
  /** Budgets of this execution; reading them is not a Cogover call. */
100
102
  readonly limits: LimitsApi;
103
+ readonly processes: ProcessesApi;
104
+ readonly agents: AgentsApi;
101
105
  }
102
106
  export type JobHandler<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects> = (context: JobContext<TPayload, TSchema>) => void | Promise<void>;
103
107
  /** Declares a background job. Add the result to the project's `jobs` export. */
@@ -0,0 +1,52 @@
1
+ /** Runs a background job of the project when the started Process instance finishes. */
2
+ export interface ProcessCompletion {
3
+ /** Key of a job of the project's `jobs` export. */
4
+ readonly job: string;
5
+ /** JSON value of at most 8192 UTF-8 bytes handed to the job as `payload`. */
6
+ readonly payload?: unknown;
7
+ }
8
+ /** Options of `processes.start`. */
9
+ export interface ProcessStartOptions {
10
+ /** Input variables of the Process, as a JSON object of at most 65536 UTF-8 bytes. */
11
+ readonly input?: Record<string, unknown>;
12
+ /** Name of the new instance, 1 to 255 characters. */
13
+ readonly instanceName?: string;
14
+ /** A second start with the same key in the same project returns the first instance instead of a new one. */
15
+ readonly idempotencyKey?: string;
16
+ /** Job that receives the outcome of the instance. */
17
+ readonly onComplete?: ProcessCompletion;
18
+ }
19
+ export interface ProcessStartResult {
20
+ readonly instanceId: string;
21
+ /** `true` when an earlier start with the same `idempotencyKey` was found; `instanceId` is that instance. */
22
+ readonly duplicate: boolean;
23
+ }
24
+ /** Current state of a Process instance. */
25
+ export interface ProcessInstanceState {
26
+ readonly instanceId: string;
27
+ readonly processId: string;
28
+ readonly processInfoId: string;
29
+ readonly state: string;
30
+ /** Unix milliseconds, or `null` when the instance has not started. */
31
+ readonly startedAt: number | null;
32
+ /** Unix milliseconds, or `null` while the instance runs. */
33
+ readonly finishedAt: number | null;
34
+ }
35
+ /** Starts Cogover Processes and reads their state. The result of a Process is delivered to a background job. */
36
+ export interface ProcessesApi {
37
+ start(processInfoId: string, options?: ProcessStartOptions): Promise<ProcessStartResult>;
38
+ get(instanceId: string): Promise<ProcessInstanceState>;
39
+ }
40
+ /** The `payload` of the job named by `onComplete` when the Process instance finishes. */
41
+ export interface ProcessCompletionJobPayload<TPayload = unknown> {
42
+ /** `onComplete.payload`, or `null` when there was none. */
43
+ readonly payload: TPayload | null;
44
+ readonly process: {
45
+ readonly instanceId: string;
46
+ readonly processId: string;
47
+ readonly processInfoId: string;
48
+ readonly state: "COMPLETED" | "CANCELED" | "DELETED" | "FAILED";
49
+ readonly output: Record<string, unknown> | null;
50
+ readonly finishedAt: number | null;
51
+ };
52
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/router.js CHANGED
@@ -67,6 +67,8 @@ export function createRouter() {
67
67
  crypto: context.crypto,
68
68
  org: context.org,
69
69
  limits: context.limits,
70
+ processes: context.processes,
71
+ agents: context.agents,
70
72
  });
71
73
  });
72
74
  },
package/dist/script.d.ts CHANGED
@@ -15,6 +15,8 @@ import type { SecretsApi } from "./secrets.js";
15
15
  import type { CryptoApi } from "./crypto.js";
16
16
  import type { OrgApi } from "./org.js";
17
17
  import type { LimitsApi } from "./limits.js";
18
+ import type { ProcessesApi } from "./processes.js";
19
+ import type { AgentsApi } from "./agents.js";
18
20
  export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
19
21
  readonly input: TInput;
20
22
  readonly request: ScriptRequest<TInput>;
@@ -34,6 +36,8 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
34
36
  readonly org: OrgApi;
35
37
  /** Budgets of this execution; reading them is not a Cogover call. */
36
38
  readonly limits: LimitsApi;
39
+ readonly processes: ProcessesApi;
40
+ readonly agents: AgentsApi;
37
41
  }
38
42
  export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
39
43
  export type SandboxHandler = (inputJson: string) => Promise<string | null>;
package/dist/script.js CHANGED
@@ -18,6 +18,8 @@ import { crypto } from "./crypto.js";
18
18
  import { createOrgApi } from "./org.js";
19
19
  import { limits } from "./limits.js";
20
20
  import { runInvocation } from "./internal/local-invocation.js";
21
+ import { createProcessesApi } from "./internal/processes-api.js";
22
+ import { createAgentsApi } from "./internal/agents-api.js";
21
23
  const RESPONSE_TOKEN_VERSION_MEMBER = "__cogoverResponseTokenVersion";
22
24
  export function defineScript(handler) {
23
25
  if (typeof handler !== "function") {
@@ -61,6 +63,8 @@ export function createSandboxHandler(handler) {
61
63
  crypto,
62
64
  org: createOrgApi(() => invocation ??= invocationContext(input)),
63
65
  limits,
66
+ processes: createProcessesApi(),
67
+ agents: createAgentsApi(),
64
68
  }));
65
69
  if (output === null) {
66
70
  return null;
package/dist/trigger.d.ts CHANGED
@@ -13,6 +13,8 @@ import type { FilterOperator } from "./query.js";
13
13
  import type { CogoverRecordId, UpdateFields } from "./records.js";
14
14
  import type { SchemaApi } from "./schema.js";
15
15
  import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
16
+ import type { ProcessesApi } from "./processes.js";
17
+ import type { AgentsApi } from "./agents.js";
16
18
  /** When a record trigger runs relative to the record change. */
17
19
  export type TriggerTiming = "beforeChange" | "afterChange";
18
20
  /** Record operations a trigger can subscribe to. */
@@ -136,6 +138,10 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
136
138
  readonly org: OrgApi;
137
139
  /** Budgets of this execution; reading them is not a Cogover call. */
138
140
  readonly limits: LimitsApi;
141
+ /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
142
+ readonly processes: ProcessesApi;
143
+ /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
144
+ readonly agents: AgentsApi;
139
145
  }
140
146
  export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
141
147
  /** Declares a record trigger. Add the result to the project's `triggers` export. */
@@ -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).
@@ -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.