@cogover/sdk 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +63 -5
  2. package/dist/action-schema.d.ts +86 -0
  3. package/dist/action-schema.js +52 -0
  4. package/dist/actions.d.ts +129 -0
  5. package/dist/actions.js +11 -0
  6. package/dist/agents.d.ts +75 -0
  7. package/dist/agents.js +1 -0
  8. package/dist/index.d.ts +8 -0
  9. package/dist/index.js +3 -0
  10. package/dist/internal/action-config.js +94 -0
  11. package/dist/internal/action-runtime.js +143 -0
  12. package/dist/internal/action-schema-rules.js +33 -0
  13. package/dist/internal/agents-api.js +163 -0
  14. package/dist/internal/job-runtime.js +9 -2
  15. package/dist/internal/local-invocation.js +8 -0
  16. package/dist/internal/processes-api.js +74 -0
  17. package/dist/internal/schema-nodes.js +179 -0
  18. package/dist/internal/start-options.js +52 -0
  19. package/dist/internal/trigger-runtime.js +10 -2
  20. package/dist/jobs.d.ts +7 -0
  21. package/dist/limits.d.ts +33 -0
  22. package/dist/limits.js +51 -0
  23. package/dist/processes.d.ts +52 -0
  24. package/dist/processes.js +1 -0
  25. package/dist/router.js +3 -0
  26. package/dist/script.d.ts +7 -0
  27. package/dist/script.js +9 -2
  28. package/dist/trigger.d.ts +9 -0
  29. package/docs/en/api-reference/actions.md +403 -0
  30. package/docs/en/api-reference/background-jobs.md +24 -12
  31. package/docs/en/api-reference/cryptography.md +3 -2
  32. package/docs/en/api-reference/fetch-and-secrets.md +5 -5
  33. package/docs/en/api-reference/organization-structure.md +4 -3
  34. package/docs/en/api-reference/overview.md +124 -15
  35. package/docs/en/api-reference/processes-and-agents.md +357 -0
  36. package/docs/en/api-reference/record-triggers.md +10 -5
  37. package/docs/en/api-reference/records.md +23 -16
  38. package/docs/en/api-reference/scripts-and-routes.md +10 -4
  39. package/docs/en/usage-guide.md +159 -7
  40. package/package.json +1 -1
@@ -0,0 +1,52 @@
1
+ import { ValidationError } from "../errors.js";
2
+ import { JOB_KEY } from "./job-config.js";
3
+ import { toJsonValue } from "./json.js";
4
+ import { requireKnownKeys } from "./messaging.js";
5
+ import { utf8ByteLength } from "./utf8.js";
6
+ /** ID of a Process definition, a Process instance or an AI Agent. */
7
+ export const PLATFORM_ID = /^[A-Za-z0-9_-]{1,64}$/u;
8
+ const IDEMPOTENCY_KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/u;
9
+ const COMPLETION_KEYS = new Set(["job", "payload"]);
10
+ const MAX_COMPLETION_PAYLOAD_BYTES = 8192;
11
+ export function requirePlatformId(value, label) {
12
+ if (typeof value !== "string" || !PLATFORM_ID.test(value)) {
13
+ throw new ValidationError(`${label} must contain 1 to 64 letters, digits, '_' or '-'`);
14
+ }
15
+ return value;
16
+ }
17
+ export function optionalStartIdempotencyKey(value, method) {
18
+ if (value === undefined)
19
+ return undefined;
20
+ if (typeof value !== "string" || !IDEMPOTENCY_KEY.test(value)) {
21
+ throw new ValidationError(`${method} idempotencyKey must start with a letter or digit and contain at most `
22
+ + "200 letters, digits, '.', '_', ':' or '-'");
23
+ }
24
+ return value;
25
+ }
26
+ /** Validates an `onComplete` / `onResult` option; `null` and `undefined` payloads are left out. */
27
+ export function optionalCompletion(value, label) {
28
+ if (value === undefined)
29
+ return undefined;
30
+ const completion = requireKnownKeys(value, COMPLETION_KEYS, label);
31
+ if (typeof completion.job !== "string" || !JOB_KEY.test(completion.job)) {
32
+ throw new ValidationError(`${label}.job must start with a letter and contain at most 100 letters, digits or underscores`);
33
+ }
34
+ const result = { job: completion.job };
35
+ if (completion.payload !== undefined && completion.payload !== null) {
36
+ const payload = toJsonValue(completion.payload, `${label}.payload`);
37
+ if (utf8ByteLength(JSON.stringify(payload)) > MAX_COMPLETION_PAYLOAD_BYTES) {
38
+ throw new ValidationError(`${label}.payload must not exceed ${MAX_COMPLETION_PAYLOAD_BYTES} UTF-8 bytes`);
39
+ }
40
+ result.payload = payload;
41
+ }
42
+ return result;
43
+ }
44
+ /** A string that is not blank and has at most `maximum` characters; returned unchanged. */
45
+ export function optionalBoundedText(value, label, maximum) {
46
+ if (value === undefined)
47
+ return undefined;
48
+ if (typeof value !== "string" || value.trim().length === 0 || value.length > maximum) {
49
+ throw new ValidationError(`${label} must be a non-empty string of at most ${maximum} characters`);
50
+ }
51
+ return value;
52
+ }
@@ -1,4 +1,6 @@
1
1
  import { crypto } from "../crypto.js";
2
+ import { limits } from "../limits.js";
3
+ import { runInvocation } from "./local-invocation.js";
2
4
  import { createDataApi } from "../data.js";
3
5
  import { ValidationError } from "../errors.js";
4
6
  import { installCogoverFetch } from "../fetch.js";
@@ -14,6 +16,8 @@ import { createJobsApi } from "./jobs-api.js";
14
16
  import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
15
17
  import { TRIGGER_SLUG } from "./trigger-config.js";
16
18
  import { errorMessage, isRecord } from "./values.js";
19
+ import { createProcessesApi } from "./processes-api.js";
20
+ import { createAgentsApi } from "./agents-api.js";
17
21
  const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
18
22
  const MAX_ERROR_MESSAGE_LENGTH = 500;
19
23
  // Both spellings of a timing and an operation are accepted; project code only ever sees the SDK literals.
@@ -47,7 +51,7 @@ export function createTriggerSandboxHandler(manifest, handler) {
47
51
  const trigger = triggerInfo(input, manifest);
48
52
  const entries = recordEntries(input.records, trigger.operation);
49
53
  let invocation;
50
- await handler(Object.freeze({
54
+ await runInvocation(trigger.timing, async () => handler(Object.freeze({
51
55
  records: Object.freeze(entries.map(entry => entry.record)),
52
56
  trigger,
53
57
  get invocation() {
@@ -65,7 +69,11 @@ export function createTriggerSandboxHandler(manifest, handler) {
65
69
  secrets: createSecretsApi(),
66
70
  crypto,
67
71
  org: createOrgApi(() => invocation ??= invocationContext(input)),
68
- }));
72
+ limits,
73
+ // The host refuses processes and agents in a before-change trigger, like jobs.
74
+ processes: createProcessesApi(),
75
+ agents: createAgentsApi(),
76
+ })));
69
77
  const results = [];
70
78
  for (const entry of entries) {
71
79
  // Always diff: changing a field outside writableFields is a bug even on a rejected record.
package/dist/jobs.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { CryptoApi } from "./crypto.js";
2
2
  import type { DataApi } from "./data.js";
3
3
  import type { InvocationContext } from "./invocation.js";
4
+ import type { LimitsApi } from "./limits.js";
4
5
  import type { DistributedLocks } from "./locks.js";
5
6
  import type { EmailApi } from "./email.js";
6
7
  import type { NotificationsApi } from "./notifications.js";
@@ -11,6 +12,8 @@ import type { SandboxHandler } from "./script.js";
11
12
  import type { SecretsApi } from "./secrets.js";
12
13
  import type { ProjectState } from "./state.js";
13
14
  import type { EffectiveWorkspaceObjects } from "./workspace.js";
15
+ import type { ProcessesApi } from "./processes.js";
16
+ import type { AgentsApi } from "./agents.js";
14
17
  /** Runs a job on a cron schedule. */
15
18
  export interface JobSchedule {
16
19
  /** Five fields: minute, hour, day-of-month, month, day-of-week. */
@@ -95,6 +98,10 @@ export interface JobContext<TPayload = unknown, TSchema extends object = Effecti
95
98
  readonly secrets: SecretsApi;
96
99
  readonly crypto: CryptoApi;
97
100
  readonly org: OrgApi;
101
+ /** Budgets of this execution; reading them is not a Cogover call. */
102
+ readonly limits: LimitsApi;
103
+ readonly processes: ProcessesApi;
104
+ readonly agents: AgentsApi;
98
105
  }
99
106
  export type JobHandler<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects> = (context: JobContext<TPayload, TSchema>) => void | Promise<void>;
100
107
  /** Declares a background job. Add the result to the project's `jobs` export. */
@@ -0,0 +1,33 @@
1
+ /** One budget of the current execution. */
2
+ export interface LimitCounter {
3
+ /** What the execution has used so far. */
4
+ readonly used: number;
5
+ /** The budget of the execution. */
6
+ readonly limit: number;
7
+ /** `limit - used`, never below 0. */
8
+ readonly remaining: number;
9
+ }
10
+ /** What the current execution has used of its budgets, as of its last Cogover call. */
11
+ export interface LimitUsage {
12
+ /** Calls that reach records, state, locks, messaging, jobs, secrets or `fetch`. */
13
+ readonly capabilityCalls: LimitCounter;
14
+ /** `crypto` calls and `org` reads without `withDisplay`. */
15
+ readonly localCalls: LimitCounter;
16
+ /** Records returned by `records.get`, `records.getMany` and `records.list`, and records read by `expandLookups`. */
17
+ readonly recordsRead: LimitCounter;
18
+ /** Records sent to `records` write operations. */
19
+ readonly recordsWritten: LimitCounter;
20
+ /** Milliseconds since the handler started, as of the last Cogover call. */
21
+ readonly elapsedMs: number;
22
+ /** Wall-clock time the execution may take, in milliseconds. */
23
+ readonly timeLimitMs: number;
24
+ }
25
+ /** Reads the budgets of the current execution. Reading them is free: it is not a Cogover call. */
26
+ export interface LimitsApi {
27
+ usage(): LimitUsage;
28
+ }
29
+ /**
30
+ * Budgets of the current execution. Cogover refuses a call that would go over a budget with `RateLimitError`,
31
+ * whose `details.budget` names it.
32
+ */
33
+ export declare const limits: LimitsApi;
package/dist/limits.js ADDED
@@ -0,0 +1,51 @@
1
+ import { CogoverApiError } from "./errors.js";
2
+ const COUNTERS = ["capabilityCalls", "localCalls", "recordsRead", "recordsWritten"];
3
+ function unavailable() {
4
+ return new CogoverApiError("CAPABILITY_UNAVAILABLE", "Execution limits are only available while a Cogover handler runs");
5
+ }
6
+ function invalid() {
7
+ return new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Execution limits could not be read");
8
+ }
9
+ function isRecord(value) {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+ function count(value) {
13
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
14
+ throw invalid();
15
+ return value;
16
+ }
17
+ function counter(value) {
18
+ if (!isRecord(value))
19
+ throw invalid();
20
+ const used = count(value.used);
21
+ const limit = count(value.limit);
22
+ return Object.freeze({ used, limit, remaining: Math.max(0, limit - used) });
23
+ }
24
+ function readUsage() {
25
+ const reader = globalThis.__cogoverLimitUsage;
26
+ const text = typeof reader === "function" ? reader() : null;
27
+ if (typeof text !== "string")
28
+ throw unavailable();
29
+ let raw;
30
+ try {
31
+ raw = JSON.parse(text);
32
+ }
33
+ catch {
34
+ throw invalid();
35
+ }
36
+ if (!isRecord(raw))
37
+ throw invalid();
38
+ const counters = Object.fromEntries(COUNTERS.map(name => [name, counter(raw[name])]));
39
+ return Object.freeze({
40
+ ...counters,
41
+ elapsedMs: count(raw.elapsedMs),
42
+ timeLimitMs: count(raw.timeLimitMs),
43
+ });
44
+ }
45
+ /**
46
+ * Budgets of the current execution. Cogover refuses a call that would go over a budget with `RateLimitError`,
47
+ * whose `details.budget` names it.
48
+ */
49
+ export const limits = Object.freeze({
50
+ usage: readUsage,
51
+ });
@@ -0,0 +1,52 @@
1
+ /** Runs a background job of the project when the started Process instance finishes. */
2
+ export interface ProcessCompletion {
3
+ /** Key of a job of the project's `jobs` export. */
4
+ readonly job: string;
5
+ /** JSON value of at most 8192 UTF-8 bytes handed to the job as `payload`. */
6
+ readonly payload?: unknown;
7
+ }
8
+ /** Options of `processes.start`. */
9
+ export interface ProcessStartOptions {
10
+ /** Input variables of the Process, as a JSON object of at most 65536 UTF-8 bytes. */
11
+ readonly input?: Record<string, unknown>;
12
+ /** Name of the new instance, 1 to 255 characters. */
13
+ readonly instanceName?: string;
14
+ /** A second start with the same key in the same project returns the first instance instead of a new one. */
15
+ readonly idempotencyKey?: string;
16
+ /** Job that receives the outcome of the instance. */
17
+ readonly onComplete?: ProcessCompletion;
18
+ }
19
+ export interface ProcessStartResult {
20
+ readonly instanceId: string;
21
+ /** `true` when an earlier start with the same `idempotencyKey` was found; `instanceId` is that instance. */
22
+ readonly duplicate: boolean;
23
+ }
24
+ /** Current state of a Process instance. */
25
+ export interface ProcessInstanceState {
26
+ readonly instanceId: string;
27
+ readonly processId: string;
28
+ readonly processInfoId: string;
29
+ readonly state: string;
30
+ /** Unix milliseconds, or `null` when the instance has not started. */
31
+ readonly startedAt: number | null;
32
+ /** Unix milliseconds, or `null` while the instance runs. */
33
+ readonly finishedAt: number | null;
34
+ }
35
+ /** Starts Cogover Processes and reads their state. The result of a Process is delivered to a background job. */
36
+ export interface ProcessesApi {
37
+ start(processInfoId: string, options?: ProcessStartOptions): Promise<ProcessStartResult>;
38
+ get(instanceId: string): Promise<ProcessInstanceState>;
39
+ }
40
+ /** The `payload` of the job named by `onComplete` when the Process instance finishes. */
41
+ export interface ProcessCompletionJobPayload<TPayload = unknown> {
42
+ /** `onComplete.payload`, or `null` when there was none. */
43
+ readonly payload: TPayload | null;
44
+ readonly process: {
45
+ readonly instanceId: string;
46
+ readonly processId: string;
47
+ readonly processInfoId: string;
48
+ readonly state: "COMPLETED" | "CANCELED" | "DELETED" | "FAILED";
49
+ readonly output: Record<string, unknown> | null;
50
+ readonly finishedAt: number | null;
51
+ };
52
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/router.js CHANGED
@@ -66,6 +66,9 @@ export function createRouter() {
66
66
  secrets: context.secrets,
67
67
  crypto: context.crypto,
68
68
  org: context.org,
69
+ limits: context.limits,
70
+ processes: context.processes,
71
+ agents: context.agents,
69
72
  });
70
73
  });
71
74
  },
package/dist/script.d.ts CHANGED
@@ -14,6 +14,9 @@ import type { JobsApi } from "./jobs.js";
14
14
  import type { SecretsApi } from "./secrets.js";
15
15
  import type { CryptoApi } from "./crypto.js";
16
16
  import type { OrgApi } from "./org.js";
17
+ import type { LimitsApi } from "./limits.js";
18
+ import type { ProcessesApi } from "./processes.js";
19
+ import type { AgentsApi } from "./agents.js";
17
20
  export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
18
21
  readonly input: TInput;
19
22
  readonly request: ScriptRequest<TInput>;
@@ -31,6 +34,10 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
31
34
  readonly secrets: SecretsApi;
32
35
  readonly crypto: CryptoApi;
33
36
  readonly org: OrgApi;
37
+ /** Budgets of this execution; reading them is not a Cogover call. */
38
+ readonly limits: LimitsApi;
39
+ readonly processes: ProcessesApi;
40
+ readonly agents: AgentsApi;
34
41
  }
35
42
  export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
36
43
  export type SandboxHandler = (inputJson: string) => Promise<string | null>;
package/dist/script.js CHANGED
@@ -16,6 +16,10 @@ import { createJobsApi } from "./internal/jobs-api.js";
16
16
  import { createSecretsApi } from "./secrets.js";
17
17
  import { crypto } from "./crypto.js";
18
18
  import { createOrgApi } from "./org.js";
19
+ import { limits } from "./limits.js";
20
+ import { runInvocation } from "./internal/local-invocation.js";
21
+ import { createProcessesApi } from "./internal/processes-api.js";
22
+ import { createAgentsApi } from "./internal/agents-api.js";
19
23
  const RESPONSE_TOKEN_VERSION_MEMBER = "__cogoverResponseTokenVersion";
20
24
  export function defineScript(handler) {
21
25
  if (typeof handler !== "function") {
@@ -39,7 +43,7 @@ export function createSandboxHandler(handler) {
39
43
  throw new ValidationError("Script input must be valid JSON", errorMessage(error));
40
44
  }
41
45
  let invocation;
42
- const output = await handler({
46
+ const output = await runInvocation("route", async () => handler({
43
47
  input,
44
48
  request: scriptRequest(input),
45
49
  get invocation() {
@@ -58,7 +62,10 @@ export function createSandboxHandler(handler) {
58
62
  secrets: createSecretsApi(),
59
63
  crypto,
60
64
  org: createOrgApi(() => invocation ??= invocationContext(input)),
61
- });
65
+ limits,
66
+ processes: createProcessesApi(),
67
+ agents: createAgentsApi(),
68
+ }));
62
69
  if (output === null) {
63
70
  return null;
64
71
  }
package/dist/trigger.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { CryptoApi } from "./crypto.js";
2
2
  import type { DataApi } from "./data.js";
3
3
  import type { JobsApi } from "./jobs.js";
4
+ import type { LimitsApi } from "./limits.js";
4
5
  import type { OrgApi } from "./org.js";
5
6
  import type { SecretsApi } from "./secrets.js";
6
7
  import type { InvocationContext } from "./invocation.js";
@@ -12,6 +13,8 @@ import type { FilterOperator } from "./query.js";
12
13
  import type { CogoverRecordId, UpdateFields } from "./records.js";
13
14
  import type { SchemaApi } from "./schema.js";
14
15
  import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
16
+ import type { ProcessesApi } from "./processes.js";
17
+ import type { AgentsApi } from "./agents.js";
15
18
  /** When a record trigger runs relative to the record change. */
16
19
  export type TriggerTiming = "beforeChange" | "afterChange";
17
20
  /** Record operations a trigger can subscribe to. */
@@ -133,6 +136,12 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
133
136
  readonly secrets: SecretsApi;
134
137
  readonly crypto: CryptoApi;
135
138
  readonly org: OrgApi;
139
+ /** Budgets of this execution; reading them is not a Cogover call. */
140
+ readonly limits: LimitsApi;
141
+ /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
142
+ readonly processes: ProcessesApi;
143
+ /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
144
+ readonly agents: AgentsApi;
136
145
  }
137
146
  export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
138
147
  /** Declares a record trigger. Add the result to the project's `triggers` export. */