@cogover/sdk 0.13.0 → 0.14.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
@@ -49,7 +49,9 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
49
49
  data, schema, logging, state, lock, push, notification, email, job, secret, and
50
50
  crypto 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
- the configured permissions and limits on capability calls.
52
+ the configured permissions and the per-execution limits on capability calls and
53
+ records. `limits.usage()` (also `context.limits`) reports how much of each budget
54
+ the execution has used, without a capability call.
53
55
 
54
56
  ## Current identity and workspace
55
57
 
@@ -357,7 +359,8 @@ transport-specific field metadata or response envelopes.
357
359
 
358
360
  Every read names the fields it needs: `fields` is required by `get`, `getMany`, and
359
361
  `list`, either as a list of field slugs or as `"*"` for every field that the identity
360
- in use and the project's identity policy may read. A read without `fields` throws
362
+ in use may read (with `data.asUser()` or `data.asSystem()`, only the fields that the
363
+ project's identity policy grants). A read without `fields` throws
361
364
  `ValidationError` (`fields is required: pass field slugs or "*" (@cogover/sdk
362
365
  0.13.0+)`). With workspace types, the result is narrowed to the requested fields, so
363
366
  reading a field that was not requested is a compile error. A single result is limited
package/dist/index.d.ts CHANGED
@@ -14,6 +14,8 @@ export { defineJob } from "./jobs.js";
14
14
  export type { JobSchedule, JobConfig, JobManifest, JobDefinition, JobInfo, EnqueueOptions, EnqueueResult, JobsApi, JobContext, JobHandler, } from "./jobs.js";
15
15
  export type { SecretsApi } from "./secrets.js";
16
16
  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
+ export { limits } from "./limits.js";
18
+ export type { LimitsApi, LimitUsage, LimitCounter } from "./limits.js";
17
19
  export { crypto } from "./crypto.js";
18
20
  export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
19
21
  export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentWorkspaceRole, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ 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 { limits } from "./limits.js";
6
7
  export { crypto } from "./crypto.js";
7
8
  export { createRouter } from "./router.js";
8
9
  export { fetch } from "./fetch.js";
@@ -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";
@@ -34,7 +36,7 @@ export function createJobSandboxHandler(manifest, handler) {
34
36
  throw new ValidationError("Job input must be a JSON object");
35
37
  const job = jobInfo(input, manifest);
36
38
  let invocation;
37
- await handler(Object.freeze({
39
+ await runInvocation("job", async () => handler(Object.freeze({
38
40
  job,
39
41
  payload: input.payload ?? null,
40
42
  get invocation() {
@@ -51,7 +53,8 @@ export function createJobSandboxHandler(manifest, handler) {
51
53
  secrets: createSecretsApi(),
52
54
  crypto,
53
55
  org: createOrgApi(() => invocation ??= invocationContext(input)),
54
- }));
56
+ limits,
57
+ })));
55
58
  // The result of a job is not delivered anywhere, so nothing is serialized.
56
59
  return null;
57
60
  };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Runs one handler invocation. When the handler runs locally under Cogover Dev CLI, the CLI provides a hook that
3
+ * counts the invocation's calls against the budgets of its lane; Cogover Runtime counts them on the host instead.
4
+ */
5
+ export function runInvocation(lane, run) {
6
+ const hook = globalThis.__cogoverLocalInvocation;
7
+ return typeof hook === "function" ? hook(lane, run) : run();
8
+ }
@@ -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";
@@ -47,7 +49,7 @@ export function createTriggerSandboxHandler(manifest, handler) {
47
49
  const trigger = triggerInfo(input, manifest);
48
50
  const entries = recordEntries(input.records, trigger.operation);
49
51
  let invocation;
50
- await handler(Object.freeze({
52
+ await runInvocation(trigger.timing, async () => handler(Object.freeze({
51
53
  records: Object.freeze(entries.map(entry => entry.record)),
52
54
  trigger,
53
55
  get invocation() {
@@ -65,7 +67,8 @@ export function createTriggerSandboxHandler(manifest, handler) {
65
67
  secrets: createSecretsApi(),
66
68
  crypto,
67
69
  org: createOrgApi(() => invocation ??= invocationContext(input)),
68
- }));
70
+ limits,
71
+ })));
69
72
  const results = [];
70
73
  for (const entry of entries) {
71
74
  // 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";
@@ -95,6 +96,8 @@ export interface JobContext<TPayload = unknown, TSchema extends object = Effecti
95
96
  readonly secrets: SecretsApi;
96
97
  readonly crypto: CryptoApi;
97
98
  readonly org: OrgApi;
99
+ /** Budgets of this execution; reading them is not a Cogover call. */
100
+ readonly limits: LimitsApi;
98
101
  }
99
102
  export type JobHandler<TPayload = unknown, TSchema extends object = EffectiveWorkspaceObjects> = (context: JobContext<TPayload, TSchema>) => void | Promise<void>;
100
103
  /** 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
+ });
package/dist/router.js CHANGED
@@ -66,6 +66,7 @@ export function createRouter() {
66
66
  secrets: context.secrets,
67
67
  crypto: context.crypto,
68
68
  org: context.org,
69
+ limits: context.limits,
69
70
  });
70
71
  });
71
72
  },
package/dist/script.d.ts CHANGED
@@ -14,6 +14,7 @@ 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";
17
18
  export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
18
19
  readonly input: TInput;
19
20
  readonly request: ScriptRequest<TInput>;
@@ -31,6 +32,8 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
31
32
  readonly secrets: SecretsApi;
32
33
  readonly crypto: CryptoApi;
33
34
  readonly org: OrgApi;
35
+ /** Budgets of this execution; reading them is not a Cogover call. */
36
+ readonly limits: LimitsApi;
34
37
  }
35
38
  export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
36
39
  export type SandboxHandler = (inputJson: string) => Promise<string | null>;
package/dist/script.js CHANGED
@@ -16,6 +16,8 @@ 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";
19
21
  const RESPONSE_TOKEN_VERSION_MEMBER = "__cogoverResponseTokenVersion";
20
22
  export function defineScript(handler) {
21
23
  if (typeof handler !== "function") {
@@ -39,7 +41,7 @@ export function createSandboxHandler(handler) {
39
41
  throw new ValidationError("Script input must be valid JSON", errorMessage(error));
40
42
  }
41
43
  let invocation;
42
- const output = await handler({
44
+ const output = await runInvocation("route", async () => handler({
43
45
  input,
44
46
  request: scriptRequest(input),
45
47
  get invocation() {
@@ -58,7 +60,8 @@ export function createSandboxHandler(handler) {
58
60
  secrets: createSecretsApi(),
59
61
  crypto,
60
62
  org: createOrgApi(() => invocation ??= invocationContext(input)),
61
- });
63
+ limits,
64
+ }));
62
65
  if (output === null) {
63
66
  return null;
64
67
  }
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";
@@ -133,6 +134,8 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
133
134
  readonly secrets: SecretsApi;
134
135
  readonly crypto: CryptoApi;
135
136
  readonly org: OrgApi;
137
+ /** Budgets of this execution; reading them is not a Cogover call. */
138
+ readonly limits: LimitsApi;
136
139
  }
137
140
  export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
138
141
  /** Declares a record trigger. Add the result to the project's `triggers` export. */
@@ -164,6 +164,7 @@ interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspa
164
164
  readonly secrets: SecretsApi;
165
165
  readonly crypto: CryptoApi;
166
166
  readonly org: OrgApi;
167
+ readonly limits: LimitsApi;
167
168
  }
168
169
 
169
170
  interface JobInfo {
@@ -179,8 +180,9 @@ interface JobInfo {
179
180
 
180
181
  A handler may be synchronous or asynchronous; its return value is ignored. `data`,
181
182
  `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
182
- `secrets`, `crypto`, and `org` are the same APIs that scripts receive. A job context has
183
- no `input`, `request`, `response`, or `push`.
183
+ `secrets`, `crypto`, `org`, and `limits` are the same APIs that scripts receive; `limits`
184
+ reports the larger budgets of a job (see [Execution limits](overview.md#execution-limits)).
185
+ A job context has no `input`, `request`, `response`, or `push`.
184
186
 
185
187
  - `job.id` identifies the run and stays the same across its attempts; use it as the
186
188
  idempotency key of external calls. `job.attempt` starts at 1.
@@ -234,10 +236,9 @@ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
234
236
  (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
235
237
  without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
236
238
  enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
237
- running; beyond that `RateLimitError` is thrown. An HTTP route or a trigger reaches
238
- its budget of 20 capability calls first (see
239
- [Execution limits](overview.md#execution-limits)), so there the limit of 50 enqueues
240
- is not reached. When jobs are not enabled for the Workspace, the error is
239
+ running; beyond that `RateLimitError` is thrown. Each `enqueue` also counts as a
240
+ capability call (see [Execution limits](overview.md#execution-limits)). When jobs are
241
+ not enabled for the Workspace, the error is
241
242
  `CogoverApiError` with `code: "JOBS_DISABLED"`.
242
243
 
243
244
  ### Job execution rules
@@ -310,8 +310,9 @@ base64, which is a third larger. Binary data larger than about 190 KiB, or text
310
310
  close to 256 KiB together with other arguments, therefore throws `ValidationError`
311
311
  before the call even though each value is within its own limit. The key, algorithm, and option errors that
312
312
  Cogover detects, such as a key of the wrong size or type, also throw
313
- `ValidationError`. Every operation except `timingSafeEqual` is a capability call
314
- and counts towards the invocation's limits; `randomUUID` makes one call for every
313
+ `ValidationError`. Every operation except `timingSafeEqual` is a local call and counts
314
+ towards the invocation's budget of local calls, not its capability calls (see
315
+ [Execution limits](overview.md#execution-limits)); `randomUUID` makes one call for every
315
316
  64 UUIDs.
316
317
 
317
318
  The operations work in every context, including before-change triggers, with a key
@@ -86,9 +86,9 @@ headers, time, calls, destinations, and concurrency are bounded by platform quot
86
86
  Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
87
87
  `FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
88
88
  `FETCH_FAILED`; quota failures use `RateLimitError`. One execution may make at most 20
89
- `fetch` calls; an HTTP route or a trigger reaches its budget of 20 capability calls
90
- first, which is also reported as `RateLimitError` (see
91
- [Execution limits](overview.md#execution-limits)). When POST, PUT, PATCH, or DELETE
89
+ `fetch` calls, and each one also counts against the capability-call budget of the
90
+ execution (see [Execution limits](overview.md#execution-limits)); going over either is
91
+ reported as `RateLimitError`. When POST, PUT, PATCH, or DELETE
92
92
  times out or loses its response, the remote server may already have applied the
93
93
  request. Use the remote API's idempotency mechanism and never retry blindly.
94
94
 
@@ -174,8 +174,8 @@ webhook calls. A before-change trigger is refused with `PermissionDeniedError`
174
174
  secrets only when its administrator allowed it, otherwise the reason is
175
175
  `"SECRETS_NOT_ALLOWED"`. One invocation may read secrets at most 20 times; every
176
176
  read counts, including a repeated read of the same name and a `crypto` operation keyed
177
- by `{ secret: name }`, and the 21st throws `RateLimitError`. In an HTTP route or a
178
- trigger the budget of 20 capability calls is reached first (see
177
+ by `{ secret: name }`, and the 21st throws `RateLimitError`. `secrets.get` also counts
178
+ as a capability call, and a `crypto` operation as a local call (see
179
179
  [Execution limits](overview.md#execution-limits)). When secrets are
180
180
  not enabled for the Workspace, the error is `CogoverApiError` with
181
181
  `code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
@@ -291,7 +291,7 @@ only the chain that starts there and `directOnly` only its nearest tier. Both re
291
291
  when the project's approved identity policy sets `allowInternalSystem: true`;
292
292
  otherwise every call except `org.me()` throws `PermissionDeniedError` with
293
293
  `details.reason` `"IDENTITY_NOT_GRANTED"`. `org.me()` returns `null` there without a
294
- capability call, because the execution has no user.
294
+ call, because the execution has no user.
295
295
  - All calls of one execution read the same version of the structure.
296
296
  - IDs are validated by the SDK and again by Cogover; an invalid ID or option throws
297
297
  `ValidationError`. Every method returns a promise, and an invalid argument rejects
@@ -300,5 +300,6 @@ only the chain that starts there and `directOnly` only its nearest tier. Both re
300
300
  `NotFoundError` with `resource` `"department"` or `"position"`.
301
301
  - When the structure cannot be read, the call throws `CogoverApiError` with code
302
302
  `ORGANIZATION_UNAVAILABLE`.
303
- - Call `getMany` or `members` instead of calling `get` in a loop: each call is one
304
- capability call.
303
+ - A read without `withDisplay` is a local call; a read with `withDisplay: true` is a
304
+ capability call (see [Execution limits](overview.md#execution-limits)). Call `getMany`
305
+ or `members` instead of calling `get` in a loop: each call counts once.
@@ -23,7 +23,7 @@ The reference is split into the following pages. Each page covers one area of th
23
23
  | [Notifications and email](notifications-and-email.md) | Notifications; Email |
24
24
  | [Organization structure](organization-structure.md) | Organization structure |
25
25
 
26
- The sections below apply to every area: the errors every API can throw, the limits of one execution, and the compatibility helper.
26
+ The sections below apply to every area: the errors every API can throw, the limits of one execution, reading those limits in code, and the compatibility helper.
27
27
 
28
28
  ## Errors
29
29
 
@@ -171,16 +171,41 @@ These responses do not roll back earlier writes; do not retry writes automatical
171
171
  Every execution runs within platform limits. These are the default values; they are
172
172
  set by the platform and may differ between environments.
173
173
 
174
- - An HTTP route and a record trigger may make at most 20 capability calls. Every call
175
- to `data`, `schema`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`,
176
- `secrets`, `crypto`, `org`, or `fetch` counts once. A background job may make 200.
177
- The call over the budget, and every call after it, throws `RateLimitError`
178
- (`details.limit` is the budget) without being sent, so a script can catch it.
174
+ | Budget of one execution | HTTP route | Before-change trigger | After-change trigger | Background job |
175
+ |---|---|---|---|---|
176
+ | Capability calls (`capabilityCalls`) | 100 | 20 | 100 | 1,000 |
177
+ | Local calls (`localCalls`) | 200 | 50 | 200 | 1,000 |
178
+ | Records read (`recordsRead`) | 10,000 | 4,000 | 10,000 | 50,000 |
179
+ | Records written (`recordsWritten`) | 10,000 | — | 10,000 | 50,000 |
180
+
181
+ - **Capability calls.** Every call to `data`, `schema`, `state`, `locks`, `push`,
182
+ `notifications`, `email`, `jobs`, `secrets`, or `fetch`, and every `org` read with
183
+ `withDisplay: true`, counts once.
184
+ - **Local calls.** `crypto` calls and `org` reads without `withDisplay` are handled by
185
+ Cogover itself, so they count against their own budget instead. A `crypto` key given as
186
+ `{ secret: name }` is still a secret read (see its quota below).
187
+ - **Records read.** The records returned by `records.get`, `records.getMany`, and
188
+ `records.list`, and the linked records that `expandLookups` reads. A read is refused
189
+ before it is sent when it could go over the budget: `records.get` counts 1,
190
+ `records.getMany` the number of IDs, and `records.list` its `limit` (20 by default).
191
+ `records.aggregate` returns no records and does not count.
192
+ - **Records written.** 1 for `create`, `update`, and `upsertByUniqueField`, the number of
193
+ records for `batchInsert` and `batchUpdate`, and the number of IDs for `deleteMany`,
194
+ counted when the call is sent. A before-change trigger cannot write records.
195
+ - A call that would go over a budget, and every later call against that budget, throws
196
+ `RateLimitError` without being sent, so a script can catch it. `details.budget` names
197
+ the budget, `details.limit` is its size, `details.used` is what the execution had used,
198
+ and for records `details.requested` is what the call asked for. Waiting does not help:
199
+ the budget belongs to the execution. Read fewer records, use `records.aggregate` for
200
+ totals, or move the work to a background job. An execution that keeps calling after
201
+ 1,000 refused calls is ended with `code: "RATE_LIMITED"`; the script cannot catch that.
179
202
  - An HTTP route has 8 seconds of wall-clock time, counted from when its handler
180
203
  starts, including the time spent waiting for capability calls, a lock, or a remote
181
204
  server. A record trigger has its own `timeoutMs`, and a background job its
182
205
  `timeoutMs`. Exceeding the time ends the whole execution: the script cannot catch it,
183
- and an HTTP route returns the generic HTTP 422 response.
206
+ and an HTTP route returns the generic HTTP 422 response. Capability calls of one
207
+ execution run one after another, also when they are started together with
208
+ `Promise.all`.
184
209
  - A single capability request, JSON-encoded with its arguments, must not exceed
185
210
  262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
186
211
  or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
@@ -190,10 +215,73 @@ set by the platform and may differ between environments.
190
215
  operation itself did run, so a write may have completed.
191
216
  - When the Workspace already has too many executions waiting, a new HTTP call is
192
217
  refused with HTTP 429 and `code: "RATE_LIMITED"` before anything runs; retry it later.
218
+ This refusal has no `details.budget`.
193
219
 
194
- When an API has its own per-execution quota that is not below the call budget, such
195
- as 20 `fetch` calls or 20 secret reads, the call budget is reached first in a route
196
- or a trigger; both are reported as `RateLimitError`.
220
+ Some APIs also keep their own quota per execution, such as 20 `fetch` calls or 20
221
+ secret reads. Going over one is reported as `RateLimitError` too.
222
+
223
+ ## Reading limits in code
224
+
225
+ ```typescript
226
+ const limits: LimitsApi;
227
+
228
+ interface LimitsApi {
229
+ usage(): LimitUsage;
230
+ }
231
+
232
+ interface LimitUsage {
233
+ readonly capabilityCalls: LimitCounter;
234
+ readonly localCalls: LimitCounter;
235
+ readonly recordsRead: LimitCounter;
236
+ readonly recordsWritten: LimitCounter;
237
+ readonly elapsedMs: number;
238
+ readonly timeLimitMs: number;
239
+ }
240
+
241
+ interface LimitCounter {
242
+ readonly used: number;
243
+ readonly limit: number;
244
+ readonly remaining: number;
245
+ }
246
+ ```
247
+
248
+ `limits` is exported by the package and is also the `limits` member of the context of
249
+ a script, a route, a record trigger, and a background job. `limits.usage()` returns the
250
+ budgets of the current execution as of its last Cogover call: reading them is not a
251
+ capability call. `remaining` is `limit - used` and never below 0. `elapsedMs` is the
252
+ time since the handler started, as of that last call, and `timeLimitMs` is the
253
+ wall-clock time the execution may take. Called outside a handler, for example while the
254
+ module loads or in a test that runs outside Cogover, `usage()` throws `CogoverApiError`
255
+ with `code: "CAPABILITY_UNAVAILABLE"`.
256
+
257
+ When code runs locally with Cogover Dev CLI, each handler gets the budgets of its kind of
258
+ execution and the same refusals; linked records read by `expandLookups` are not counted
259
+ there.
260
+
261
+ ```typescript
262
+ import { defineScript } from "@cogover/sdk";
263
+
264
+ export default defineScript(async ({ data, jobs, limits }) => {
265
+ const orders = data.object("order");
266
+ let cursor: string | undefined;
267
+ let total = 0;
268
+ do {
269
+ const page = await orders.records.list({ fields: ["amount"], limit: 200, cursor });
270
+ for (const order of page.items) total += Number(order.fields.amount ?? 0);
271
+ cursor = page.nextCursor;
272
+ const usage = limits.usage();
273
+ if (cursor !== undefined && (usage.recordsRead.remaining < 200 || usage.capabilityCalls.remaining < 2)) {
274
+ // Hand the rest to a background job, which has larger budgets.
275
+ await jobs.enqueue("sum_orders", { cursor, total });
276
+ return { total, complete: false };
277
+ }
278
+ } while (cursor !== undefined);
279
+ return { total, complete: true };
280
+ });
281
+ ```
282
+
283
+ For a total like this one, `records.aggregate` is one capability call and reads no
284
+ records; page through records only when the result cannot be expressed as an aggregate.
197
285
 
198
286
  ## Compatibility helper
199
287
 
@@ -226,6 +226,7 @@ interface TriggerContext<
226
226
  readonly secrets: SecretsApi;
227
227
  readonly crypto: CryptoApi;
228
228
  readonly org: OrgApi;
229
+ readonly limits: LimitsApi;
229
230
  }
230
231
 
231
232
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -262,7 +263,8 @@ once per record. Keep `fields` short, and read related data for the whole list w
262
263
  one `records.getMany` call rather than one read per record.
263
264
 
264
265
  `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
265
- `crypto`, and `org` are the same APIs that scripts receive. A trigger context has no `input`,
266
+ `crypto`, `org`, and `limits` are the same APIs that scripts receive; a before-change trigger has
267
+ smaller budgets (see [Execution limits](overview.md#execution-limits)). A trigger context has no `input`,
266
268
  `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
267
269
  before-change trigger. `trigger.operation` is
268
270
  the operation of the current call, `trigger.id` identifies the trigger registration, and
@@ -320,8 +320,10 @@ const { records, missingIds } = await accounts.records.getMany(accountIds, { fie
320
320
  const accountById = new Map(records.map(record => [record.id, record]));
321
321
  ```
322
322
 
323
- Use `getMany` instead of calling `get` in a loop. Every capability call counts
324
- towards the project's limits, and a record trigger can receive 200 records at once.
323
+ Use `getMany` instead of calling `get` in a loop. Every capability call and every record
324
+ read counts towards the budgets of the execution (see
325
+ [Execution limits](overview.md#execution-limits)), and a record trigger can receive 200
326
+ records at once.
325
327
 
326
328
  Service `0`/`1` booleans are normalized to JavaScript booleans. A lookup or reference
327
329
  value is a `RecordReference` with `id`, `name`, and `objectSlug`. Its `name` is `""`
@@ -351,9 +353,10 @@ field as its UTC day. Other text for these fields throws `ValidationError` with
351
353
  costs no more than what the script uses. `fields` is required and is one of:
352
354
 
353
355
  - a non-empty list of field slugs, trimmed and deduplicated in their original order;
354
- - the string `"*"` on its own: every field that the identity in use may read and the
355
- project's identity policy grants. When the policy grants only some fields, `"*"`
356
- means those fields, not every field of the Object.
356
+ - the string `"*"` on its own: every field that the identity in use may read. With
357
+ `data.asUser()` or `data.asSystem()` it is limited to the fields that the project's
358
+ identity policy grants: when the policy grants only some fields, `"*"` means those
359
+ fields, not every field of the Object.
357
360
 
358
361
  Leaving `fields` out, or passing `null`, an empty list, `["*"]`, or a value that is not
359
362
  a field slug, throws `ValidationError` before any request is sent, with this message:
@@ -368,9 +371,11 @@ and publish it again.
368
371
 
369
372
  The system slugs `id`, `created`, `updated`, and `created_by` may be listed; their
370
373
  values are always returned in `id` and `system`, not in `fields`. `where` and `orderBy`
371
- may use fields that are not in `fields`. Every field of `fields`, `where`, and
372
- `orderBy` must be granted by the project's identity policy, otherwise the read throws
373
- `PermissionDeniedError`; a slug that the Object does not have throws `ValidationError`.
374
+ may use fields that are not in `fields`. With `data.asUser()` or `data.asSystem()`,
375
+ every field of `fields`, `where`, and `orderBy` must be granted by the project's identity
376
+ policy, otherwise the read throws `PermissionDeniedError`; reads through `data.object()`
377
+ need no policy and follow the permissions of the identity in use. A slug that the Object
378
+ does not have throws `ValidationError`.
374
379
 
375
380
  The result type follows `fields`. With workspace declarations, `fields: ["code",
376
381
  "amount"]` returns `CogoverRecord<Pick<Fields, "code" | "amount">>`, so reading a field
@@ -429,8 +434,9 @@ person's full name; for display names, use
429
434
  with `withDisplay: true`.
430
435
 
431
436
  Linked records are read with the same identity as the read itself: the caller,
432
- `data.asUser()`, or `data.asSystem()`. The project's identity policy must grant reading
433
- the linked Object:
437
+ `data.asUser()`, or `data.asSystem()`. With `data.object()` the linked records follow
438
+ the permissions of the identity in use. With `data.asUser()` or `data.asSystem()`, the
439
+ project's identity policy must also grant reading the linked Object:
434
440
 
435
441
  - With `true` or `"*"`, only the linked fields that the policy grants are returned.
436
442
  When the policy does not grant reading the linked Object, its values stay
@@ -485,7 +491,7 @@ letters, digits, or underscores, and each metric is exactly one of:
485
491
  | Metric | Field | Value |
486
492
  |---|---|---|
487
493
  | `{ count: "id" }` | | number of matching records |
488
- | `{ count: field }` | any field except `reference`, `file`, and `url` | number of matching records with a value in the field |
494
+ | `{ count: field }` | number, date, choice, `boolean`, `lookup_normal`, text, `email`, `phone`, and `auto_number` fields; not `reference`, `file`, `url`, `formula`, or `rollup_summary` | number of matching records with a value in the field |
489
495
  | `{ countDistinct: field }` | the fields that `count` accepts | number of distinct values, approximate on large sets |
490
496
  | `{ sum: field }` | `numeric`, `decimal`, `currency`, `percent` | sum |
491
497
  | `{ avg: field }` | the number types above | average; `null` when no matching record has a value |
@@ -509,9 +515,10 @@ group.
509
515
  1,000 when it is left out. `truncated` is `true` when there were more groups and only
510
516
  the first `limit` are returned.
511
517
 
512
- Every field of `where`, `groupBy`, and `metrics`, except `"id"`, must be granted by the
513
- project's identity policy, otherwise the call throws `PermissionDeniedError`. Only the
514
- records that the identity in use can see are counted.
518
+ With `data.asUser()` or `data.asSystem()`, every field of `where`, `groupBy`, and
519
+ `metrics`, except `"id"`, must be granted by the project's identity policy, otherwise the
520
+ call throws `PermissionDeniedError`. Only the records that the identity in use can see are
521
+ counted.
515
522
 
516
523
  A client from `data.asUser()` has narrower limits:
517
524
 
@@ -524,8 +531,8 @@ A client from `data.asUser()` has narrower limits:
524
531
  avg, min and max on number fields; use the caller or asSystem()`).
525
532
 
526
533
  The same limits apply to `data.object()` when the execution reads as a user who is not
527
- an HTTP caller: in a record trigger for a change made by a user, or in a job run that
528
- has a user. Grouping
534
+ an HTTP caller: in a record trigger for a change made by a user, in a job run that has
535
+ a user, or in a local Development Session started by `cogover-dev run`. Grouping
529
536
  there throws `ValidationError` (`aggregate with groupBy is not supported for the default
530
537
  identity of this invocation, which reads as a delegated user; use asSystem()`). Use
531
538
  `data.asSystem()` there, or the caller in an HTTP route, for groups and the other
@@ -6,8 +6,8 @@ This page is part of the [`@cogover/sdk` API reference](overview.md).
6
6
 
7
7
  `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
8
8
  the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
9
- `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
10
- result.
9
+ `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, and `limits`, awaits the handler, and
10
+ serializes its result.
11
11
 
12
12
  ```typescript
13
13
  function defineScript<
@@ -44,6 +44,7 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
44
44
  readonly secrets: SecretsApi;
45
45
  readonly crypto: CryptoApi;
46
46
  readonly org: OrgApi;
47
+ readonly limits: LimitsApi;
47
48
  }
48
49
  ```
49
50
 
@@ -54,8 +55,9 @@ Returning `null` produces a null handler result; returning `undefined` is invali
54
55
  ## HTTP routers and request context
55
56
 
56
57
  `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
57
- `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
58
- and route handlers. `input`
58
+ `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, `org`, and `limits` to
59
+ both script and route handlers. `limits` reads the budgets of the execution (see
60
+ [Reading limits in code](overview.md#reading-limits-in-code)). `input`
59
61
  preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
60
62
  metadata and transport/authentication fields removed by Cogover.
61
63
 
@@ -175,7 +175,8 @@ const approvers = chain?.tiers.flatMap(tier =>
175
175
  ## Choose the fields to read
176
176
 
177
177
  Every read names its fields: the slugs the script uses, or `"*"` for every field that
178
- the identity in use and the project's identity policy may read. A read without
178
+ the identity in use may read (with `data.asUser()` or `data.asSystem()`, only the fields
179
+ that the project's identity policy grants). A read without
179
180
  `fields` throws `ValidationError` (`fields is required: pass field slugs or "*"
180
181
  (@cogover/sdk 0.13.0+)`) before anything is sent.
181
182
 
@@ -225,7 +226,8 @@ if (missingIds.length > 0) log.warn("Accounts could not be read", { missingIds }
225
226
 
226
227
  Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
227
228
  `ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
228
- every capability call counts towards the project's limits.
229
+ every capability call and every record read counts towards the budgets of the
230
+ execution.
229
231
 
230
232
  ## Read linked records
231
233
 
@@ -265,8 +267,9 @@ for (const group of byStatus.groups) {
265
267
  ```
266
268
 
267
269
  Without `groupBy` the result is `{ values }`. A client from `data.asUser()`, like
268
- `data.object()` in a trigger or a job that runs as a user, cannot group and supports
269
- only counts and number metrics; use `data.asSystem()` there. Aggregates follow record writes after about one second,
270
+ `data.object()` in a trigger or a job that runs as a user or in a local Development
271
+ Session started by `cogover-dev run`, cannot group and supports only counts and number
272
+ metrics; use `data.asSystem()` there, or try grouping on a published version. Aggregates follow record writes after about one second,
270
273
  so a record saved just before may not be counted yet. See
271
274
  [Aggregates](api-reference/records.md#aggregates) for every metric and limit.
272
275
 
@@ -406,7 +409,16 @@ and the JWT algorithm names.
406
409
  - Cogover authentication credentials are never exposed to module code. Access is
407
410
  limited to the configured Objects, operations, and fields.
408
411
  - TypeScript types do not replace runtime validation of business input.
409
- - Cogover limits capability calls, request and response sizes, and execution time.
412
+ - Cogover limits, for each execution, the capability calls, the local calls (`crypto`,
413
+ `org` without display data), the records read and written, request and response
414
+ sizes, and execution time. An HTTP route may make 100 capability calls and read
415
+ 10,000 records; a background job 1,000 calls and 50,000 records. A call that would go
416
+ over a budget throws `RateLimitError` with `details.budget`; waiting does not help.
417
+ - `limits.usage()` (also `context.limits`) tells how much of each budget the execution
418
+ has used, without a capability call. Use it to hand the rest of a long task to a
419
+ background job before a budget runs out.
420
+ - Totals and counts do not need to read records: `records.aggregate` is one capability
421
+ call whatever the number of records.
410
422
  - Do not automatically retry writes after a timeout because the commit outcome may
411
423
  be unknown.
412
424
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,