@cogover/sdk 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,8 +46,8 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
46
46
  ```
47
47
 
48
48
  `defineScript` parses the input JSON, provides invocation metadata and scoped
49
- data, schema, logging, state, lock, push, notification, email, job, secret, and
50
- crypto APIs, waits for the async handler, and serializes its result. Cogover
49
+ data, schema, logging, state, lock, push, notification, email, job, secret, crypto,
50
+ Process, and AI Agent APIs, waits for the async handler, and serializes its result. Cogover
51
51
  authentication credentials are not exposed to project code, and Cogover enforces
52
52
  the configured permissions and the per-execution limits on capability calls and
53
53
  records. `limits.usage()` (also `context.limits`) reports how much of each budget
@@ -249,7 +249,8 @@ export const jobs = [
249
249
 
250
250
  A job handler receives `job` (run ID, key, attempt, source), the `payload` passed
251
251
  to `enqueue` or `null`, and the same `data`, `schema`, `log`, `state`, `locks`,
252
- `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` APIs as a script.
252
+ `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, `processes`, and `agents` APIs as
253
+ a script.
253
254
  Runs are delivered at least once and retried with growing delays when the handler
254
255
  throws `RetryableError` or times out, up to `maxAttempts` (default 5) attempts;
255
256
  other errors fail the run. A run
@@ -257,6 +258,72 @@ enqueued from a route acts as that route's user, while a scheduled run uses the
257
258
  system identity. `jobs.enqueue(key, payload?, { delayMs?, runAt?, idempotencyKey? })`
258
259
  returns `{ runId, duplicate }`.
259
260
 
261
+ ## Custom Module Actions, Processes, and AI Agents
262
+
263
+ A **Custom Module Action** lets a Cogover Process (a **Custom Module Action** node) or an
264
+ AI Agent (a **Custom Module** tool) call the module. Declare actions with
265
+ `defineAction`, describe their input and output with the `s` schema builder, and list
266
+ them in the named `actions` export. Cogover checks the input before the handler runs and
267
+ the output after it returns; an action runs for at most 8 seconds.
268
+
269
+ ```typescript
270
+ import { defineAction, s } from "@cogover/sdk";
271
+
272
+ export const actions = [
273
+ defineAction({
274
+ key: "score_lead",
275
+ label: "Score lead",
276
+ description: "Scores a lead from its rating and returns a tier.",
277
+ exposeTo: ["process", "agent"],
278
+ effect: "read",
279
+ input: s.object({ leadId: s.recordId("lead").describe("ID of the lead to score") }),
280
+ output: s.object({ found: s.boolean(), tier: s.enum(["A", "B", "C"]) }),
281
+ async handler({ data }, input) {
282
+ const lead = await data.object("lead").records.get(input.leadId, { fields: ["rating"] });
283
+ if (!lead) return { found: false, tier: "C" };
284
+ const rating = Number(lead.fields.rating ?? 0);
285
+ return { found: true, tier: rating >= 8 ? "A" : rating >= 5 ? "B" : "C" };
286
+ },
287
+ }),
288
+ ];
289
+ ```
290
+
291
+ In the other direction, `processes.start` starts a Process and `agents.start` runs an AI
292
+ Agent from a route, an after-change trigger, a job, or an action. Both return once the
293
+ run is created, and the outcome is delivered to a background job:
294
+
295
+ ```typescript
296
+ const { instanceId } = await processes.start("PIXXXXXXXXXXXX", {
297
+ input: { quote_id: quoteId },
298
+ idempotencyKey: `quote-approval:${quoteId}`,
299
+ onComplete: { job: "quote_approved", payload: { quoteId } },
300
+ });
301
+
302
+ const { runId } = await agents.start("AGXXXXXXXXXXXX", {
303
+ instruction: "Classify this support ticket by product area.",
304
+ records: [{ objectSlug: "ticket", recordId: ticketId }],
305
+ resultSchema: s.object({ area: s.enum(["billing", "shipping", "product"]) }),
306
+ onResult: { job: "ticket_classified", payload: { ticketId } },
307
+ });
308
+ ```
309
+
310
+ The Project's approved identity policy lists the Processes and AI Agents the module may
311
+ use (`processes` and `agents` sections). `processes.get(instanceId)` and
312
+ `agents.get(runId)` read the state of a run the module started. One execution may start
313
+ at most 20 Processes and 5 agent runs.
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
+
260
327
  ## Outbound HTTP with `fetch`
261
328
 
262
329
  Cogover provides a Fetch-compatible function for calling an external HTTPS API.
@@ -0,0 +1,86 @@
1
+ import type { CogoverRecordId } from "./records.js";
2
+ declare const schemaValue: unique symbol;
3
+ declare const schemaOptional: unique symbol;
4
+ declare const schemaShape: unique symbol;
5
+ type JsonSchemaValue = null | boolean | number | string | readonly JsonSchemaValue[] | JsonSchema;
6
+ /** A JSON Schema document as plain JSON data. */
7
+ export interface JsonSchema {
8
+ readonly [keyword: string]: JsonSchemaValue;
9
+ }
10
+ /**
11
+ * An immutable schema node created by `s`. It describes a value of type `T`; `Optional` is `true` after
12
+ * `.optional()`. `JSON.stringify(node)` returns its JSON Schema.
13
+ */
14
+ export interface Schema<T = unknown, Optional extends boolean = false> {
15
+ readonly [schemaValue]: T;
16
+ readonly [schemaOptional]: Optional;
17
+ /** Returns a node whose property may be left out of the object that contains it. */
18
+ optional(): Schema<T, true>;
19
+ /** Returns a node with a description of 1 to 500 characters, stored trimmed. */
20
+ describe(text: string): Schema<T, Optional>;
21
+ /** The JSON Schema of the node. */
22
+ toJSON(): JsonSchema;
23
+ }
24
+ /** Property schemas of `s.object`, in declaration order. */
25
+ export type ObjectShape = {
26
+ readonly [property: string]: Schema<unknown, boolean>;
27
+ };
28
+ type Simplify<T> = {
29
+ [K in keyof T]: T[K];
30
+ } & {};
31
+ type ShapeValue<Shape extends ObjectShape> = Simplify<{
32
+ [K in keyof Shape as Shape[K] extends Schema<unknown, true> ? never : K]: InferSchema<Shape[K]>;
33
+ } & {
34
+ [K in keyof Shape as Shape[K] extends Schema<unknown, true> ? K : never]?: InferSchema<Shape[K]>;
35
+ }>;
36
+ /** A schema node created by `s.object`. */
37
+ export interface ObjectSchema<Shape extends ObjectShape = ObjectShape, Optional extends boolean = false> extends Schema<ShapeValue<Shape>, Optional> {
38
+ readonly [schemaShape]: Shape;
39
+ optional(): ObjectSchema<Shape, true>;
40
+ describe(text: string): ObjectSchema<Shape, Optional>;
41
+ }
42
+ /** The TypeScript type of the values a schema node describes. */
43
+ export type InferSchema<T> = T extends Schema<infer Value, boolean> ? Value : never;
44
+ /**
45
+ * Builds schemas that describe values as TypeScript types and as JSON Schema at the same time. An invalid argument
46
+ * throws `ValidationError`.
47
+ */
48
+ export declare const s: Readonly<{
49
+ /**
50
+ * A string; `maxLength` defaults to 10000 and may be 1 to 100000. There is no `pattern` option: check a format
51
+ * (for example with a regular expression) in the handler.
52
+ */
53
+ string(options?: {
54
+ readonly minLength?: number;
55
+ readonly maxLength?: number;
56
+ }): Schema<string>;
57
+ /** One of 1 to 100 distinct strings of 1 to 200 characters. */
58
+ enum<const Values extends readonly string[]>(values: Values): Schema<Values[number]>;
59
+ /** A finite number. */
60
+ number(options?: {
61
+ readonly minimum?: number;
62
+ readonly maximum?: number;
63
+ }): Schema<number>;
64
+ /** A safe integer. */
65
+ integer(options?: {
66
+ readonly minimum?: number;
67
+ readonly maximum?: number;
68
+ }): Schema<number>;
69
+ boolean(): Schema<boolean>;
70
+ /** A calendar date as a `YYYY-MM-DD` string. */
71
+ date(): Schema<string>;
72
+ /** A point in time in Unix milliseconds. */
73
+ dateTime(): Schema<number>;
74
+ /**
75
+ * The ID of a record of the Object `objectSlug`, typed as `CogoverRecordId` so that it can be passed to the
76
+ * records API without a cast. Cogover does not check that the record exists.
77
+ */
78
+ recordId(objectSlug: string): Schema<CogoverRecordId>;
79
+ /** A list of `item` values; `maxItems` defaults to 1000 and may be 1 to 10000. */
80
+ array<Item extends Schema<unknown, false>>(item: Item, options?: {
81
+ readonly maxItems?: number;
82
+ }): Schema<InferSchema<Item>[]>;
83
+ /** An object with exactly these properties; at most 50, named like `leadId`. */
84
+ object<Shape extends ObjectShape>(shape: Shape): ObjectSchema<Shape>;
85
+ }>;
86
+ export {};
@@ -0,0 +1,52 @@
1
+ import { arraySchema, booleanSchema, dateSchema, dateTimeSchema, enumSchema, numberSchema, objectSchema, recordIdSchema, stringSchema, } from "./internal/schema-nodes.js";
2
+ /**
3
+ * Builds schemas that describe values as TypeScript types and as JSON Schema at the same time. An invalid argument
4
+ * throws `ValidationError`.
5
+ */
6
+ export const s = Object.freeze({
7
+ /**
8
+ * A string; `maxLength` defaults to 10000 and may be 1 to 100000. There is no `pattern` option: check a format
9
+ * (for example with a regular expression) in the handler.
10
+ */
11
+ string(options) {
12
+ return stringSchema(options);
13
+ },
14
+ /** One of 1 to 100 distinct strings of 1 to 200 characters. */
15
+ enum(values) {
16
+ return enumSchema(values);
17
+ },
18
+ /** A finite number. */
19
+ number(options) {
20
+ return numberSchema(options, false);
21
+ },
22
+ /** A safe integer. */
23
+ integer(options) {
24
+ return numberSchema(options, true);
25
+ },
26
+ boolean() {
27
+ return booleanSchema();
28
+ },
29
+ /** A calendar date as a `YYYY-MM-DD` string. */
30
+ date() {
31
+ return dateSchema();
32
+ },
33
+ /** A point in time in Unix milliseconds. */
34
+ dateTime() {
35
+ return dateTimeSchema();
36
+ },
37
+ /**
38
+ * The ID of a record of the Object `objectSlug`, typed as `CogoverRecordId` so that it can be passed to the
39
+ * records API without a cast. Cogover does not check that the record exists.
40
+ */
41
+ recordId(objectSlug) {
42
+ return recordIdSchema(objectSlug);
43
+ },
44
+ /** A list of `item` values; `maxItems` defaults to 1000 and may be 1 to 10000. */
45
+ array(item, options) {
46
+ return arraySchema(item, options);
47
+ },
48
+ /** An object with exactly these properties; at most 50, named like `leadId`. */
49
+ object(shape) {
50
+ return objectSchema(shape);
51
+ },
52
+ });
@@ -0,0 +1,129 @@
1
+ import type { InferSchema, JsonSchema, ObjectSchema, ObjectShape } from "./action-schema.js";
2
+ import type { AgentsApi } from "./agents.js";
3
+ import type { CryptoApi } from "./crypto.js";
4
+ import type { DataApi } from "./data.js";
5
+ import type { EmailApi } from "./email.js";
6
+ import type { SystemInvocationContext, UserInvocationContext } from "./invocation.js";
7
+ import type { JobsApi } from "./jobs.js";
8
+ import type { LimitsApi } from "./limits.js";
9
+ import type { DistributedLocks } from "./locks.js";
10
+ import type { ScriptLogger } from "./logger.js";
11
+ import type { NotificationsApi } from "./notifications.js";
12
+ import type { OrgApi } from "./org.js";
13
+ import type { ProcessesApi } from "./processes.js";
14
+ import type { PushApi } from "./push.js";
15
+ import type { SchemaApi } from "./schema.js";
16
+ import type { SecretsApi } from "./secrets.js";
17
+ import type { ProjectState } from "./state.js";
18
+ import type { EffectiveWorkspaceObjects } from "./workspace.js";
19
+ /** Where an action can be used: a Process node or an AI Agent tool. */
20
+ export type ActionExposure = "process" | "agent";
21
+ /** `"read"` actions cannot write data; `"write"` actions can. */
22
+ export type ActionEffect = "read" | "write";
23
+ /**
24
+ * How the Process node chose the identity the action runs as: the person who started the process, a person the
25
+ * node names, or the system identity. `null` when the caller did not say.
26
+ */
27
+ export type ProcessActionRunAs = "PROCESS_STARTER" | "PERSONNEL" | "SYSTEM";
28
+ /** A Process instance ran the action from one of its nodes. */
29
+ export interface ProcessActionSource {
30
+ readonly type: "process";
31
+ readonly processId: string;
32
+ readonly processInfoId: string;
33
+ readonly instanceId: string;
34
+ readonly nodeId: string;
35
+ readonly runAs: ProcessActionRunAs | null;
36
+ }
37
+ /** An AI Agent called the action as a tool. */
38
+ export interface AgentActionSource {
39
+ readonly type: "agent";
40
+ readonly agentId: string;
41
+ /** Chat session of the agent, or `null` outside a session. */
42
+ readonly sessionId: string | null;
43
+ /** Agent run, or `null` when the agent was not started as a run. */
44
+ readonly runId: string | null;
45
+ /** Whether a person is chatting with the agent. */
46
+ readonly interactive: boolean;
47
+ /**
48
+ * Personnel ID of the person chatting with the agent, or of the person who started the agent run; `null` when
49
+ * there is none. The action still runs as the agent's identity: use this ID to decide what that person may do.
50
+ */
51
+ readonly initiatorPersonnelId: string | null;
52
+ }
53
+ export type ActionSource = ProcessActionSource | AgentActionSource;
54
+ /** Identity, workspace and caller of the current action call. */
55
+ export type ActionInvocationContext = (UserInvocationContext | SystemInvocationContext) & {
56
+ /** `"user"` when the action runs as a user of the workspace, `"system"` otherwise. */
57
+ readonly executionIdentity: "user" | "system";
58
+ readonly source: ActionSource;
59
+ };
60
+ /** Identifies the action call. */
61
+ export interface ActionInfo {
62
+ readonly key: string;
63
+ /** Identifies this call. */
64
+ readonly runId: string;
65
+ readonly effect: ActionEffect;
66
+ }
67
+ export interface ActionContext<TSchema extends object = EffectiveWorkspaceObjects> {
68
+ readonly action: ActionInfo;
69
+ readonly invocation: ActionInvocationContext;
70
+ readonly data: DataApi<TSchema>;
71
+ readonly schema: SchemaApi<TSchema>;
72
+ readonly log: ScriptLogger;
73
+ readonly state: ProjectState;
74
+ readonly locks: DistributedLocks;
75
+ readonly push: PushApi<TSchema>;
76
+ readonly notifications: NotificationsApi;
77
+ readonly email: EmailApi<TSchema>;
78
+ readonly jobs: JobsApi;
79
+ readonly secrets: SecretsApi;
80
+ readonly crypto: CryptoApi;
81
+ readonly org: OrgApi;
82
+ /** Budgets of this execution; reading them is not a Cogover call. */
83
+ readonly limits: LimitsApi;
84
+ readonly processes: ProcessesApi;
85
+ readonly agents: AgentsApi;
86
+ }
87
+ /** Receives the input, already checked against the input schema, and returns the output. */
88
+ export type ActionHandler<TInput extends ObjectSchema<ObjectShape, false> = ObjectSchema<ObjectShape, false>, TOutput extends ObjectSchema<ObjectShape, false> = ObjectSchema<ObjectShape, false>, TSchema extends object = EffectiveWorkspaceObjects> = (context: ActionContext<TSchema>, input: InferSchema<TInput>) => InferSchema<TOutput> | Promise<InferSchema<TOutput>>;
89
+ type InferredActionHandler<TInput extends ObjectSchema<ObjectShape, false>, TOutput extends ObjectSchema<ObjectShape, false>, TSchema extends object> = [TInput, TOutput] extends [unknown, unknown] ? ActionHandler<TInput, TOutput, TSchema> : never;
90
+ /** Options accepted by `defineAction`. */
91
+ export interface ActionConfig<TInput extends ObjectSchema<ObjectShape, false> = ObjectSchema<ObjectShape, false>, TOutput extends ObjectSchema<ObjectShape, false> = ObjectSchema<ObjectShape, false>, TSchema extends object = EffectiveWorkspaceObjects> {
92
+ /** Stable identifier of the action inside the project. */
93
+ readonly key: string;
94
+ /** Name shown in Process Builder and AI Agent Builder, 1 to 100 characters. */
95
+ readonly label: string;
96
+ /** At most 1000 characters; required when `exposeTo` includes `"agent"`. */
97
+ readonly description?: string;
98
+ readonly exposeTo: readonly ActionExposure[];
99
+ readonly effect: ActionEffect;
100
+ /** Schema of the input, created with `s.object`. */
101
+ readonly input: TInput;
102
+ /** Schema of the output, created with `s.object`. */
103
+ readonly output: TOutput;
104
+ /** Time budget of one call, 1000 to 8000 milliseconds; defaults to 8000. */
105
+ readonly timeoutMs?: number;
106
+ readonly handler: InferredActionHandler<TInput, TOutput, TSchema>;
107
+ }
108
+ /** Normalized, immutable action configuration with every default applied. */
109
+ export interface ActionManifest {
110
+ readonly key: string;
111
+ readonly label: string;
112
+ /** `""` when the action has no description. */
113
+ readonly description: string;
114
+ readonly exposeTo: readonly ActionExposure[];
115
+ readonly effect: ActionEffect;
116
+ readonly timeoutMs: number;
117
+ readonly inputSchema: JsonSchema;
118
+ readonly outputSchema: JsonSchema;
119
+ }
120
+ /** Result of `defineAction`; list it in the project's `actions` export. */
121
+ export interface ActionDefinition {
122
+ readonly key: string;
123
+ readonly config: ActionManifest;
124
+ /** Reserved for Cogover; project code does not call it. */
125
+ readonly __cogoverActionHandler: (inputJson: string) => Promise<string>;
126
+ }
127
+ /** Declares an action for Processes and AI Agents. Add the result to the project's `actions` export. */
128
+ export declare function defineAction<TInput extends ObjectSchema<ObjectShape, false>, TOutput extends ObjectSchema<ObjectShape, false>, TSchema extends object = EffectiveWorkspaceObjects>(config: ActionConfig<TInput, TOutput, TSchema>): ActionDefinition;
129
+ export {};
@@ -0,0 +1,11 @@
1
+ import { normalizeActionConfig } from "./internal/action-config.js";
2
+ import { createActionSandboxHandler } from "./internal/action-runtime.js";
3
+ /** Declares an action for Processes and AI Agents. Add the result to the project's `actions` export. */
4
+ export function defineAction(config) {
5
+ const { manifest, handler } = normalizeActionConfig(config);
6
+ return Object.freeze({
7
+ key: manifest.key,
8
+ config: manifest,
9
+ __cogoverActionHandler: createActionSandboxHandler(manifest, handler),
10
+ });
11
+ }
@@ -0,0 +1,112 @@
1
+ import type { ObjectSchema, ObjectShape } from "./action-schema.js";
2
+ /** A record the agent reads as context. */
3
+ export interface AgentRecordReference {
4
+ readonly objectSlug: string;
5
+ readonly recordId: string;
6
+ /** Also gives the agent the record's activities. */
7
+ readonly withActivities?: boolean;
8
+ }
9
+ /** Runs a background job of the project when the agent run ends. */
10
+ export interface AgentResultCompletion {
11
+ /** Key of a job of the project's `jobs` export. */
12
+ readonly job: string;
13
+ /** JSON value of at most 8192 UTF-8 bytes handed to the job as `payload`. */
14
+ readonly payload?: unknown;
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
+ }
47
+ /** Options of `agents.start`. */
48
+ export interface AgentStartOptions {
49
+ /** What the agent must do, 1 to 20000 characters. */
50
+ readonly instruction: string;
51
+ /** At most 50 named values; a string value has at most 4000 characters. */
52
+ readonly variables?: Readonly<Record<string, string | number | boolean>>;
53
+ /** At most 20 records the agent reads as context. */
54
+ readonly records?: readonly AgentRecordReference[];
55
+ /** Shape of a structured result, created with `s.object`. */
56
+ readonly resultSchema?: ObjectSchema<ObjectShape, false>;
57
+ /** `"caller"` (default) runs with the identity of this execution, `"agent"` with the agent's own identity. */
58
+ readonly runAs?: "caller" | "agent";
59
+ /** `"deny"` (default) refuses tools that need approval; `"autoApprove"` approves them. */
60
+ readonly approvalPolicy?: "deny" | "autoApprove";
61
+ /** Time budget of the run, 10 to 1800 seconds; defaults to 300. */
62
+ readonly timeoutSeconds?: number;
63
+ /** A second start with the same key in the same project returns the first run instead of a new one. */
64
+ readonly idempotencyKey?: string;
65
+ /** Job that receives the outcome of the run. */
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;
69
+ }
70
+ export interface AgentStartResult {
71
+ readonly runId: string;
72
+ /** `true` when an earlier start with the same `idempotencyKey` was found; `runId` is that run. */
73
+ readonly duplicate: boolean;
74
+ }
75
+ /** Current state of an agent run. */
76
+ export interface AgentRunState<TResult = unknown> {
77
+ readonly runId: string;
78
+ readonly status: string;
79
+ /** Text answer of the agent, or `null` when there is none yet. */
80
+ readonly text: string | null;
81
+ /** Structured result that matches `resultSchema`, or `null`. */
82
+ readonly result: TResult | null;
83
+ readonly error: {
84
+ readonly code: string;
85
+ readonly message: string;
86
+ } | null;
87
+ /** Outcome of `deliverTo`; `null` for a run started without it, and possibly until the run ends. */
88
+ readonly delivery: AgentDelivery | null;
89
+ }
90
+ /** Starts AI Agent runs and reads their state. The result of a run is delivered to a background job. */
91
+ export interface AgentsApi {
92
+ start(agentId: string, options: AgentStartOptions): Promise<AgentStartResult>;
93
+ get<TResult = unknown>(runId: string): Promise<AgentRunState<TResult>>;
94
+ }
95
+ /** The `payload` of the job named by `onResult` when the agent run ends. */
96
+ export interface AgentResultJobPayload<TPayload = unknown, TResult = unknown> {
97
+ /** `onResult.payload`, or `null` when there was none. */
98
+ readonly payload: TPayload | null;
99
+ readonly agentRun: {
100
+ readonly runId: string;
101
+ readonly status: string;
102
+ readonly text: string | null;
103
+ readonly result: TResult | null;
104
+ readonly error: {
105
+ readonly code: string;
106
+ readonly message: string;
107
+ } | null;
108
+ readonly usage: Record<string, unknown> | null;
109
+ /** Outcome of `deliverTo`; `null` for a run started without it. */
110
+ readonly delivery: AgentDelivery | null;
111
+ };
112
+ }
package/dist/agents.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -12,6 +12,12 @@ export { defineTrigger } from "./trigger.js";
12
12
  export type { TriggerTiming, TriggerOperation, TriggerRunWhen, TriggerFilterCondition, TriggerFilterGroup, TriggerFilter, TriggerConfig, TriggerManifest, TriggerSandboxHandler, TriggerDefinition, TriggerInfo, TriggerNewValues, TriggerOldValues, TriggerRecord, TriggerContext, TriggerHandler, } from "./trigger.js";
13
13
  export { defineJob } from "./jobs.js";
14
14
  export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
15
+ export { defineAction } from "./actions.js";
16
+ export type { ActionExposure, ActionEffect, ActionConfig, ActionManifest, ActionDefinition, ActionHandler, ActionContext, ActionInfo, ActionInvocationContext, ActionSource, ProcessActionSource, ProcessActionRunAs, AgentActionSource, } from "./actions.js";
17
+ export { s } from "./action-schema.js";
18
+ export type { Schema, ObjectSchema, ObjectShape, InferSchema, JsonSchema, } from "./action-schema.js";
19
+ export type { ProcessesApi, ProcessStartOptions, ProcessStartResult, ProcessInstanceState, ProcessCompletion, ProcessCompletionJobPayload, } from "./processes.js";
20
+ export type { AgentsApi, AgentStartOptions, AgentStartResult, AgentRunState, AgentRecordReference, AgentResultCompletion, AgentResultJobPayload, AgentDeliveryTarget, AgentDelivery, } from "./agents.js";
15
21
  export type { SecretsApi } from "./secrets.js";
16
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";
17
23
  export { limits } from "./limits.js";
package/dist/index.js CHANGED
@@ -3,6 +3,8 @@ export { and, or } from "./query.js";
3
3
  export { defineScript } from "./script.js";
4
4
  export { defineTrigger } from "./trigger.js";
5
5
  export { defineJob } from "./jobs.js";
6
+ export { defineAction } from "./actions.js";
7
+ export { s } from "./action-schema.js";
6
8
  export { limits } from "./limits.js";
7
9
  export { crypto } from "./crypto.js";
8
10
  export { createRouter } from "./router.js";
@@ -0,0 +1,94 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { MAX_SCHEMA_BYTES, rootSchemaJson, schemaByteLength } from "./action-schema-rules.js";
3
+ import { cloneJson, deepFreeze } from "./json.js";
4
+ import { isRecord } from "./values.js";
5
+ export const ACTION_KEY = /^[a-z][a-z0-9_]{0,63}$/u;
6
+ const CONFIG_KEYS = new Set([
7
+ "key", "label", "description", "exposeTo", "effect", "input", "output", "timeoutMs", "handler",
8
+ ]);
9
+ const EXPOSURES = new Set(["process", "agent"]);
10
+ const EFFECTS = new Set(["read", "write"]);
11
+ const MAX_LABEL_LENGTH = 100;
12
+ const MAX_DESCRIPTION_LENGTH = 1000;
13
+ const MIN_TIMEOUT_MILLIS = 1000;
14
+ const MAX_TIMEOUT_MILLIS = 8000;
15
+ const DEFAULT_TIMEOUT_MILLIS = 8000;
16
+ /** Validates a defineAction() config and returns the frozen plain-JSON manifest with defaults applied. */
17
+ export function normalizeActionConfig(config) {
18
+ if (!isRecord(config)) {
19
+ throw new ValidationError("defineAction() requires a configuration object");
20
+ }
21
+ const key = config.key;
22
+ if (typeof key !== "string" || !ACTION_KEY.test(key)) {
23
+ throw new ValidationError("Action key must start with a lowercase letter and contain at most 64 lowercase "
24
+ + "letters, digits or underscores");
25
+ }
26
+ const fail = (option, message) => new ValidationError(`Action '${key}': ${message}`, { actionKey: key, option });
27
+ for (const option of Object.keys(config)) {
28
+ if (!CONFIG_KEYS.has(option))
29
+ throw fail(option, `unknown config key '${option}'`);
30
+ }
31
+ const label = typeof config.label === "string" ? config.label.trim() : "";
32
+ if (label.length === 0 || label.length > MAX_LABEL_LENGTH) {
33
+ throw fail("label", `label must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`);
34
+ }
35
+ let description = "";
36
+ if (config.description !== undefined) {
37
+ if (typeof config.description !== "string" || config.description.trim().length > MAX_DESCRIPTION_LENGTH) {
38
+ throw fail("description", `description must be a string of at most ${MAX_DESCRIPTION_LENGTH} characters`);
39
+ }
40
+ description = config.description.trim();
41
+ }
42
+ const exposeTo = exposures(config.exposeTo, fail);
43
+ // Agents choose a tool by its description, so an action they can call must have one.
44
+ if (exposeTo.includes("agent") && description.length === 0) {
45
+ throw fail("description", "description is required when exposeTo includes \"agent\"");
46
+ }
47
+ const effect = config.effect;
48
+ if (typeof effect !== "string" || !EFFECTS.has(effect)) {
49
+ throw fail("effect", "effect must be \"read\" or \"write\"");
50
+ }
51
+ const inputSchema = rootSchemaJson(config.input, "input", message => fail("input", message));
52
+ const outputSchema = rootSchemaJson(config.output, "output", message => fail("output", message));
53
+ if (schemaByteLength(inputSchema) + schemaByteLength(outputSchema) > MAX_SCHEMA_BYTES) {
54
+ throw fail("input", `the JSON Schemas of input and output together must not exceed ${MAX_SCHEMA_BYTES} `
55
+ + "UTF-8 bytes");
56
+ }
57
+ let timeoutMs = DEFAULT_TIMEOUT_MILLIS;
58
+ if (config.timeoutMs !== undefined) {
59
+ const value = config.timeoutMs;
60
+ if (typeof value !== "number" || !Number.isInteger(value)
61
+ || value < MIN_TIMEOUT_MILLIS || value > MAX_TIMEOUT_MILLIS) {
62
+ throw fail("timeoutMs", `timeoutMs must be an integer between ${MIN_TIMEOUT_MILLIS} and ${MAX_TIMEOUT_MILLIS}`);
63
+ }
64
+ timeoutMs = value;
65
+ }
66
+ const handler = config.handler;
67
+ if (typeof handler !== "function")
68
+ throw fail("handler", "handler must be a function");
69
+ // Key order follows the manifest contract that Cogover stores.
70
+ const manifest = {
71
+ key,
72
+ label,
73
+ description,
74
+ exposeTo,
75
+ effect: effect,
76
+ timeoutMs,
77
+ inputSchema: cloneJson(inputSchema),
78
+ outputSchema: cloneJson(outputSchema),
79
+ };
80
+ return { manifest: deepFreeze(manifest), handler: handler };
81
+ }
82
+ function exposures(value, fail) {
83
+ const invalid = () => fail("exposeTo", "exposeTo must be a non-empty list of \"process\" and \"agent\" without duplicates");
84
+ if (!Array.isArray(value) || value.length === 0)
85
+ throw invalid();
86
+ const result = [];
87
+ for (const item of value) {
88
+ if (typeof item !== "string" || !EXPOSURES.has(item) || result.includes(item)) {
89
+ throw invalid();
90
+ }
91
+ result.push(item);
92
+ }
93
+ return result;
94
+ }