@cogover/sdk 0.15.0 → 0.17.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.
package/README.md CHANGED
@@ -312,6 +312,18 @@ use (`processes` and `agents` sections). `processes.get(instanceId)` and
312
312
  `agents.get(runId)` read the state of a run the module started. One execution may start
313
313
  at most 20 Processes and 5 agent runs.
314
314
 
315
+ With `deliverTo`, an agent run can send a chat message to a personnel on its own, in the
316
+ AI chat of the agent and that personnel; the run reports the outcome as `delivery`:
317
+
318
+ ```typescript
319
+ await agents.start("AGXXXXXXXXXXXX", {
320
+ instruction: "Tell the ticket owner what the customer is waiting for.",
321
+ records: [{ objectSlug: "ticket", recordId: ticketId }],
322
+ deliverTo: { personnelId: ownerPersonnelId, conversation: "latest" },
323
+ onResult: { job: "owner_notified", payload: { ticketId } },
324
+ });
325
+ ```
326
+
315
327
  ## Outbound HTTP with `fetch`
316
328
 
317
329
  Cogover provides a Fetch-compatible function for calling an external HTTPS API.
@@ -642,6 +654,7 @@ router.post("/quotes/:id/send", async ({ request, notifications, email }) => {
642
654
  title: "Quote sent to the customer",
643
655
  content: "The quote was emailed and logged on its timeline.",
644
656
  link: { url: `/app/quote/${quoteId}` },
657
+ categories: ["sales"],
645
658
  idempotencyKey: `quote-sent:${quoteId}`,
646
659
  });
647
660
  return { requestId: sent.requestId };
@@ -651,7 +664,9 @@ router.post("/quotes/:id/send", async ({ request, notifications, email }) => {
651
664
  Both are available in scripts, routes, after-change triggers, and jobs, and both are
652
665
  asynchronous and best-effort: a successful call means Cogover accepted the message.
653
666
  `idempotencyKey` makes a retry within 7 days return the first result with
654
- `duplicate: true` instead of sending again. Notifications need no approval; email
667
+ `duplicate: true` instead of sending again. `categories` files a notification under
668
+ notification categories of the workspace by category code (such as `"sales"`) or
669
+ record ID, so recipients can filter their list. Notifications need no approval; email
655
670
  may only be sent from the mailboxes allowed by the `email` section of the Project's
656
671
  approved identity policy, otherwise `PermissionDeniedError` is thrown with
657
672
  `details.reason === "EMAIL_SENDER_NOT_GRANTED"`. `email.senders()` lists the
package/dist/agents.d.ts CHANGED
@@ -13,6 +13,37 @@ export interface AgentResultCompletion {
13
13
  /** JSON value of at most 8192 UTF-8 bytes handed to the job as `payload`. */
14
14
  readonly payload?: unknown;
15
15
  }
16
+ /**
17
+ * A personnel the agent may send a chat message to during the run. The message arrives in the AI chat of the
18
+ * agent and that personnel, and the personnel can answer there.
19
+ */
20
+ export interface AgentDeliveryTarget {
21
+ /** Personnel ID of the recipient. */
22
+ readonly personnelId: string;
23
+ /**
24
+ * `"new"` (default) always opens a new conversation; `"latest"` continues the most recent conversation of the
25
+ * agent and the recipient and opens a new one when there is none to continue.
26
+ */
27
+ readonly conversation?: "new" | "latest";
28
+ /** Name of a conversation the run opens: one line of at most 80 characters; defaults to the message's start. */
29
+ readonly title?: string;
30
+ }
31
+ /** What happened to the message of a run started with `deliverTo`. */
32
+ export interface AgentDelivery {
33
+ /**
34
+ * `"SENT"`: the recipient received at least one message. `"NOT_SENT"`: the agent sent none. `"BLOCKED"`: the
35
+ * agent tried, and the recipient may not receive it. `"FAILED"`: the agent tried, and sending failed.
36
+ */
37
+ readonly status: "SENT" | "NOT_SENT" | "BLOCKED" | "FAILED";
38
+ /** Why the message was blocked or failed, or `null`. */
39
+ readonly errorCode: string | null;
40
+ /** Chat session of the agent and the recipient, or `null` when nothing was sent. */
41
+ readonly chatSessionId: string | null;
42
+ /** Conversation the message was sent to, or `null` when nothing was sent. */
43
+ readonly conversationId: string | null;
44
+ /** `true` when the run opened a new conversation. */
45
+ readonly newConversation: boolean;
46
+ }
16
47
  /** Options of `agents.start`. */
17
48
  export interface AgentStartOptions {
18
49
  /** What the agent must do, 1 to 20000 characters. */
@@ -33,6 +64,8 @@ export interface AgentStartOptions {
33
64
  readonly idempotencyKey?: string;
34
65
  /** Job that receives the outcome of the run. */
35
66
  readonly onResult?: AgentResultCompletion;
67
+ /** Lets the agent send a chat message to this personnel; the run reports the outcome as `delivery`. */
68
+ readonly deliverTo?: AgentDeliveryTarget;
36
69
  }
37
70
  export interface AgentStartResult {
38
71
  readonly runId: string;
@@ -51,6 +84,8 @@ export interface AgentRunState<TResult = unknown> {
51
84
  readonly code: string;
52
85
  readonly message: string;
53
86
  } | null;
87
+ /** Outcome of `deliverTo`; `null` for a run started without it, and possibly until the run ends. */
88
+ readonly delivery: AgentDelivery | null;
54
89
  }
55
90
  /** Starts AI Agent runs and reads their state. The result of a run is delivered to a background job. */
56
91
  export interface AgentsApi {
@@ -71,5 +106,7 @@ export interface AgentResultJobPayload<TPayload = unknown, TResult = unknown> {
71
106
  readonly message: string;
72
107
  } | null;
73
108
  readonly usage: Record<string, unknown> | null;
109
+ /** Outcome of `deliverTo`; `null` for a run started without it. */
110
+ readonly delivery: AgentDelivery | null;
74
111
  };
75
112
  }
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export type { ActionExposure, ActionEffect, ActionConfig, ActionManifest, Action
17
17
  export { s } from "./action-schema.js";
18
18
  export type { Schema, ObjectSchema, ObjectShape, InferSchema, JsonSchema, } from "./action-schema.js";
19
19
  export type { ProcessesApi, ProcessStartOptions, ProcessStartResult, ProcessInstanceState, ProcessCompletion, ProcessCompletionJobPayload, } from "./processes.js";
20
- export type { AgentsApi, AgentStartOptions, AgentStartResult, AgentRunState, AgentRecordReference, AgentResultCompletion, AgentResultJobPayload, } from "./agents.js";
20
+ export type { AgentsApi, AgentStartOptions, AgentStartResult, AgentRunState, AgentRecordReference, AgentResultCompletion, AgentResultJobPayload, AgentDeliveryTarget, AgentDelivery, } from "./agents.js";
21
21
  export type { SecretsApi } from "./secrets.js";
22
22
  export type { OrgApi, OrgPersonnelApi, OrgDepartmentsApi, OrgPositionsApi, OrgReadOptions, OrgPageOptions, OrgDepartmentMembersOptions, OrgPositionMembersOptions, OrgManagerOptions, OrgPersonnelChainOptions, OrgTreeOptions, OrgIsInDepartmentOptions, OrgIsManagerOfOptions, OrgPersonnelDisplay, OrgNameDisplay, OrgMembership, OrgMember, OrgPersonnel, OrgDepartment, OrgDepartmentNode, OrgPosition, OrgManagerTier, OrgManagerChain, OrgPage, OrgGetManyResult, } from "./org.js";
23
23
  export { limits } from "./limits.js";
@@ -2,17 +2,20 @@ import { CogoverApiError, ValidationError } from "../errors.js";
2
2
  import { MAX_SCHEMA_BYTES, rootSchemaJson, schemaByteLength } from "./action-schema-rules.js";
3
3
  import { callBridge } from "./bridge.js";
4
4
  import { deepFreeze } from "./json.js";
5
- import { requireKnownKeys } from "./messaging.js";
5
+ import { PERSONNEL_ID, requireKnownKeys } from "./messaging.js";
6
6
  import { OBJECT_SLUG, PROPERTY_NAME } from "./schema-nodes.js";
7
7
  import { optionalBoundedText, optionalCompletion, optionalStartIdempotencyKey, requirePlatformId, } from "./start-options.js";
8
8
  import { isRecord } from "./values.js";
9
9
  const START_OPTIONS = new Set([
10
10
  "instruction", "variables", "records", "resultSchema", "runAs", "approvalPolicy", "timeoutSeconds",
11
- "idempotencyKey", "onResult",
11
+ "idempotencyKey", "onResult", "deliverTo",
12
12
  ]);
13
13
  const RECORD_KEYS = new Set(["objectSlug", "recordId", "withActivities"]);
14
+ const DELIVER_TO_KEYS = new Set(["personnelId", "conversation", "title"]);
14
15
  const RUN_AS = new Set(["caller", "agent"]);
15
16
  const APPROVAL_POLICIES = new Set(["deny", "autoApprove"]);
17
+ const CONVERSATIONS = new Set(["new", "latest"]);
18
+ const DELIVERY_STATUSES = new Set(["SENT", "NOT_SENT", "BLOCKED", "FAILED"]);
16
19
  const RUN_ID = /^[A-Za-z0-9:_.-]{1,160}$/u;
17
20
  const RECORD_ID = /^[A-Za-z0-9_-]{1,128}$/u;
18
21
  const MAX_INSTRUCTION_LENGTH = 20_000;
@@ -22,6 +25,8 @@ const MAX_RECORDS = 20;
22
25
  const MIN_TIMEOUT_SECONDS = 10;
23
26
  const MAX_TIMEOUT_SECONDS = 1800;
24
27
  const DEFAULT_TIMEOUT_SECONDS = 300;
28
+ const MAX_DELIVERY_TITLE_LENGTH = 80;
29
+ const CONTROL_CHARACTER = /[\u0000-\u001f\u007f-\u009f]/u;
25
30
  /** @internal */
26
31
  export function createAgentsApi() {
27
32
  return Object.freeze({
@@ -71,8 +76,26 @@ function startPayload(agentId, options) {
71
76
  const onResult = optionalCompletion(settings.onResult, "agents.start() onResult");
72
77
  if (onResult !== undefined)
73
78
  payload.onResult = onResult;
79
+ if (settings.deliverTo !== undefined)
80
+ payload.deliverTo = deliverTo(settings.deliverTo);
74
81
  return payload;
75
82
  }
83
+ function deliverTo(value) {
84
+ const target = requireKnownKeys(value, DELIVER_TO_KEYS, "agents.start() deliverTo");
85
+ if (typeof target.personnelId !== "string" || !PERSONNEL_ID.test(target.personnelId)) {
86
+ throw new ValidationError("agents.start() deliverTo personnelId must contain 1 to 128 letters, digits, "
87
+ + "'_' or '-'");
88
+ }
89
+ const title = optionalBoundedText(target.title, "agents.start() deliverTo title", MAX_DELIVERY_TITLE_LENGTH);
90
+ if (title !== undefined && CONTROL_CHARACTER.test(title)) {
91
+ throw new ValidationError("agents.start() deliverTo title must be a single line without control characters");
92
+ }
93
+ return {
94
+ personnelId: target.personnelId,
95
+ conversation: choice(target.conversation, "deliverTo conversation", CONVERSATIONS, "new"),
96
+ ...(title === undefined ? {} : { title }),
97
+ };
98
+ }
76
99
  function variables(value) {
77
100
  if (!isRecord(value) || Object.keys(value).length > MAX_VARIABLES) {
78
101
  throw new ValidationError(`agents.start() variables must be an object of at most ${MAX_VARIABLES} entries`);
@@ -159,5 +182,29 @@ function runState(value) {
159
182
  text,
160
183
  result: deepFreeze(value.result ?? null),
161
184
  error,
185
+ delivery: delivery(value.delivery ?? null, invalid),
186
+ });
187
+ }
188
+ function delivery(value, invalid) {
189
+ if (value === null)
190
+ return null;
191
+ if (!isRecord(value) || typeof value.status !== "string" || !DELIVERY_STATUSES.has(value.status))
192
+ throw invalid();
193
+ const errorCode = value.errorCode ?? null;
194
+ const chatSessionId = value.chatSessionId ?? null;
195
+ const conversationId = value.conversationId ?? null;
196
+ const newConversation = value.newConversation ?? false;
197
+ if ((errorCode !== null && typeof errorCode !== "string")
198
+ || (chatSessionId !== null && typeof chatSessionId !== "string")
199
+ || (conversationId !== null && typeof conversationId !== "string")
200
+ || typeof newConversation !== "boolean") {
201
+ throw invalid();
202
+ }
203
+ return Object.freeze({
204
+ status: value.status,
205
+ errorCode,
206
+ chatSessionId,
207
+ conversationId,
208
+ newConversation,
162
209
  });
163
210
  }
@@ -36,6 +36,15 @@ export interface NotificationMessage {
36
36
  * mobile push, email) are enabled; without one, all of them are.
37
37
  */
38
38
  readonly channel?: string;
39
+ /**
40
+ * Notification categories the notification is filed under in the recipients' notification list, at most 10. Each
41
+ * entry is the `code` of a category (for example `"sales"`), which stays the same across workspaces, or a
42
+ * category record ID. Duplicates are ignored, and so are entries that do not name an active category of the
43
+ * workspace; when none is left, the `system` category is used. Without categories, the workspace's own category
44
+ * settings apply. Categories only group notifications in the list, unlike `channel`, which decides how they are
45
+ * delivered.
46
+ */
47
+ readonly categories?: readonly string[];
39
48
  /** Whether to include an email copy for channels that enable email. Defaults to `true`. */
40
49
  readonly email?: boolean;
41
50
  /** A retry with the same key returns the first result instead of notifying again. */
@@ -8,12 +8,14 @@ const MAX_SUBTITLE_CHARS = 200;
8
8
  const MAX_CONTENT_CHARS = 16_384;
9
9
  const MAX_LINK_CHARS = 2_048;
10
10
  const CHANNEL_ID = /^[A-Za-z0-9_-]{1,64}$/u;
11
+ const MAX_CATEGORIES = 10;
12
+ const CATEGORY = /^[A-Za-z0-9_-]{1,64}$/u;
11
13
  // The sandbox has no WHATWG `URL` global, so the shape is checked with a pattern; Cogover parses it again.
12
14
  const HTTP_URL = /^https?:\/\/[^\s/?#\\@]+(?:[/?#]\S*)?$/iu;
13
15
  const APP_PATH = /^\/(?!\/)[^\s\\]*$/u;
14
16
  const MESSAGE_KEYS = new Set([
15
17
  "to", "exclude", "title", "content", "contentType", "subtitle", "display", "link", "sender", "channel",
16
- "email", "idempotencyKey",
18
+ "categories", "email", "idempotencyKey",
17
19
  ]);
18
20
  const LINK_KEYS = new Set(["url", "openIn"]);
19
21
  const CONTENT_TYPES = new Set(["text", "html"]);
@@ -73,6 +75,11 @@ function notificationPayload(message) {
73
75
  }
74
76
  payload.channel = input.channel;
75
77
  }
78
+ if (input.categories !== undefined) {
79
+ const categories = notificationCategories(input.categories);
80
+ if (categories.length > 0)
81
+ payload.categories = categories;
82
+ }
76
83
  const email = optionalBoolean(input.email, "email");
77
84
  if (email !== undefined)
78
85
  payload.email = email;
@@ -81,6 +88,23 @@ function notificationPayload(message) {
81
88
  payload.idempotencyKey = idempotencyKey;
82
89
  return payload;
83
90
  }
91
+ /** Category codes or record IDs in order without duplicates. */
92
+ function notificationCategories(value) {
93
+ if (!Array.isArray(value))
94
+ throw new ValidationError("categories must be a list of category codes or record IDs");
95
+ if (value.length > MAX_CATEGORIES) {
96
+ throw new ValidationError(`categories must not list more than ${MAX_CATEGORIES} entries`);
97
+ }
98
+ const categories = new Set();
99
+ for (const entry of value) {
100
+ if (typeof entry !== "string" || !CATEGORY.test(entry)) {
101
+ throw new ValidationError("categories must only contain category codes or record IDs of 1 to 64 letters, "
102
+ + "digits, '_' or '-'");
103
+ }
104
+ categories.add(entry);
105
+ }
106
+ return [...categories];
107
+ }
84
108
  function notificationLink(value) {
85
109
  const link = requireKnownKeys(value, LINK_KEYS, "link");
86
110
  const url = requiredText(link.url, "link.url", MAX_LINK_CHARS);
@@ -34,6 +34,7 @@ interface NotificationMessage {
34
34
  readonly link?: NotificationLink;
35
35
  readonly sender?: NotificationSender;
36
36
  readonly channel?: string;
37
+ readonly categories?: readonly string[];
37
38
  readonly email?: boolean;
38
39
  readonly idempotencyKey?: string;
39
40
  }
@@ -58,6 +59,7 @@ const result = await notifications.send({
58
59
  content: "A leave request of 3 days was submitted and needs your decision.",
59
60
  link: { url: `/app/leave_request/${recordId}` },
60
61
  channel: approvalChannelId,
62
+ categories: ["process"],
61
63
  idempotencyKey: `leave-approval:${recordId}`,
62
64
  });
63
65
  // result.notified: accounts addressed; result.skippedPersonnelIds: personnel without an account
@@ -105,6 +107,20 @@ enabled. An unknown channel throws `NotFoundError` with `resource`
105
107
  `"notificationChannel"`; a workspace in which notifications are not set up throws
106
108
  `NotFoundError` with `resource` `"object"` and `resourceId` `"notification_channel"`.
107
109
 
110
+ **Categories.** `categories` files the notification under up to 10 notification
111
+ categories of the workspace, which recipients use to filter their notification list.
112
+ Each entry is the `code` of a category, such as `"process"`, `"sales"`, or `"system"`,
113
+ or the record ID of a category; a code stays the same in every workspace that has
114
+ the category, while a record ID belongs to one workspace. Each entry has 1 to 64
115
+ letters, digits, `_`, or `-`; duplicates are removed, and an empty list is the same as
116
+ leaving the option out. Categories only group notifications in the list and do not
117
+ change how they are delivered, which is what `channel` decides. Cogover does not
118
+ check the entries when you call `send`: entries that do not name an active category
119
+ of the workspace are ignored, and when none is left the notification is filed under
120
+ the active `system` category. Without `categories`, the categories the workspace
121
+ assigns to notifications of this kind are used, again falling back to `system`. A
122
+ workspace without notification categories saves the notification without one.
123
+
108
124
  `email: false` leaves out the email copy even when the channel enables email. The
109
125
  copy uses `title` as its subject and `content` as its body, is sent from a Cogover
110
126
  notification address rather than from a workspace mailbox, and counts against the
@@ -125,7 +125,10 @@ automation budget is used up, `IDEMPOTENCY_CONFLICT` when another identity of th
125
125
  project already used the `idempotencyKey`, `AGENT_DEPTH_EXCEEDED` when AI Agents would
126
126
  start one another too deeply,
127
127
  `NOT_SUPPORTED` for `onComplete` or `onResult` in a local development session, and
128
- `PROCESSES_DISABLED` or `AGENTS_DISABLED` when the feature is not available. A Process
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
129
132
  node or an AI Agent that calls a Custom Module Action receives the errors described in
130
133
  [Errors seen by the caller](actions.md#errors-seen-by-the-caller).
131
134
 
@@ -183,6 +183,7 @@ interface AgentStartOptions {
183
183
  readonly timeoutSeconds?: number;
184
184
  readonly idempotencyKey?: string;
185
185
  readonly onResult?: AgentResultCompletion;
186
+ readonly deliverTo?: AgentDeliveryTarget;
186
187
  }
187
188
 
188
189
  interface AgentRecordReference {
@@ -196,6 +197,12 @@ interface AgentResultCompletion {
196
197
  readonly payload?: unknown;
197
198
  }
198
199
 
200
+ interface AgentDeliveryTarget {
201
+ readonly personnelId: string;
202
+ readonly conversation?: "new" | "latest";
203
+ readonly title?: string;
204
+ }
205
+
199
206
  interface AgentStartResult {
200
207
  readonly runId: string;
201
208
  readonly duplicate: boolean;
@@ -214,7 +221,8 @@ const { runId } = await agents.start("AGXXXXXXXXXXXX", {
214
221
  ```
215
222
 
216
223
  `agentId` is the ID of an AI Agent: 1 to 64 letters, digits, `_`, or `-`. Each run
217
- starts a new conversation of the agent.
224
+ works in a new session of its own, which no person sees; `deliverTo` is how a run
225
+ reaches a person.
218
226
 
219
227
  | Option | Rules and meaning |
220
228
  |---|---|
@@ -227,11 +235,59 @@ starts a new conversation of the agent.
227
235
  | `timeoutSeconds` | Integer from 10 through 1800; defaults to `300`. Time limit of the run. |
228
236
  | `idempotencyKey` | Same rules as for `processes.start`. |
229
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). |
230
239
 
231
240
  The result is the `runId` of the new run, and `duplicate: true` when an earlier start
232
241
  with the same `idempotencyKey` returned that run instead. Invalid arguments throw
233
242
  `ValidationError` before anything is sent.
234
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
+
235
291
  ### `agents.get(runId): Promise<AgentRunState>`
236
292
 
237
293
  ```typescript
@@ -241,6 +297,15 @@ interface AgentRunState<TResult = unknown> {
241
297
  readonly text: string | null;
242
298
  readonly result: TResult | null;
243
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;
244
309
  }
245
310
  ```
246
311
 
@@ -252,11 +317,42 @@ such as `COMPLETED`, `FAILED`, `TIMEOUT`, or `CANCELLED`. `text` is the agent's
252
317
  `GUARDRAIL_REJECTED`, `APPROVAL_DENIED`, `SERVER_RESTARTED`, `SESSION_BUSY`,
253
318
  `SESSION_EVICTED`, `AGENT_INACTIVE`, `AGENT_ACCESS_DENIED`, `AGENT_CONFIG_INVALID`,
254
319
  `CONFIG_LOAD_FAILED`, `LLM_HTTP_ERROR`, `LLM_NETWORK`, `LLM_RESPONSE_FAILED`, `LLM_PARSE`,
255
- `OUTPUT_TRUNCATED`, `INTERNAL_ERROR`, or `AGENT_ERROR` for any other reason, and
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
256
324
  `error.message` is a fixed English description of that code: the text of the AI model
257
325
  provider is never passed on. The `onResult` job receives the same `error`. A run that
258
326
  this project did not start throws `NotFoundError`.
259
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
+
260
356
  ### Agent result job
261
357
 
262
358
  ```typescript
@@ -269,14 +365,28 @@ interface AgentResultJobPayload<TPayload = unknown, TResult = unknown> {
269
365
  readonly result: TResult | null;
270
366
  readonly error: { readonly code: string; readonly message: string } | null;
271
367
  readonly usage: Record<string, unknown> | null;
368
+ readonly delivery: AgentDelivery | null;
272
369
  };
273
370
  }
274
371
  ```
275
372
 
276
373
  When a run started with `onResult` ends, Cogover enqueues one run of the job with this
277
374
  value as its `payload`: `payload` is `onResult.payload` (or `null`), `agentRun.text` is
278
- cut to 32 KiB, `agentRun.result` is `null` when it takes more than 16 KiB, and
279
- `agentRun.usage` reports `inputTokens`, `outputTokens`, `iterations`, and `durationMs`.
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
+ ```
280
390
 
281
391
  ### Completion jobs
282
392
 
@@ -305,12 +415,17 @@ cut to 32 KiB, `agentRun.result` is `null` when it takes more than 16 KiB, and
305
415
  another user of the project, or an execution without a user, that sends the same key
306
416
  receives `CogoverApiError` with `code: "IDEMPOTENCY_CONFLICT"`, never the other
307
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.
308
422
  - `RetryableError` reports a temporary failure. When `details.writesMayHaveCompleted` is
309
423
  `false`, nothing was started. When it is `true`, the instance or run may have been
310
424
  created: retry later with the same `idempotencyKey`, and Cogover completes that start
311
425
  instead of creating a second one; a retry that comes too soon may throw
312
- `RetryableError` again. After a definite refusal, such as `ValidationError` or
313
- `PermissionDeniedError`, the key can be used again.
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.
314
429
  - In a job, a key derived from the job's `payload` or `job.id`, and in an action from
315
430
  `action.runId`, keeps a retried handler from starting the same work twice.
316
431
 
@@ -332,6 +447,9 @@ cut to 32 KiB, `agentRun.result` is `null` when it takes more than 16 KiB, and
332
447
  `code: "AGENT_DEPTH_EXCEEDED"`.
333
448
  - A `"read"` action and a read-only local development session can call `get` but not
334
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)).
335
453
 
336
454
  ### Errors
337
455
 
@@ -345,13 +463,40 @@ cut to 32 KiB, `agentRun.result` is `null` when it takes more than 16 KiB, and
345
463
  | `CogoverApiError` | `MAX_HOP_EXCEEDED` | The automation budget is used up. |
346
464
  | `CogoverApiError` | `IDEMPOTENCY_CONFLICT` | Another identity of the project already used this `idempotencyKey`. |
347
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. |
348
475
  | `CogoverApiError` | `NOT_SUPPORTED` | `onComplete` or `onResult` in a local development session. |
349
476
  | `CogoverApiError` | `PROCESSES_DISABLED`, `AGENTS_DISABLED` | The feature is not available in this environment. |
350
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
+
351
494
  ### Local development
352
495
 
353
496
  When code runs locally with Cogover Dev CLI, `start` creates real Process instances and
354
- agent runs, as the user of the Project key, and a read-only session refuses it.
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.
355
500
  `onComplete` and `onResult` are refused with `CogoverApiError` `code: "NOT_SUPPORTED"`,
356
501
  because their job runs only in a published version: test the start without them and
357
502
  read the outcome with `get`, then publish the project to test the job.
@@ -711,8 +711,16 @@ export const jobs = [
711
711
  a daily limit of agent runs (`maxRunsPerDay`, 200 by default).
712
712
  - `processes.get` and `agents.get` read the current state of a run the project
713
713
  started. Do not wait for the result inside a route: use the job.
714
- - With Cogover Dev CLI, starts are real, but `onComplete` and `onResult` are refused
715
- with `NOT_SUPPORTED`; test the job after publishing.
714
+ - To let an agent write to a person on its own, add
715
+ `deliverTo: { personnelId, conversation: "new" | "latest" }` to `agents.start`. The agent
716
+ can then send a chat message to that personnel in the AI chat of the agent, and the run
717
+ reports the outcome as `delivery` (`SENT`, `NOT_SENT`, `BLOCKED`, or `FAILED`) in
718
+ `agents.get` and in the `onResult` job. The recipient must be allowed to use the agent
719
+ and have an AI Agent seat; otherwise `start` throws `CogoverApiError` with a
720
+ `RECIPIENT_...` code.
721
+ - With Cogover Dev CLI, starts are real, and so is a message sent through `deliverTo`,
722
+ but `onComplete` and `onResult` are refused with `NOT_SUPPORTED`; test the job after
723
+ publishing.
716
724
 
717
725
  See the [Process and AI Agent reference](api-reference/processes-and-agents.md#processes-and-ai-agents)
718
726
  for every option, limit, and error.
@@ -762,6 +770,8 @@ export const triggers = [
762
770
  content: "A leave request was submitted and needs your decision.",
763
771
  link: { url: `/app/leave_request/${record.id}` },
764
772
  channel: APPROVAL_CHANNEL,
773
+ // Category code: the same in every workspace, unlike the channel record ID.
774
+ categories: ["process"],
765
775
  // The same change of the same record always produces the same key.
766
776
  idempotencyKey: `leave-approval:${trigger.changeId}:${record.id}`,
767
777
  });
@@ -779,6 +789,11 @@ export const triggers = [
779
789
  `email: false` to never send the email copy. The copy comes from a Cogover
780
790
  notification address and counts against the workspace plan's daily
781
791
  notification-email limit.
792
+ - `categories` files the notification under up to 10 notification categories, which
793
+ recipients use to filter their notification list. Pass category codes such as
794
+ `"process"` or `"sales"` (or category record IDs); unknown or inactive categories
795
+ are ignored, and without usable categories the notification goes to `system`.
796
+ Categories do not change delivery, which `channel` decides.
782
797
  - `link.url` is a path of the web app starting with `/` or an absolute `http(s)`
783
798
  URL. `contentType: "html"` keeps only basic formatting such as paragraphs, lists,
784
799
  tables, and links.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.15.0",
3
+ "version": "0.17.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,