@cogover/sdk 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.
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
  }
@@ -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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,