@cogover/sdk 0.12.2 → 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.
@@ -0,0 +1,183 @@
1
+ import { CogoverApiError, ValidationError } from "../errors.js";
2
+ import { isRecord } from "./values.js";
3
+ /** Refusal of a read without a valid `fields` option; Cogover refuses such a read with the same message. */
4
+ export const FIELDS_REQUIRED = 'fields is required: pass field slugs or "*" (@cogover/sdk 0.13.0+)';
5
+ /** Refusal of a grouped aggregate on a client from `asUser()`; Cogover refuses it with the same message. */
6
+ export const AS_USER_GROUP_BY = "aggregate with groupBy is not supported for asUser(); use the caller or asSystem()";
7
+ /** Refusal of a metric that a client from `asUser()` cannot compute; Cogover refuses it with the same message. */
8
+ const AS_USER_METRICS = "asUser() without groupBy supports only count on id and count, sum, avg, min and max on "
9
+ + "number fields; use the caller or asSystem()";
10
+ export const MAX_METRICS = 20;
11
+ export const MAX_GROUP_BY_FIELDS = 3;
12
+ export const MAX_GROUPS = 5000;
13
+ const FIELD_SLUG = /^[A-Za-z_][A-Za-z0-9_]*$/u;
14
+ const METRIC_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/u;
15
+ const METRIC_OPERATIONS = new Set(["count", "sum", "avg", "min", "max", "countDistinct"]);
16
+ /** Validates the `fields` option of `get`, `getMany` and `list`. */
17
+ export function normalizeFieldSelection(value) {
18
+ if (value === "*") {
19
+ return "*";
20
+ }
21
+ if (!Array.isArray(value) || value.length === 0) {
22
+ throw new ValidationError(FIELDS_REQUIRED);
23
+ }
24
+ const slugs = new Set();
25
+ for (const item of value) {
26
+ const slug = typeof item === "string" ? item.trim() : "";
27
+ // `["*"]` lands here too: "*" is only accepted on its own, not inside the list.
28
+ if (!FIELD_SLUG.test(slug)) {
29
+ throw new ValidationError(FIELDS_REQUIRED);
30
+ }
31
+ slugs.add(slug);
32
+ }
33
+ return [...slugs];
34
+ }
35
+ /**
36
+ * Validates the `expandLookups` option against the requested fields. `undefined` means that no lookup is expanded;
37
+ * Cogover checks that each named field is a lookup and that the linked fields exist.
38
+ */
39
+ export function normalizeExpandLookups(value, fields) {
40
+ if (value === undefined || value === false) {
41
+ return undefined;
42
+ }
43
+ if (value === true) {
44
+ return true;
45
+ }
46
+ if (!isRecord(value)) {
47
+ throw new ValidationError('expandLookups must be true or an object that maps lookup field slugs to field slugs or "*"');
48
+ }
49
+ const lookupFields = Object.keys(value);
50
+ if (lookupFields.length === 0) {
51
+ throw new ValidationError("expandLookups must name at least one lookup field");
52
+ }
53
+ // No prototype, so that a field slug such as `__proto__` stays an ordinary key.
54
+ const normalized = Object.create(null);
55
+ for (const lookupField of lookupFields) {
56
+ if (!FIELD_SLUG.test(lookupField)) {
57
+ throw new ValidationError(`Invalid expandLookups field slug '${lookupField}'`);
58
+ }
59
+ if (fields !== "*" && !fields.includes(lookupField)) {
60
+ throw new ValidationError(`expandLookups field '${lookupField}' must also be listed in fields`);
61
+ }
62
+ const linkedFields = value[lookupField];
63
+ if (linkedFields === "*") {
64
+ normalized[lookupField] = "*";
65
+ continue;
66
+ }
67
+ const invalid = () => new ValidationError(`expandLookups.${lookupField} must be "*" or a non-empty array of field slugs`);
68
+ if (!Array.isArray(linkedFields) || linkedFields.length === 0) {
69
+ throw invalid();
70
+ }
71
+ const slugs = new Set();
72
+ for (const item of linkedFields) {
73
+ const slug = typeof item === "string" ? item.trim() : "";
74
+ if (!FIELD_SLUG.test(slug)) {
75
+ throw invalid();
76
+ }
77
+ slugs.add(slug);
78
+ }
79
+ normalized[lookupField] = [...slugs];
80
+ }
81
+ return normalized;
82
+ }
83
+ /**
84
+ * Validates the options of `records.aggregate` and converts each metric to `{ op, field }`. `delegated` is true for
85
+ * a client from `asUser()`, which cannot group.
86
+ */
87
+ export function normalizeAggregateOptions(options, delegated) {
88
+ if (!isRecord(options)) {
89
+ throw new ValidationError("aggregate() requires an options object with metrics");
90
+ }
91
+ const { where, groupBy, metrics, limit } = options;
92
+ if (groupBy !== undefined && delegated) {
93
+ throw new ValidationError(AS_USER_GROUP_BY);
94
+ }
95
+ const normalizedMetrics = normalizeMetrics(metrics);
96
+ if (delegated) {
97
+ // The other limits of asUser() depend on the field types, which Cogover checks.
98
+ const distinct = Object.keys(normalizedMetrics).find(name => normalizedMetrics[name].op === "countDistinct");
99
+ if (distinct !== undefined) {
100
+ throw new ValidationError(`metrics.${distinct}: ${AS_USER_METRICS}`);
101
+ }
102
+ }
103
+ if (groupBy === undefined) {
104
+ if (limit !== undefined) {
105
+ throw new ValidationError("aggregate() accepts limit only together with groupBy");
106
+ }
107
+ return where === undefined ? { metrics: normalizedMetrics } : { where, metrics: normalizedMetrics };
108
+ }
109
+ const normalizedGroupBy = normalizeGroupBy(groupBy);
110
+ if (limit !== undefined
111
+ && (typeof limit !== "number" || !Number.isSafeInteger(limit) || limit < 1 || limit > MAX_GROUPS)) {
112
+ throw new ValidationError(`aggregate() limit must be an integer from 1 to ${MAX_GROUPS}`);
113
+ }
114
+ return {
115
+ ...(where === undefined ? {} : { where }),
116
+ groupBy: normalizedGroupBy,
117
+ metrics: normalizedMetrics,
118
+ ...(limit === undefined ? {} : { limit }),
119
+ };
120
+ }
121
+ function normalizeMetrics(value) {
122
+ const names = isRecord(value) ? Object.keys(value) : [];
123
+ if (!isRecord(value) || names.length === 0 || names.length > MAX_METRICS) {
124
+ throw new ValidationError(`aggregate() requires metrics: an object with 1 to ${MAX_METRICS} named metrics`);
125
+ }
126
+ const normalized = Object.create(null);
127
+ for (const name of names) {
128
+ if (!METRIC_NAME.test(name)) {
129
+ throw new ValidationError(`Invalid metric name '${name}': use a letter followed by up to 63 letters, digits or underscores`);
130
+ }
131
+ const metric = value[name];
132
+ const operations = isRecord(metric) ? Object.keys(metric) : [];
133
+ const op = operations[0];
134
+ const field = isRecord(metric) && op !== undefined && typeof metric[op] === "string"
135
+ ? metric[op].trim()
136
+ : "";
137
+ if (operations.length !== 1 || op === undefined || !METRIC_OPERATIONS.has(op) || !FIELD_SLUG.test(field)) {
138
+ throw new ValidationError(`Metric '${name}' must be exactly one of { count }, { sum }, { avg }, { min }, `
139
+ + "{ max } or { countDistinct } with a field slug");
140
+ }
141
+ normalized[name] = { op, field };
142
+ }
143
+ return normalized;
144
+ }
145
+ function normalizeGroupBy(value) {
146
+ const message = `aggregate() groupBy must list 1 to ${MAX_GROUP_BY_FIELDS} field slugs`;
147
+ if (!Array.isArray(value) || value.length === 0) {
148
+ throw new ValidationError(message);
149
+ }
150
+ const slugs = new Set();
151
+ for (const item of value) {
152
+ const slug = typeof item === "string" ? item.trim() : "";
153
+ if (!FIELD_SLUG.test(slug)) {
154
+ throw new ValidationError(`Invalid groupBy field slug '${String(item)}'`);
155
+ }
156
+ slugs.add(slug);
157
+ }
158
+ if (slugs.size > MAX_GROUP_BY_FIELDS) {
159
+ throw new ValidationError(message);
160
+ }
161
+ return [...slugs];
162
+ }
163
+ /** Checks the shape of a `records.aggregate` result before the script sees it. */
164
+ export function requireAggregateResult(result, request) {
165
+ const metricNames = Object.keys(request.metrics);
166
+ const validValues = (values) => isRecord(values) && metricNames.every(name => {
167
+ const value = values[name];
168
+ return value === null || (typeof value === "number" && Number.isFinite(value));
169
+ });
170
+ const valid = isRecord(result) && (request.groupBy === undefined
171
+ ? validValues(result.values)
172
+ : Array.isArray(result.groups) && typeof result.truncated === "boolean"
173
+ && result.groups.every(group => isRecord(group) && validValues(group.values) && isRecord(group.key)
174
+ && request.groupBy.every(slug => isGroupKeyValue(group.key[slug]))));
175
+ if (!valid) {
176
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "records.aggregate returned an invalid result");
177
+ }
178
+ return result;
179
+ }
180
+ function isGroupKeyValue(value) {
181
+ return typeof value === "string" || typeof value === "boolean"
182
+ || (typeof value === "number" && Number.isFinite(value));
183
+ }
@@ -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/records.d.ts CHANGED
@@ -1,10 +1,24 @@
1
+ import type { WorkspaceObjects } from "./workspace.js";
1
2
  export type CogoverRecordId = string & {
2
3
  readonly __cogoverRecordIdBrand: unique symbol;
3
4
  };
5
+ /** Fields of a linked record: the target Object's fields when it is declared in `WorkspaceObjects`. */
6
+ type LinkedRecordFields<TObjectSlug extends string> = TObjectSlug extends keyof WorkspaceObjects ? Readonly<Partial<WorkspaceObjects[TObjectSlug]>> : Readonly<Record<string, unknown>>;
7
+ /** Value of a lookup or reference field: the linked record. */
4
8
  export interface RecordReference<TObjectSlug extends string = string> {
5
9
  readonly id: CogoverRecordId;
10
+ /**
11
+ * Name of the linked record. A record read through `data` without `expandLookups` has `""` here, except in a
12
+ * `reference` field, which stores the name with the record; so does a linked record that could not be read.
13
+ * The `new` and `old` values of a record trigger always carry the name.
14
+ */
6
15
  readonly name: string;
7
16
  readonly objectSlug?: TObjectSlug;
17
+ /**
18
+ * Fields of the linked record, present only when the read expanded this lookup with `expandLookups` and the
19
+ * linked record could be read. Lookups inside these fields are not expanded.
20
+ */
21
+ readonly fields?: LinkedRecordFields<TObjectSlug>;
8
22
  }
9
23
  export interface UrlValue {
10
24
  readonly url: string;
@@ -25,6 +39,10 @@ export interface CogoverRecord<TFields> {
25
39
  readonly updatedAt: number;
26
40
  readonly createdBy?: {
27
41
  readonly id: string;
42
+ /**
43
+ * `""` unless the read used `expandLookups`; then the `name` field of the creator's personnel record,
44
+ * which can be a generated code rather than the person's full name.
45
+ */
28
46
  readonly name: string;
29
47
  };
30
48
  };
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
@@ -251,7 +252,10 @@ is not reached. When jobs are not enabled for the Workspace, the error is
251
252
  is `"system"`, and `data.object()` works only if the project's approved identity
252
253
  policy sets `allowInternalSystem: true`; otherwise its calls throw
253
254
  `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
254
- `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
255
+ `data.asUser()` and `data.asSystem()` follow the identity policy as usual. In a run
256
+ that has a user, `records.aggregate` through `data.object()` has the limits of
257
+ `data.asUser()`; use `data.asSystem()` to group (see
258
+ [Aggregates](records.md#aggregates)).
255
259
  - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
256
260
  `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
257
261
  within the runtime limits of the job lane.
@@ -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.