commitlayer 0.1.1 → 0.1.4

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
@@ -1,10 +1,10 @@
1
1
  # commitlayer (JavaScript / TypeScript)
2
2
 
3
3
  Record agent actions, push facts from systems of record, read verdicts and draft contracts. Zero runtime
4
- dependencies; Node 18+ (uses the global `fetch`). Ships with TypeScript types.
4
+ dependencies; Node 20+ (uses the global `fetch` and `crypto`). Ships with TypeScript types.
5
5
 
6
6
  ```bash
7
- npm install ./sdk/js # from this repository (run `npm run build` in sdk/js first)
7
+ npm install commitlayer
8
8
  export COMMITLAYER_API_KEY=spk_... # the agent runtime's key: a *recorder* key (records actions, nothing else)
9
9
  export COMMITLAYER_EVIDENCE_KEY=spk_... # the pipeline's key: an *evidence* key bound to the sources it pushes for
10
10
  # COMMITLAYER_API_URL defaults to https://api.commitlayer.ai. One credential per side of the line: the key that
@@ -113,10 +113,27 @@ if (v.timed_out) {
113
113
 
114
114
  The API holds each call for up to 60 seconds; the SDK loops. The gate reads evidence; it never changes a verdict.
115
115
 
116
+ ## Install a workflow pack (drafts, never activation)
117
+
118
+ ```ts
119
+ const { items } = await cl.packs.list();
120
+ const detail = await cl.packs.get("x402_service_delivery");
121
+ const effective = await cl.packs.configure("x402_service_delivery", { purchase_api_call: { approved_limit: 2 } });
122
+ const report = await cl.packs.dryRun("x402_service_delivery", { purchase_api_call: { approved_limit: 2 } });
123
+ const out = await cl.packs.install("x402_service_delivery", { purchase_api_call: { approved_limit: 2 } }, { confirm: true });
124
+ console.log(out.activation); // the person's step: POST /v1/contracts/{id}/select
125
+ const mapping = await cl.packs.recorderMapping("x402_service_delivery");
126
+ ```
127
+
128
+ `configure` and `dryRun` write nothing; `install` saves the configured contracts as **drafts** and never
129
+ activates. Below the pack's minimum plan the service answers `402 plan_required` with `upgrade_to`.
130
+
116
131
  ## Errors
117
132
 
118
133
  Every method throws a `CommitLayerError` for a 4xx or 5xx response, with `status`, `code`, `message` and
119
- `details` taken from the API's `{ error: { code, message, details } }` body.
134
+ `details` taken from the API's `{ error: { code, message, details } }` body. Two more fields say what happened
135
+ on the way: `retryAfterMs`, the wait the server stated in `Retry-After` in milliseconds (`undefined` when the
136
+ answer carried none), and `attempts`, how many times the request was sent (see [Retries](#retries)).
120
137
 
121
138
  ```js
122
139
  import { CommitLayerError } from "commitlayer";
@@ -130,6 +147,95 @@ try {
130
147
  }
131
148
  ```
132
149
 
150
+ ## Retries
151
+
152
+ The API refuses a request it cannot take right now with an answer made to be retried: `503 busy` when the write
153
+ path or the database is full, `429 workspace_busy` when one workspace already has its share of the write path in
154
+ progress, `429 rate_limited` past the plan's requests a minute. Each carries a `Retry-After` header. The
155
+ client waits the stated time and sends the same request again, so a burst of a few dozen writes is a short wait,
156
+ not an error.
157
+
158
+ - **Retried:** an answer with status `429` or `503` **and** a `Retry-After` header the client can read: a number
159
+ of seconds, whole or decimal, or an HTTP-date (`Wed, 21 Oct 2026 07:28:00 GMT`). On every method, reads included.
160
+ - **Not retried:** any other status (`400`, `401`, `402`, `404`, `409`, `500`, `502`, `504`, ...); a `429` or `503`
161
+ without `Retry-After`, or with one that is not a wait (`soon`, `-1`); a network error or a timeout, because after
162
+ those the client cannot know whether the request was applied.
163
+ - **The wait:** the time the server stated, never less, plus a random addition of up to twice as much, so that
164
+ requests refused together come back spread out and are not refused together again: one stated second is a wait
165
+ of one to three. Never more than `maxRetryWaitMs` (default `10000`); close to it the addition is a share of
166
+ what is left under it. A stated wait above `maxRetryWaitMs` is not waited for at all: the error is thrown at
167
+ once. That is what happens to `429 fair_use_exceeded`, which states the seconds until midnight UTC.
168
+ - **How many:** `maxRetries` times after the first attempt, default `3`. **`maxRetries: 0` turns retrying off.**
169
+ - **Worst case:** the waits add at most `maxRetries × maxRetryWaitMs`, 30 seconds with the defaults. The API's own
170
+ busy answers state one second, so a call refused once waits one to three seconds and a call that uses all
171
+ three retries waits three to nine. `timeoutMs` (default 20 seconds) applies to each attempt and the wait is not
172
+ counted against it, so the longest a call can take is
173
+ `(maxRetries + 1) × timeoutMs + maxRetries × maxRetryWaitMs`: 110 seconds with the defaults. That is an API
174
+ that answers slowly and then refuses, every time: the retries multiply the time to a failure, and a smaller
175
+ `maxRetries` or `timeoutMs` bounds it.
176
+ - **The same request every time:** each attempt sends the same body, fixed when the call starts. The `action_id`
177
+ the client generates when you give none is generated once, before the first attempt, `requested_at` is set
178
+ once, and a retry sends `params`, the facts or an inline action as they were at that moment, whatever your
179
+ code has done to those objects during the wait. The API records one action however many attempts it took.
180
+
181
+ ```js
182
+ const cl = new Client({
183
+ maxRetries: 2, // default 3; 0 is off
184
+ maxRetryWaitMs: 2_000, // default 10000
185
+ onRetry: (r) => console.warn(`commitlayer: ${r.status} ${r.code} on ${r.method} ${r.path}, retry ${r.attempt} of ${r.maxRetries} in ${r.waitMs} ms`),
186
+ });
187
+ ```
188
+
189
+ Nothing is logged unless you pass `onRetry`; it is called once per retry, before the wait, and never receives
190
+ the API key or the request body. When the retries are used up the error is the **last** answer's
191
+ `CommitLayerError`, with `retryAfterMs` (what the server asked for) and `attempts` (how many times the request
192
+ was sent).
193
+
194
+ **How large a burst.** The API works on a few writes of one workspace at a time, lets as many wait and refuses
195
+ the rest at once. Measured against an API set to work on three writes of a workspace at a time, with the client's
196
+ defaults, 100 `recordAction` calls started at the same instant from one workspace were all recorded, within about
197
+ seven seconds and mostly on the second attempt; with `maxRetries: 0` most of a burst of 30 was refused. Three
198
+ retries are sized for that, not for any burst. When a write took several times longer (a contract that reads
199
+ more), 60 at once were still all recorded and 100 at once left a few calls with `429 workspace_busy` after about
200
+ ten seconds. For bursts of that size send the writes a few at a time, or raise `maxRetries`. Retries make a burst
201
+ succeed, not go faster.
202
+
203
+ Two answers still reach your code as errors:
204
+
205
+ - **`429 rate_limited` past the plan's writes a minute.** It is retried like the others, but the wait it states
206
+ is for one request. A burst larger than the plan allows in a minute cannot fit into a few seconds of waiting,
207
+ and the calls beyond the allowance end in `429 rate_limited` once their retries are used up. Every attempt is
208
+ a request to the API and counts against the plan's requests a minute, so a large burst that is mostly refused
209
+ and retried spends that budget as well.
210
+ - **A plain `503` without `Retry-After`.** With more than about 64 requests in flight to one of its processes the
211
+ API answers `503 Service Unavailable` as plain text, with no header to wait for. The client reports it with
212
+ code `http_error` and does not retry it, so a client that opens a hundred connections at once can see most of
213
+ its calls fail at once. Bound the concurrency in your code.
214
+
215
+ One request is the exception. `POST /v1/actions` is idempotent on `action_id`, and the API may answer `503 busy`
216
+ after the action itself is stored, so a recording that names no `action_id` is sent once and never repeated: it
217
+ throws on the first refusal, a `429` included. `recordAction` and the `action` wrapper always name one; this only
218
+ concerns a body you build yourself for `cl.request("POST", "/v1/actions", ...)` or an inline
219
+ `cl.verify({ action })` that is stored. For the same reason a `503 busy` that `recordAction` still throws, after
220
+ its retries or without any, does not prove the action is absent. `cl.getAction(actionId)` says whether it is
221
+ there, and recording it again under the same `action_id` never makes a second action: the API returns the stored
222
+ one, or answers `409 conflict` when the new request differs from it, for instance in a `requestedAt` you did not
223
+ pass again.
224
+
225
+ The `action` wrapper awaits the record before it runs your function, so a retried record delays the function by
226
+ the waits above. Where a few seconds matter more than the record, give the client a smaller `maxRetries` and
227
+ `maxRetryWaitMs`. A retried poll can add the same waits to `waitForSettlement({ timeoutMs })`.
228
+
229
+ The wait is an ordinary timer and a call cannot be cancelled once it has started. A call you do not await
230
+ therefore keeps a Node process alive until it settles, waits included: a script that fires a record and ends
231
+ stays open for up to `maxRetries × maxRetryWaitMs` while the API keeps refusing. Await the call, or build that
232
+ client with `maxRetries: 0`.
233
+
234
+ **In a browser** a script may read `Retry-After` on a cross-origin response only when the server lists it in
235
+ `Access-Control-Expose-Headers`, and the API does not list it. A client running in a page therefore does not see
236
+ the header and does not retry: it throws on the first refusal, as it did before 0.1.4. Node, Deno, Bun and edge
237
+ runtimes see the header.
238
+
133
239
  ## TypeScript
134
240
 
135
241
  ```ts
@@ -152,6 +258,12 @@ const { refundId } = await refund("order_10231", 180);
152
258
  ```
153
259
 
154
260
  For tests, inject a transport instead of a network: `new Client({ transport: async (method, path, body) => ({ status: 201, json: {} }) })`.
261
+ A transport may also return the response headers, `{ status, json, headers }`: a `Headers` object or a plain
262
+ record, where `Retry-After` is found under any case of its name, or another object with a `get` such as a `Map`,
263
+ which is asked for `retry-after` and for `Retry-After`. A transport that returns only `status` and `json` never
264
+ triggers a retry. The first attempt is given the body object itself and a retry a copy of what it
265
+ was when the call started. `sleep`, `random` and `now` replace the wait, the random addition and the clock, so a test of
266
+ your own retry handling does not have to sleep.
155
267
 
156
268
  ## Develop
157
269
 
package/dist/index.d.ts CHANGED
@@ -18,20 +18,79 @@
18
18
  * never recorded rather than one that never happened. Set `failOpen: false` to throw.
19
19
  *
20
20
  * Verification itself is done by the API from the systems of record; nothing here consults the function's result.
21
+ *
22
+ * A request the API refuses with 429 or 503 and a `Retry-After` header is sent again after the stated wait, up to
23
+ * `maxRetries` times (default 3; 0 turns it off). The API answers that way when it is busy or the workspace is
24
+ * past a rate, and a retry is the same request: the same body, so the same `action_id`. The wait is the stated
25
+ * time plus a random addition of up to twice as much, so requests refused together come back spread out. No
26
+ * other answer is retried, and neither is a network error or a timeout.
21
27
  */
22
- export declare const VERSION = "0.1.0";
28
+ export declare const VERSION = "0.1.4";
23
29
  export type Json = Record<string, unknown>;
24
- /** Low-level transport, injectable for tests: resolves with the HTTP status and the parsed JSON body. */
25
- export type Transport = (method: string, path: string, body?: Json | null) => Promise<{
30
+ /**
31
+ * Response headers as a transport may return them: the `Headers` of a fetch response, another object with a
32
+ * `get`, or a plain record of name to value. In a record names are matched without regard to case; a `get` is
33
+ * asked for `retry-after` and then for `Retry-After`, so one that is case-sensitive is read under either spelling.
34
+ */
35
+ export type ResponseHeaders = {
36
+ get(name: string): string | null | undefined;
37
+ } | Record<string, string | string[] | null | undefined>;
38
+ /** What a transport resolves with. `headers` is optional: without it the client never sees `Retry-After` and never retries. */
39
+ export interface TransportResponse {
26
40
  status: number;
27
41
  json: unknown;
28
- }>;
42
+ headers?: ResponseHeaders | null;
43
+ }
44
+ /**
45
+ * Low-level transport, injectable for tests: resolves with the HTTP status and the parsed JSON body, and may
46
+ * add the response headers. A retry calls it again with the same arguments.
47
+ */
48
+ export type Transport = (method: string, path: string, body?: Json | null) => Promise<TransportResponse>;
49
+ /** One retry, as `onRetry` is told about it. It never carries the API key or the request body. */
50
+ export interface RetryInfo {
51
+ method: string;
52
+ path: string;
53
+ /** The answer that is being retried: 429 or 503, and the error code of its body. */
54
+ status: number;
55
+ code: string;
56
+ /** The attempt that was refused, counting from 1. */
57
+ attempt: number;
58
+ maxRetries: number;
59
+ /** The wait the server stated in `Retry-After`. */
60
+ retryAfterMs: number;
61
+ /** The wait the client is about to make: the stated time plus the random addition, at most `maxRetryWaitMs`. */
62
+ waitMs: number;
63
+ }
29
64
  export interface ClientOptions {
30
65
  apiKey?: string;
31
66
  apiUrl?: string;
67
+ /** Per attempt; default 20 seconds. The wait before a retry is not counted against it. */
32
68
  timeoutMs?: number;
33
69
  transport?: Transport;
34
70
  agentId?: string;
71
+ /**
72
+ * How many times a request refused with 429 or 503 and a `Retry-After` header is sent again; default 3,
73
+ * 0 turns retrying off. No other answer is retried, and neither is a network error or a timeout. A negative
74
+ * value is refused by the constructor.
75
+ */
76
+ maxRetries?: number;
77
+ /**
78
+ * The longest wait the client will make before one retry, in milliseconds; default 10000. A `Retry-After`
79
+ * above it is not waited for: the error is thrown at once, with the stated wait in `retryAfterMs`. A value
80
+ * above 2147483647 (the longest a timer can run, about 24 days) is taken as that.
81
+ */
82
+ maxRetryWaitMs?: number;
83
+ /** Called once per retry, before the wait, e.g. to log it. What it throws is ignored. */
84
+ onRetry?: (info: RetryInfo) => void;
85
+ /** The wait itself; default a `setTimeout`. Replaceable (a cancellation-aware sleep, a fake in tests). */
86
+ sleep?: (ms: number) => Promise<void>;
87
+ /**
88
+ * The random source of the addition to the wait, in [0, 1); default `Math.random`. The addition is this share
89
+ * of twice the stated wait, or of what is left under `maxRetryWaitMs` when that is less. Replaceable for tests.
90
+ */
91
+ random?: () => number;
92
+ /** Clock in ms, used to read a `Retry-After` given as a date; default `Date.now`. Replaceable for tests. */
93
+ now?: () => number;
35
94
  }
36
95
  export interface RecordActionOptions {
37
96
  params?: Json;
@@ -89,7 +148,17 @@ export declare class CommitLayerError extends Error {
89
148
  readonly status: number;
90
149
  readonly code: string;
91
150
  readonly details: unknown;
92
- constructor(status: number, code: string, message: string, details?: unknown);
151
+ /**
152
+ * The wait the server stated in `Retry-After`, in milliseconds; undefined when the answer carried no
153
+ * `Retry-After` the client could read.
154
+ */
155
+ readonly retryAfterMs: number | undefined;
156
+ /** How many times the request was sent, this answer included; undefined when the error is not an API answer. */
157
+ readonly attempts: number | undefined;
158
+ constructor(status: number, code: string, message: string, details?: unknown, retry?: {
159
+ retryAfterMs?: number;
160
+ attempts?: number;
161
+ });
93
162
  toString(): string;
94
163
  }
95
164
  export declare class Client {
@@ -97,9 +166,27 @@ export declare class Client {
97
166
  readonly apiUrl: string;
98
167
  readonly timeoutMs: number;
99
168
  readonly agentId: string | undefined;
169
+ /** Retries after the first attempt for a 429 or 503 answer that carries `Retry-After`; 0 is off. */
170
+ readonly maxRetries: number;
171
+ /** The longest wait before one retry; a longer `Retry-After` is thrown at once. */
172
+ readonly maxRetryWaitMs: number;
100
173
  private readonly transport;
174
+ private readonly onRetry;
175
+ private readonly sleep;
176
+ private readonly random;
177
+ private readonly now;
101
178
  constructor(options?: ClientOptions);
102
179
  private http;
180
+ /**
181
+ * One request, sent again while the API refuses it with 429 or 503 and a `Retry-After` the client will wait
182
+ * for, at most `maxRetries` more times. The body is fixed when the call starts: the first attempt is given
183
+ * `body` itself and every retry a copy of what it was at that moment, so a retry carries the same
184
+ * `action_id`, `requested_at` and parameters as the first attempt even when the caller has changed its own
185
+ * objects during the wait. The API applies an action once per `action_id`, and answers 409 to the same id
186
+ * with a different request. What the transport throws (a network error, a timeout) is never retried: the
187
+ * client cannot know whether that request was applied. A recording that names no `action_id` is sent once
188
+ * only (see `repeatable`).
189
+ */
103
190
  private call;
104
191
  /**
105
192
  * `POST /v1/actions`: record one action. Returns `{action, verification, allowance}`. The verification is
@@ -111,9 +198,16 @@ export declare class Client {
111
198
  * source; settlement waits on it instead of the clock.
112
199
  */
113
200
  pushFacts(facts: Json[], opts?: PushFactsOptions): Promise<Json>;
114
- /** `POST /v1/actions/verify`: verify now, by id or inline. `dryRun` stores nothing. */
201
+ /**
202
+ * `POST /v1/actions/verify`: verify now, by id or inline. `dryRun` stores nothing. An inline `action` that is
203
+ * stored and names no `action_id` is sent once only, never retried.
204
+ */
115
205
  verify(opts?: VerifyOptions): Promise<Json>;
116
- /** Any endpoint, with the client's auth and error handling: `request("GET", "/v1/actions/x/wait?timeout=30")`. */
206
+ /**
207
+ * Any endpoint, with the client's auth, error handling and retries: `request("GET", "/v1/actions/x/wait?timeout=30")`.
208
+ * A `POST /v1/actions` body without an `action_id` is sent once only: the API would record a new action on
209
+ * every attempt.
210
+ */
117
211
  request(method: string, path: string, body?: Json | null): Promise<Json>;
118
212
  /** `GET /v1/actions/{ref}`: `ref` is the `action_id` or the internal id. */
119
213
  getAction(ref: string): Promise<Json>;
@@ -121,7 +215,9 @@ export declare class Client {
121
215
  * The completion gate: resolves when the action's verdict settles or `timeoutMs` passes, with the
122
216
  * verification (`status` is `settled` or, on timeout, `pending`; `timed_out` says which). The API holds each
123
217
  * call for up to 60 seconds; this loops. A workflow should not tell the customer "done" before this returns a
124
- * settled PASS; FAIL routes to recovery; a timeout is the workflow's decision.
218
+ * settled PASS; FAIL routes to recovery; a timeout is the workflow's decision. A poll the API refuses with
219
+ * `Retry-After` is retried like any other request, which can add up to `maxRetries` times `maxRetryWaitMs` to
220
+ * `timeoutMs`.
125
221
  */
126
222
  waitForSettlement(ref: string, opts?: {
127
223
  timeoutMs?: number;
@@ -135,6 +231,12 @@ export declare class Client {
135
231
  validateContract(yaml: string): Promise<Json>;
136
232
  /** `POST /v1/contracts`: save a version. The response carries `warnings` when it is weaker than the last one. */
137
233
  saveContract(yaml: string): Promise<Json>;
234
+ /**
235
+ * The workflow packs (`/v1/packs`): `client.packs.list()`, `get`, `configure`, `dryRun`, `install`, `coverage`,
236
+ * `recorderMapping`. Install creates drafts and never activates; activation stays a person's
237
+ * `POST /v1/contracts/{id}/select`.
238
+ */
239
+ get packs(): Packs;
138
240
  /**
139
241
  * Record each call of the wrapped function as an action under `contractId` before it runs.
140
242
  *
@@ -145,4 +247,35 @@ export declare class Client {
145
247
  */
146
248
  action<F extends AnyFn>(contractId: string, opts: ActionOptions<F>): (fn: F) => Wrapped<F>;
147
249
  }
250
+ /** `{workflow_id: {parameter_key: value}}`, as the pack's manifest names them. */
251
+ export type PackConfiguration = Record<string, Record<string, unknown>>;
252
+ /**
253
+ * `/v1/packs`: the workflow pack library. Reads take any member; `configure` and `dryRun` write nothing and take an
254
+ * analyst; `install` saves the configured contracts as **drafts** (never activates) and needs `confirm: true`.
255
+ */
256
+ export declare class Packs {
257
+ private readonly client;
258
+ constructor(client: Client);
259
+ /** `GET /v1/packs`: `{items: PackSummary[]}`. */
260
+ list(): Promise<Json>;
261
+ /** `GET /v1/packs/{id}`: the summary plus contracts, recorder mapping, fixtures, templates, readme, versions and requirements. */
262
+ get(packId: string): Promise<Json>;
263
+ /** `POST /v1/packs/{id}/configure`: the configured contracts, the values in force and every weakening. Nothing is written. */
264
+ configure(packId: string, configuration?: PackConfiguration): Promise<Json>;
265
+ /** `POST /v1/packs/{id}/dry-run`: every fixture case through the engine, in a savepoint; nothing persists. */
266
+ dryRun(packId: string, configuration?: PackConfiguration, opts?: {
267
+ workflow?: string;
268
+ }): Promise<Json>;
269
+ /**
270
+ * `POST /v1/packs/{id}/install`: save the configured contracts as drafts and record the installation. Refused
271
+ * without `confirm: true`; 402 `plan_required` below the pack's minimum plan.
272
+ */
273
+ install(packId: string, configuration?: PackConfiguration, opts?: {
274
+ confirm?: boolean;
275
+ }): Promise<Json>;
276
+ /** `GET /v1/packs/{id}/coverage`. */
277
+ coverage(packId: string): Promise<Json>;
278
+ /** `GET /v1/packs/{id}/recorder-mapping`: the installed mapping, contract versions pinned. */
279
+ recorderMapping(packId: string): Promise<Json>;
280
+ }
148
281
  export {};
package/dist/index.js CHANGED
@@ -18,18 +18,33 @@
18
18
  * never recorded rather than one that never happened. Set `failOpen: false` to throw.
19
19
  *
20
20
  * Verification itself is done by the API from the systems of record; nothing here consults the function's result.
21
+ *
22
+ * A request the API refuses with 429 or 503 and a `Retry-After` header is sent again after the stated wait, up to
23
+ * `maxRetries` times (default 3; 0 turns it off). The API answers that way when it is busy or the workspace is
24
+ * past a rate, and a retry is the same request: the same body, so the same `action_id`. The wait is the stated
25
+ * time plus a random addition of up to twice as much, so requests refused together come back spread out. No
26
+ * other answer is retried, and neither is a network error or a timeout.
21
27
  */
22
- export const VERSION = "0.1.0";
28
+ export const VERSION = "0.1.4"; // kept equal to package.json; the tests check it
23
29
  export class CommitLayerError extends Error {
24
30
  status;
25
31
  code;
26
32
  details;
27
- constructor(status, code, message, details) {
33
+ /**
34
+ * The wait the server stated in `Retry-After`, in milliseconds; undefined when the answer carried no
35
+ * `Retry-After` the client could read.
36
+ */
37
+ retryAfterMs;
38
+ /** How many times the request was sent, this answer included; undefined when the error is not an API answer. */
39
+ attempts;
40
+ constructor(status, code, message, details, retry = {}) {
28
41
  super(message);
29
42
  this.name = "CommitLayerError";
30
43
  this.status = status;
31
44
  this.code = code;
32
45
  this.details = details;
46
+ this.retryAfterMs = retry.retryAfterMs;
47
+ this.attempts = retry.attempts;
33
48
  }
34
49
  toString() {
35
50
  return `${this.code} (${this.status}): ${this.message}`;
@@ -47,17 +62,164 @@ function now() {
47
62
  function newActionId() {
48
63
  return "act_" + crypto.randomUUID().replace(/-/g, "");
49
64
  }
65
+ // ---------------- retry ----------------
66
+ /**
67
+ * The random addition to a wait is at most this many times the stated wait, so a burst refused together comes
68
+ * back spread over that time and not all at once: a wait of one stated second is between one and three. The
69
+ * API admits a few writes of one workspace at a time and refuses the rest at once, so calls that return within
70
+ * the same quarter second are refused together again; spread over two seconds they are admitted as they arrive.
71
+ */
72
+ const RETRY_SPREAD = 2;
73
+ /** The longest delay a timer takes; a longer one fires at once in Node and in browsers. */
74
+ const MAX_TIMER_MS = 2_147_483_647;
75
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
76
+ /** The `Retry-After` header of an answer, or undefined when the transport returned none. */
77
+ function retryAfterHeader(headers) {
78
+ if (!headers || typeof headers !== "object")
79
+ return undefined;
80
+ const get = headers.get;
81
+ if (typeof get === "function") {
82
+ try {
83
+ // A fetch `Headers` answers to any case; a `Map` or a hand-written `get` may know only one spelling.
84
+ const v = get.call(headers, "retry-after") ?? get.call(headers, "Retry-After");
85
+ return typeof v === "string" ? v : undefined;
86
+ }
87
+ catch {
88
+ return undefined; // headers that cannot be read are no headers: the answer itself is still reported
89
+ }
90
+ }
91
+ for (const [k, v] of Object.entries(headers)) {
92
+ if (k.toLowerCase() !== "retry-after")
93
+ continue;
94
+ const first = Array.isArray(v) ? v[0] : v;
95
+ if (typeof first === "string")
96
+ return first;
97
+ if (typeof first === "number")
98
+ return String(first);
99
+ }
100
+ return undefined;
101
+ }
102
+ /**
103
+ * `Retry-After` as milliseconds from `nowMs`: a number of seconds (whole or decimal, zero or more) or an
104
+ * HTTP-date (`Wed, 21 Oct 2026 07:28:00 GMT`; one in the past is zero). Undefined when the header is absent or
105
+ * is anything else, and an answer without a readable wait is never retried.
106
+ */
107
+ function retryAfterMsOf(headers, nowMs) {
108
+ const value = retryAfterHeader(headers)?.trim();
109
+ if (!value)
110
+ return undefined;
111
+ if (/^(\d+(\.\d*)?|\.\d+)$/.test(value)) {
112
+ // Rounded up, so the wait is never shorter than stated; toFixed drops the float noise of the product first.
113
+ const ms = Math.ceil(Number((Number(value) * 1000).toFixed(3)));
114
+ return Number.isFinite(ms) ? ms : undefined;
115
+ }
116
+ const m = /^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/.exec(value);
117
+ if (!m)
118
+ return undefined;
119
+ const month = MONTHS.indexOf(m[2].toLowerCase());
120
+ if (month < 0)
121
+ return undefined;
122
+ // Not a number when the date or the clock is not one: then there is no wait to read.
123
+ const ms = Date.UTC(Number(m[3]), month, Number(m[1]), Number(m[4]), Number(m[5]), Number(m[6])) - nowMs;
124
+ return Number.isFinite(ms) ? Math.max(0, ms) : undefined;
125
+ }
126
+ function defaultSleep(ms) {
127
+ // The call is waiting on this timer, so it is left referenced; once it fires nothing is left behind.
128
+ return new Promise((resolve) => setTimeout(resolve, ms));
129
+ }
130
+ /** A count or a duration from an option: a whole number, zero or more; the default when it is not given. */
131
+ function atLeastZero(name, value, fallback) {
132
+ if (value === undefined)
133
+ return fallback;
134
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
135
+ throw new Error(`${name} must be zero or more`);
136
+ return Math.floor(value);
137
+ }
138
+ /**
139
+ * The route of a request path as the server will read it: without query or fragment, percent-decoded, and with
140
+ * `/./`, `//` and a trailing slash folded away, so another spelling of the same path is the same route.
141
+ */
142
+ function routeOf(path) {
143
+ let route = path;
144
+ try {
145
+ route = new URL("http://x" + path).pathname; // drops the query and the fragment, resolves `.` and `..`
146
+ route = decodeURIComponent(route);
147
+ }
148
+ catch {
149
+ // A stray percent sign, or no path at all: the text as far as it could be read.
150
+ }
151
+ return route.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
152
+ }
153
+ /**
154
+ * Whether sending the request again can never record a second action. Recording is idempotent on `action_id`,
155
+ * and the API may answer 503 `busy` to `POST /v1/actions` after the action itself is stored (its verification
156
+ * then runs in the background). A recording that names no `action_id` would be given a new one by the API on
157
+ * every attempt, so it is never sent twice. `recordAction` always names one; a raw `request` and an inline
158
+ * `verify` carry whatever the caller wrote. Only `dry_run: true` itself counts as a dry run: the API reads the
159
+ * string `"false"` as false and stores the action.
160
+ */
161
+ function repeatable(method, path, body) {
162
+ if (method.toUpperCase() !== "POST" || !body || typeof body !== "object" || Array.isArray(body))
163
+ return true;
164
+ const route = routeOf(path);
165
+ if (route === "/v1/actions")
166
+ return Boolean(body.action_id);
167
+ if (route === "/v1/actions/verify" && body.dry_run !== true) {
168
+ const action = body.action;
169
+ if (action && typeof action === "object" && !Array.isArray(action))
170
+ return Boolean(action.action_id);
171
+ }
172
+ return true;
173
+ }
174
+ /**
175
+ * The body of a request, fixed as JSON text when the call starts: each call of the result gives a new copy of
176
+ * what the body was then, whatever the caller has done to its own objects since. Undefined when the body has no
177
+ * JSON form; such a request is sent once only.
178
+ */
179
+ function frozenBody(body) {
180
+ if (body == null)
181
+ return () => body;
182
+ try {
183
+ const text = JSON.stringify(body);
184
+ return typeof text === "string" ? () => JSON.parse(text) : undefined;
185
+ }
186
+ catch {
187
+ return undefined;
188
+ }
189
+ }
190
+ function apiError(status, json, retry) {
191
+ const err = json?.error;
192
+ if (err && typeof err === "object") {
193
+ const e = err;
194
+ return new CommitLayerError(status, e.code ?? "error", e.message ?? "", e.details, retry);
195
+ }
196
+ return new CommitLayerError(status, "error", JSON.stringify(json).slice(0, 300), undefined, retry);
197
+ }
50
198
  export class Client {
51
199
  apiKey;
52
200
  apiUrl;
53
201
  timeoutMs;
54
202
  agentId;
203
+ /** Retries after the first attempt for a 429 or 503 answer that carries `Retry-After`; 0 is off. */
204
+ maxRetries;
205
+ /** The longest wait before one retry; a longer `Retry-After` is thrown at once. */
206
+ maxRetryWaitMs;
55
207
  transport;
208
+ onRetry;
209
+ sleep;
210
+ random;
211
+ now;
56
212
  constructor(options = {}) {
57
213
  this.apiKey = options.apiKey || env("COMMITLAYER_API_KEY") || "";
58
214
  this.apiUrl = (options.apiUrl || env("COMMITLAYER_API_URL") || "https://api.commitlayer.ai").replace(/\/+$/, "");
59
215
  this.timeoutMs = options.timeoutMs ?? 20_000;
60
216
  this.agentId = options.agentId;
217
+ this.maxRetries = atLeastZero("maxRetries", options.maxRetries, 3);
218
+ this.maxRetryWaitMs = Math.min(atLeastZero("maxRetryWaitMs", options.maxRetryWaitMs, 10_000), MAX_TIMER_MS);
219
+ this.onRetry = options.onRetry;
220
+ this.sleep = options.sleep ?? defaultSleep;
221
+ this.random = options.random ?? Math.random;
222
+ this.now = options.now ?? Date.now;
61
223
  this.transport = options.transport ?? ((m, p, b) => this.http(m, p, b));
62
224
  if (!this.apiKey && !options.transport) {
63
225
  throw new Error("apiKey is required (or set COMMITLAYER_API_KEY)");
@@ -65,6 +227,7 @@ export class Client {
65
227
  }
66
228
  // ---------------- transport ----------------
67
229
  async http(method, path, body) {
230
+ // One controller and one timer per attempt: a retry starts with the whole of timeoutMs.
68
231
  const controller = new AbortController();
69
232
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
70
233
  try {
@@ -80,34 +243,77 @@ export class Client {
80
243
  body: body == null ? undefined : JSON.stringify(body),
81
244
  signal: controller.signal,
82
245
  });
246
+ const { status, headers } = res;
83
247
  const raw = await res.text();
84
248
  if (!raw)
85
- return { status: res.status, json: {} };
249
+ return { status, json: {}, headers };
86
250
  try {
87
- return { status: res.status, json: JSON.parse(raw) };
251
+ return { status, json: JSON.parse(raw), headers };
88
252
  }
89
253
  catch {
90
254
  const message = raw.slice(0, 300);
91
- if (res.status >= 400)
92
- return { status: res.status, json: { error: { code: "http_error", message } } };
93
- throw new CommitLayerError(res.status, "invalid_response", message);
255
+ if (status >= 400)
256
+ return { status, json: { error: { code: "http_error", message } }, headers };
257
+ throw new CommitLayerError(status, "invalid_response", message);
94
258
  }
95
259
  }
96
260
  finally {
97
261
  clearTimeout(timer);
98
262
  }
99
263
  }
264
+ /**
265
+ * One request, sent again while the API refuses it with 429 or 503 and a `Retry-After` the client will wait
266
+ * for, at most `maxRetries` more times. The body is fixed when the call starts: the first attempt is given
267
+ * `body` itself and every retry a copy of what it was at that moment, so a retry carries the same
268
+ * `action_id`, `requested_at` and parameters as the first attempt even when the caller has changed its own
269
+ * objects during the wait. The API applies an action once per `action_id`, and answers 409 to the same id
270
+ * with a different request. What the transport throws (a network error, a timeout) is never retried: the
271
+ * client cannot know whether that request was applied. A recording that names no `action_id` is sent once
272
+ * only (see `repeatable`).
273
+ */
100
274
  async call(method, path, body) {
101
- const { status, json } = await this.transport(method, path, body);
102
- if (status >= 400) {
103
- const err = json?.error;
104
- if (err && typeof err === "object") {
105
- const e = err;
106
- throw new CommitLayerError(status, e.code ?? "error", e.message ?? "", e.details);
275
+ // Taken before anything is awaited, so it is the request as the caller made it.
276
+ const again = this.maxRetries > 0 ? frozenBody(body) : undefined;
277
+ let sending = body;
278
+ for (let attempt = 1;; attempt++) {
279
+ const { status, json, headers } = await this.transport(method, path, sending);
280
+ if (status < 400)
281
+ return json;
282
+ const retryAfterMs = retryAfterMsOf(headers, this.now());
283
+ const error = apiError(status, json, { retryAfterMs, attempts: attempt });
284
+ if ((status !== 429 && status !== 503) ||
285
+ retryAfterMs === undefined ||
286
+ retryAfterMs > this.maxRetryWaitMs ||
287
+ attempt > this.maxRetries ||
288
+ again === undefined) {
289
+ throw error;
290
+ }
291
+ const next = again();
292
+ if (!repeatable(method, path, next))
293
+ throw error;
294
+ // Never less than the server stated, never more than the ceiling: the addition is a share of twice the
295
+ // stated wait, or of what is left under the ceiling when that is less.
296
+ const r = this.random();
297
+ const room = Math.min(retryAfterMs * RETRY_SPREAD, this.maxRetryWaitMs - retryAfterMs);
298
+ const waitMs = retryAfterMs + (r > 0 && r <= 1 ? Math.floor(room * r) : 0);
299
+ try {
300
+ this.onRetry?.({
301
+ method,
302
+ path,
303
+ status,
304
+ code: error.code,
305
+ attempt,
306
+ maxRetries: this.maxRetries,
307
+ retryAfterMs,
308
+ waitMs,
309
+ });
107
310
  }
108
- throw new CommitLayerError(status, "error", JSON.stringify(json).slice(0, 300));
311
+ catch {
312
+ // A logging callback must not decide the outcome of the request.
313
+ }
314
+ await this.sleep(waitMs);
315
+ sending = next;
109
316
  }
110
- return json;
111
317
  }
112
318
  // ---------------- actions and facts ----------------
113
319
  /**
@@ -115,6 +321,7 @@ export class Client {
115
321
  * provisional until its settlement window closes and every source it reads has caught up.
116
322
  */
117
323
  async recordAction(contractId, subjectId, opts = {}) {
324
+ // Built once, before the first attempt: a retry sends this body again, generated action_id and request time included.
118
325
  const body = {
119
326
  action_id: opts.actionId || newActionId(),
120
327
  contract_id: contractId,
@@ -148,7 +355,10 @@ export class Client {
148
355
  body.watermarks = opts.watermarks;
149
356
  return this.call("POST", "/v1/facts", body);
150
357
  }
151
- /** `POST /v1/actions/verify`: verify now, by id or inline. `dryRun` stores nothing. */
358
+ /**
359
+ * `POST /v1/actions/verify`: verify now, by id or inline. `dryRun` stores nothing. An inline `action` that is
360
+ * stored and names no `action_id` is sent once only, never retried.
361
+ */
152
362
  async verify(opts = {}) {
153
363
  const body = { dry_run: opts.dryRun ?? false };
154
364
  if (opts.actionId)
@@ -161,7 +371,11 @@ export class Client {
161
371
  body.links = opts.links;
162
372
  return this.call("POST", "/v1/actions/verify", body);
163
373
  }
164
- /** Any endpoint, with the client's auth and error handling: `request("GET", "/v1/actions/x/wait?timeout=30")`. */
374
+ /**
375
+ * Any endpoint, with the client's auth, error handling and retries: `request("GET", "/v1/actions/x/wait?timeout=30")`.
376
+ * A `POST /v1/actions` body without an `action_id` is sent once only: the API would record a new action on
377
+ * every attempt.
378
+ */
165
379
  async request(method, path, body) {
166
380
  return this.call(method, path, body);
167
381
  }
@@ -173,7 +387,9 @@ export class Client {
173
387
  * The completion gate: resolves when the action's verdict settles or `timeoutMs` passes, with the
174
388
  * verification (`status` is `settled` or, on timeout, `pending`; `timed_out` says which). The API holds each
175
389
  * call for up to 60 seconds; this loops. A workflow should not tell the customer "done" before this returns a
176
- * settled PASS; FAIL routes to recovery; a timeout is the workflow's decision.
390
+ * settled PASS; FAIL routes to recovery; a timeout is the workflow's decision. A poll the API refuses with
391
+ * `Retry-After` is retried like any other request, which can add up to `maxRetries` times `maxRetryWaitMs` to
392
+ * `timeoutMs`.
177
393
  */
178
394
  async waitForSettlement(ref, opts = {}) {
179
395
  const deadline = Date.now() + Math.max(0, opts.timeoutMs ?? 300_000);
@@ -206,6 +422,15 @@ export class Client {
206
422
  async saveContract(yaml) {
207
423
  return this.call("POST", "/v1/contracts", { yaml });
208
424
  }
425
+ // ---------------- workflow packs ----------------
426
+ /**
427
+ * The workflow packs (`/v1/packs`): `client.packs.list()`, `get`, `configure`, `dryRun`, `install`, `coverage`,
428
+ * `recorderMapping`. Install creates drafts and never activates; activation stays a person's
429
+ * `POST /v1/contracts/{id}/select`.
430
+ */
431
+ get packs() {
432
+ return new Packs(this);
433
+ }
209
434
  // ---------------- wrapper ----------------
210
435
  /**
211
436
  * Record each call of the wrapped function as an action under `contractId` before it runs.
@@ -252,3 +477,50 @@ export class Client {
252
477
  };
253
478
  }
254
479
  }
480
+ /**
481
+ * `/v1/packs`: the workflow pack library. Reads take any member; `configure` and `dryRun` write nothing and take an
482
+ * analyst; `install` saves the configured contracts as **drafts** (never activates) and needs `confirm: true`.
483
+ */
484
+ export class Packs {
485
+ client;
486
+ constructor(client) {
487
+ this.client = client;
488
+ }
489
+ /** `GET /v1/packs`: `{items: PackSummary[]}`. */
490
+ list() {
491
+ return this.client.request("GET", "/v1/packs");
492
+ }
493
+ /** `GET /v1/packs/{id}`: the summary plus contracts, recorder mapping, fixtures, templates, readme, versions and requirements. */
494
+ get(packId) {
495
+ return this.client.request("GET", `/v1/packs/${encodeURIComponent(packId)}`);
496
+ }
497
+ /** `POST /v1/packs/{id}/configure`: the configured contracts, the values in force and every weakening. Nothing is written. */
498
+ configure(packId, configuration = {}) {
499
+ return this.client.request("POST", `/v1/packs/${encodeURIComponent(packId)}/configure`, { configuration });
500
+ }
501
+ /** `POST /v1/packs/{id}/dry-run`: every fixture case through the engine, in a savepoint; nothing persists. */
502
+ dryRun(packId, configuration = {}, opts = {}) {
503
+ const body = { configuration };
504
+ if (opts.workflow)
505
+ body.workflow = opts.workflow;
506
+ return this.client.request("POST", `/v1/packs/${encodeURIComponent(packId)}/dry-run`, body);
507
+ }
508
+ /**
509
+ * `POST /v1/packs/{id}/install`: save the configured contracts as drafts and record the installation. Refused
510
+ * without `confirm: true`; 402 `plan_required` below the pack's minimum plan.
511
+ */
512
+ install(packId, configuration = {}, opts = {}) {
513
+ return this.client.request("POST", `/v1/packs/${encodeURIComponent(packId)}/install`, {
514
+ configuration,
515
+ confirm: opts.confirm ?? false,
516
+ });
517
+ }
518
+ /** `GET /v1/packs/{id}/coverage`. */
519
+ coverage(packId) {
520
+ return this.client.request("GET", `/v1/packs/${encodeURIComponent(packId)}/coverage`);
521
+ }
522
+ /** `GET /v1/packs/{id}/recorder-mapping`: the installed mapping, contract versions pinned. */
523
+ recorderMapping(packId) {
524
+ return this.client.request("GET", `/v1/packs/${encodeURIComponent(packId)}/recorder-mapping`);
525
+ }
526
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "commitlayer",
3
- "version": "0.1.1",
3
+ "version": "0.1.4",
4
4
  "description": "CommitLayer JavaScript SDK: record agent actions, push facts, read verdicts, draft contracts",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,11 +18,11 @@
18
18
  "LICENSE"
19
19
  ],
20
20
  "engines": {
21
- "node": ">=18"
21
+ "node": ">=20"
22
22
  },
23
23
  "scripts": {
24
24
  "build": "tsc -p tsconfig.json",
25
- "test": "tsc -p tsconfig.test.json && node --test \"dist-test/test/**/*.test.js\""
25
+ "test": "tsc -p tsconfig.test.json && node --test dist-test/test/*.test.js"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^22.20.5",
@@ -31,7 +31,7 @@
31
31
  "homepage": "https://commitlayer.ai/docs",
32
32
  "repository": {
33
33
  "type": "git",
34
- "url": "git+https://github.com/kobikwelu/stateprf-svcs.git",
34
+ "url": "git+https://github.com/commitlayer/commitlayer.git",
35
35
  "directory": "sdk/js"
36
36
  },
37
37
  "bugs": {