commitlayer 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +162 -2
- package/dist/index.d.ts +148 -0
- package/dist/index.js +254 -0
- package/package.json +48 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Asterfold Labs, Inc.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,163 @@
|
|
|
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.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install ./sdk/js # from this repository (run `npm run build` in sdk/js first)
|
|
8
|
+
export COMMITLAYER_API_KEY=spk_... # the agent runtime's key: a *recorder* key (records actions, nothing else)
|
|
9
|
+
export COMMITLAYER_EVIDENCE_KEY=spk_... # the pipeline's key: an *evidence* key bound to the sources it pushes for
|
|
10
|
+
# COMMITLAYER_API_URL defaults to https://api.commitlayer.ai. One credential per side of the line: the key that
|
|
11
|
+
# records an action can never also supply the facts that verify it.
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Record an action where it happens
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
import { Client } from "commitlayer";
|
|
18
|
+
|
|
19
|
+
const cl = new Client({ agentId: "support-bot" });
|
|
20
|
+
|
|
21
|
+
const refund = cl.action("refund_workflow", {
|
|
22
|
+
subject: (orderId) => orderId,
|
|
23
|
+
params: (orderId, amount) => ({ amount }),
|
|
24
|
+
subjectKind: "order",
|
|
25
|
+
actionId: (orderId) => `refund:${orderId}`, // retries update one claim instead of recording two
|
|
26
|
+
})(async (orderId, amount) => {
|
|
27
|
+
return payments.refund(orderId, amount); // the agent's own work, unchanged
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
await refund("order_10231", 180.0);
|
|
31
|
+
console.log(refund.lastRecorded.verification.summary.headline);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The action is recorded **before** the function runs, so its request time precedes every effect. The function's
|
|
35
|
+
return value is never changed and never consulted: verification reads the systems of record. If the API cannot
|
|
36
|
+
be reached the function still runs and a warning is logged with `console.warn` (`failOpen: true`); pass
|
|
37
|
+
`failOpen: false` to throw instead.
|
|
38
|
+
|
|
39
|
+
The wrapper always returns a Promise, also for a synchronous function, because the record is awaited first.
|
|
40
|
+
`subject` is a function over the call's arguments or the 0-based index of the argument holding the subject id.
|
|
41
|
+
`workflowId` and `compensates` take a string or a function over the arguments; `compensates` names the earlier
|
|
42
|
+
action this one corrects.
|
|
43
|
+
|
|
44
|
+
Without the wrapper:
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
const rec = await cl.recordAction("refund_workflow", "order_10231", {
|
|
48
|
+
params: { amount: 180.0 },
|
|
49
|
+
actionType: "refund_order",
|
|
50
|
+
subjectKind: "order",
|
|
51
|
+
actionId: "refund:order_10231",
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Push facts, with a watermark
|
|
56
|
+
|
|
57
|
+
Use an **evidence** key here, bound to the sources it pushes for (Settings → API keys). The key your agent runtime records actions with is a **recorder** key and cannot push facts: the credential that records an action never also supplies the facts that verify it.
|
|
58
|
+
|
|
59
|
+
```js
|
|
60
|
+
const evidence = new Client({ apiKey: process.env.COMMITLAYER_EVIDENCE_KEY }); // the pipeline's own client
|
|
61
|
+
|
|
62
|
+
await evidence.pushFacts(
|
|
63
|
+
[
|
|
64
|
+
{
|
|
65
|
+
source: "crm",
|
|
66
|
+
subject_id: "order_10231",
|
|
67
|
+
fact_type: "note_added",
|
|
68
|
+
occurred_at: "2026-10-13T10:42:09Z",
|
|
69
|
+
},
|
|
70
|
+
],
|
|
71
|
+
{ watermarks: { crm: "2026-10-13T10:45:00Z" } }, // everything up to here has been sent for crm
|
|
72
|
+
);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
A verdict that is not yet a PASS settles only when its window has closed **and** every source it reads has a
|
|
76
|
+
watermark past the end of the window. Declare one when your feed lags; a source that never declares one is taken
|
|
77
|
+
as current.
|
|
78
|
+
|
|
79
|
+
## Draft a contract from what was recorded
|
|
80
|
+
|
|
81
|
+
```js
|
|
82
|
+
const d = await cl.draftContract("refund_order", { lookbackDays: 30 });
|
|
83
|
+
console.log(d.yaml); // expected effects, window, preconditions, limits, from the sample
|
|
84
|
+
console.log(d.stats.effects);
|
|
85
|
+
const v = await cl.validateContract(d.yaml); // errors, and weakening warnings against the version it would replace
|
|
86
|
+
await cl.saveContract(d.yaml); // the response carries the same warnings
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Every value in a draft is what the sample showed, not what the policy says. Review it before saving.
|
|
90
|
+
|
|
91
|
+
## Read a verdict
|
|
92
|
+
|
|
93
|
+
```js
|
|
94
|
+
const v = await cl.getAction("refund:order_10231");
|
|
95
|
+
v.status; // pending | settled
|
|
96
|
+
v.settlement.waiting_on; // sources still behind the window, if any
|
|
97
|
+
v.reversal; // the later record that undid the action, if any
|
|
98
|
+
v.sources; // trust level and watermark per source the contract read
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Wait for the verdict before saying "done"
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
const v = await cl.waitForSettlement("refund:order_10231", { timeoutMs: 300_000 });
|
|
105
|
+
if (v.timed_out) {
|
|
106
|
+
// still pending: your policy, never "success"
|
|
107
|
+
} else if (v.lenses.outcome.verdict === "PASS") {
|
|
108
|
+
await notifyCustomer("Your order is cancelled and refunded.");
|
|
109
|
+
} else {
|
|
110
|
+
await openRecovery(v); // FAIL: the reasons name what is missing or forbidden
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The API holds each call for up to 60 seconds; the SDK loops. The gate reads evidence; it never changes a verdict.
|
|
115
|
+
|
|
116
|
+
## Errors
|
|
117
|
+
|
|
118
|
+
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.
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
import { CommitLayerError } from "commitlayer";
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
await cl.getAction("missing");
|
|
126
|
+
} catch (e) {
|
|
127
|
+
if (e instanceof CommitLayerError && e.code === "not_found") {
|
|
128
|
+
/* ... */
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## TypeScript
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
import { Client, type Json } from "commitlayer";
|
|
137
|
+
|
|
138
|
+
const cl = new Client({ apiKey: "spk_..." });
|
|
139
|
+
|
|
140
|
+
async function refundOrder(orderId: string, amount: number): Promise<{ refundId: string }> {
|
|
141
|
+
return payments.refund(orderId, amount);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The wrapped function keeps refundOrder's parameters; its result is Promise<{ refundId: string }>.
|
|
145
|
+
const refund = cl.action<typeof refundOrder>("refund_workflow", {
|
|
146
|
+
subject: (orderId) => orderId,
|
|
147
|
+
params: (_orderId, amount) => ({ amount }),
|
|
148
|
+
onRecorded: (rec: Json) => console.log(rec.verification),
|
|
149
|
+
})(refundOrder);
|
|
150
|
+
|
|
151
|
+
const { refundId } = await refund("order_10231", 180);
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
For tests, inject a transport instead of a network: `new Client({ transport: async (method, path, body) => ({ status: 201, json: {} }) })`.
|
|
155
|
+
|
|
156
|
+
## Develop
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
cd sdk/js
|
|
160
|
+
npm install # typescript and @types/node only
|
|
161
|
+
npm run build # compiles src/ to dist/
|
|
162
|
+
npm test # compiles the node:test suite and runs it offline
|
|
163
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CommitLayer JavaScript SDK: record agent actions, push facts, read verdicts, draft contracts.
|
|
3
|
+
*
|
|
4
|
+
* Zero dependencies; uses the global `fetch` (Node 18+ or a browser). One client per workspace API key:
|
|
5
|
+
*
|
|
6
|
+
* import { Client } from "commitlayer";
|
|
7
|
+
*
|
|
8
|
+
* const cl = new Client({ apiKey: "spk_..." }); // COMMITLAYER_API_KEY / COMMITLAYER_API_URL are read when omitted
|
|
9
|
+
*
|
|
10
|
+
* const refund = cl.action("refund_workflow", {
|
|
11
|
+
* subject: (orderId) => orderId,
|
|
12
|
+
* params: (_orderId, amount) => ({ amount }),
|
|
13
|
+
* })(async (orderId, amount) => { ... }); // the agent's own work, unchanged
|
|
14
|
+
*
|
|
15
|
+
* The wrapper records the action BEFORE the function runs, so the request time precedes every effect, and never
|
|
16
|
+
* changes what the function returns. Recording failures are logged and swallowed by default (`failOpen: true`):
|
|
17
|
+
* a verifier that is unreachable must not stop the business action, and the gap shows up as an action that was
|
|
18
|
+
* never recorded rather than one that never happened. Set `failOpen: false` to throw.
|
|
19
|
+
*
|
|
20
|
+
* Verification itself is done by the API from the systems of record; nothing here consults the function's result.
|
|
21
|
+
*/
|
|
22
|
+
export declare const VERSION = "0.1.0";
|
|
23
|
+
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<{
|
|
26
|
+
status: number;
|
|
27
|
+
json: unknown;
|
|
28
|
+
}>;
|
|
29
|
+
export interface ClientOptions {
|
|
30
|
+
apiKey?: string;
|
|
31
|
+
apiUrl?: string;
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
transport?: Transport;
|
|
34
|
+
agentId?: string;
|
|
35
|
+
}
|
|
36
|
+
export interface RecordActionOptions {
|
|
37
|
+
params?: Json;
|
|
38
|
+
actionId?: string;
|
|
39
|
+
actionType?: string;
|
|
40
|
+
subjectKind?: string;
|
|
41
|
+
workflowId?: string;
|
|
42
|
+
agentId?: string;
|
|
43
|
+
requestedAt?: string;
|
|
44
|
+
channel?: string;
|
|
45
|
+
/** The action id of an earlier action this one corrects. Sent only when given. */
|
|
46
|
+
compensates?: string;
|
|
47
|
+
/** Pin the contract version the action is verified under; the active version when omitted. */
|
|
48
|
+
contractVersion?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface PushFactsOptions {
|
|
51
|
+
links?: Json[];
|
|
52
|
+
/** Source to time: everything up to that time has been sent for the source; settlement waits on it. */
|
|
53
|
+
watermarks?: Record<string, string>;
|
|
54
|
+
}
|
|
55
|
+
export interface VerifyOptions {
|
|
56
|
+
actionId?: string;
|
|
57
|
+
action?: Json;
|
|
58
|
+
facts?: Json[];
|
|
59
|
+
links?: Json[];
|
|
60
|
+
dryRun?: boolean;
|
|
61
|
+
}
|
|
62
|
+
export interface DraftContractOptions {
|
|
63
|
+
contractId?: string;
|
|
64
|
+
lookbackDays?: number;
|
|
65
|
+
lookahead?: string;
|
|
66
|
+
minShare?: number;
|
|
67
|
+
}
|
|
68
|
+
type AnyFn = (...args: any[]) => any;
|
|
69
|
+
export interface ActionOptions<F extends AnyFn> {
|
|
70
|
+
/** A function over the wrapped function's arguments returning the subject id, or a 0-based argument index. */
|
|
71
|
+
subject: ((...args: Parameters<F>) => unknown) | number;
|
|
72
|
+
/** The parameters the contract limits (an amount, a tier), computed from the arguments. */
|
|
73
|
+
params?: (...args: Parameters<F>) => Json;
|
|
74
|
+
actionType?: string;
|
|
75
|
+
subjectKind?: string;
|
|
76
|
+
workflowId?: string | ((...args: Parameters<F>) => string | undefined);
|
|
77
|
+
agentId?: string;
|
|
78
|
+
/** Makes retries idempotent: the same id updates the one claim instead of recording two. */
|
|
79
|
+
actionId?: (...args: Parameters<F>) => string;
|
|
80
|
+
compensates?: string | ((...args: Parameters<F>) => string | undefined);
|
|
81
|
+
failOpen?: boolean;
|
|
82
|
+
onRecorded?: (recorded: Json) => void;
|
|
83
|
+
}
|
|
84
|
+
/** The wrapped function: same arguments, always async, with the last API response attached. */
|
|
85
|
+
export type Wrapped<F extends AnyFn> = ((...args: Parameters<F>) => Promise<Awaited<ReturnType<F>>>) & {
|
|
86
|
+
lastRecorded: Json | null;
|
|
87
|
+
};
|
|
88
|
+
export declare class CommitLayerError extends Error {
|
|
89
|
+
readonly status: number;
|
|
90
|
+
readonly code: string;
|
|
91
|
+
readonly details: unknown;
|
|
92
|
+
constructor(status: number, code: string, message: string, details?: unknown);
|
|
93
|
+
toString(): string;
|
|
94
|
+
}
|
|
95
|
+
export declare class Client {
|
|
96
|
+
readonly apiKey: string;
|
|
97
|
+
readonly apiUrl: string;
|
|
98
|
+
readonly timeoutMs: number;
|
|
99
|
+
readonly agentId: string | undefined;
|
|
100
|
+
private readonly transport;
|
|
101
|
+
constructor(options?: ClientOptions);
|
|
102
|
+
private http;
|
|
103
|
+
private call;
|
|
104
|
+
/**
|
|
105
|
+
* `POST /v1/actions`: record one action. Returns `{action, verification, allowance}`. The verification is
|
|
106
|
+
* provisional until its settlement window closes and every source it reads has caught up.
|
|
107
|
+
*/
|
|
108
|
+
recordAction(contractId: string, subjectId: string, opts?: RecordActionOptions): Promise<Json>;
|
|
109
|
+
/**
|
|
110
|
+
* `POST /v1/facts`. `watermarks` (source to time) states that everything up to that time has been sent for the
|
|
111
|
+
* source; settlement waits on it instead of the clock.
|
|
112
|
+
*/
|
|
113
|
+
pushFacts(facts: Json[], opts?: PushFactsOptions): Promise<Json>;
|
|
114
|
+
/** `POST /v1/actions/verify`: verify now, by id or inline. `dryRun` stores nothing. */
|
|
115
|
+
verify(opts?: VerifyOptions): Promise<Json>;
|
|
116
|
+
/** Any endpoint, with the client's auth and error handling: `request("GET", "/v1/actions/x/wait?timeout=30")`. */
|
|
117
|
+
request(method: string, path: string, body?: Json | null): Promise<Json>;
|
|
118
|
+
/** `GET /v1/actions/{ref}`: `ref` is the `action_id` or the internal id. */
|
|
119
|
+
getAction(ref: string): Promise<Json>;
|
|
120
|
+
/**
|
|
121
|
+
* The completion gate: resolves when the action's verdict settles or `timeoutMs` passes, with the
|
|
122
|
+
* verification (`status` is `settled` or, on timeout, `pending`; `timed_out` says which). The API holds each
|
|
123
|
+
* 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.
|
|
125
|
+
*/
|
|
126
|
+
waitForSettlement(ref: string, opts?: {
|
|
127
|
+
timeoutMs?: number;
|
|
128
|
+
}): Promise<Json>;
|
|
129
|
+
/**
|
|
130
|
+
* `POST /v1/contracts/draft`: a contract drafted from recorded actions and the facts around them.
|
|
131
|
+
* Returns `{yaml, contract, errors, warnings, stats}`; nothing is saved.
|
|
132
|
+
*/
|
|
133
|
+
draftContract(actionType?: string, opts?: DraftContractOptions): Promise<Json>;
|
|
134
|
+
/** `POST /v1/contracts/validate`: errors, compiled lenses and weakening warnings against the version it would replace. */
|
|
135
|
+
validateContract(yaml: string): Promise<Json>;
|
|
136
|
+
/** `POST /v1/contracts`: save a version. The response carries `warnings` when it is weaker than the last one. */
|
|
137
|
+
saveContract(yaml: string): Promise<Json>;
|
|
138
|
+
/**
|
|
139
|
+
* Record each call of the wrapped function as an action under `contractId` before it runs.
|
|
140
|
+
*
|
|
141
|
+
* `subject` is a function over the call's arguments returning the subject id, or the 0-based index of the
|
|
142
|
+
* argument holding it. `params` is a function over the arguments returning the parameters the contract limits.
|
|
143
|
+
* `actionId` makes retries idempotent: give it the same id and the API updates the one claim rather than
|
|
144
|
+
* recording two. The API response is passed to `onRecorded` and stored on the function as `lastRecorded`.
|
|
145
|
+
*/
|
|
146
|
+
action<F extends AnyFn>(contractId: string, opts: ActionOptions<F>): (fn: F) => Wrapped<F>;
|
|
147
|
+
}
|
|
148
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CommitLayer JavaScript SDK: record agent actions, push facts, read verdicts, draft contracts.
|
|
3
|
+
*
|
|
4
|
+
* Zero dependencies; uses the global `fetch` (Node 18+ or a browser). One client per workspace API key:
|
|
5
|
+
*
|
|
6
|
+
* import { Client } from "commitlayer";
|
|
7
|
+
*
|
|
8
|
+
* const cl = new Client({ apiKey: "spk_..." }); // COMMITLAYER_API_KEY / COMMITLAYER_API_URL are read when omitted
|
|
9
|
+
*
|
|
10
|
+
* const refund = cl.action("refund_workflow", {
|
|
11
|
+
* subject: (orderId) => orderId,
|
|
12
|
+
* params: (_orderId, amount) => ({ amount }),
|
|
13
|
+
* })(async (orderId, amount) => { ... }); // the agent's own work, unchanged
|
|
14
|
+
*
|
|
15
|
+
* The wrapper records the action BEFORE the function runs, so the request time precedes every effect, and never
|
|
16
|
+
* changes what the function returns. Recording failures are logged and swallowed by default (`failOpen: true`):
|
|
17
|
+
* a verifier that is unreachable must not stop the business action, and the gap shows up as an action that was
|
|
18
|
+
* never recorded rather than one that never happened. Set `failOpen: false` to throw.
|
|
19
|
+
*
|
|
20
|
+
* Verification itself is done by the API from the systems of record; nothing here consults the function's result.
|
|
21
|
+
*/
|
|
22
|
+
export const VERSION = "0.1.0";
|
|
23
|
+
export class CommitLayerError extends Error {
|
|
24
|
+
status;
|
|
25
|
+
code;
|
|
26
|
+
details;
|
|
27
|
+
constructor(status, code, message, details) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = "CommitLayerError";
|
|
30
|
+
this.status = status;
|
|
31
|
+
this.code = code;
|
|
32
|
+
this.details = details;
|
|
33
|
+
}
|
|
34
|
+
toString() {
|
|
35
|
+
return `${this.code} (${this.status}): ${this.message}`;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function env(name) {
|
|
39
|
+
// `process` is absent in browsers; the option or the default applies there.
|
|
40
|
+
const p = globalThis.process;
|
|
41
|
+
return p?.env?.[name];
|
|
42
|
+
}
|
|
43
|
+
function now() {
|
|
44
|
+
// The API takes whole seconds, as the Python SDK sends them.
|
|
45
|
+
return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
46
|
+
}
|
|
47
|
+
function newActionId() {
|
|
48
|
+
return "act_" + crypto.randomUUID().replace(/-/g, "");
|
|
49
|
+
}
|
|
50
|
+
export class Client {
|
|
51
|
+
apiKey;
|
|
52
|
+
apiUrl;
|
|
53
|
+
timeoutMs;
|
|
54
|
+
agentId;
|
|
55
|
+
transport;
|
|
56
|
+
constructor(options = {}) {
|
|
57
|
+
this.apiKey = options.apiKey || env("COMMITLAYER_API_KEY") || "";
|
|
58
|
+
this.apiUrl = (options.apiUrl || env("COMMITLAYER_API_URL") || "https://api.commitlayer.ai").replace(/\/+$/, "");
|
|
59
|
+
this.timeoutMs = options.timeoutMs ?? 20_000;
|
|
60
|
+
this.agentId = options.agentId;
|
|
61
|
+
this.transport = options.transport ?? ((m, p, b) => this.http(m, p, b));
|
|
62
|
+
if (!this.apiKey && !options.transport) {
|
|
63
|
+
throw new Error("apiKey is required (or set COMMITLAYER_API_KEY)");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// ---------------- transport ----------------
|
|
67
|
+
async http(method, path, body) {
|
|
68
|
+
const controller = new AbortController();
|
|
69
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
70
|
+
try {
|
|
71
|
+
const res = await fetch(this.apiUrl + path, {
|
|
72
|
+
method,
|
|
73
|
+
headers: {
|
|
74
|
+
"X-API-Key": this.apiKey,
|
|
75
|
+
"Content-Type": "application/json",
|
|
76
|
+
Accept: "application/json",
|
|
77
|
+
// Browsers refuse to set User-Agent and drop it silently; Node sends it.
|
|
78
|
+
"User-Agent": `commitlayer-js/${VERSION}`,
|
|
79
|
+
},
|
|
80
|
+
body: body == null ? undefined : JSON.stringify(body),
|
|
81
|
+
signal: controller.signal,
|
|
82
|
+
});
|
|
83
|
+
const raw = await res.text();
|
|
84
|
+
if (!raw)
|
|
85
|
+
return { status: res.status, json: {} };
|
|
86
|
+
try {
|
|
87
|
+
return { status: res.status, json: JSON.parse(raw) };
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
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);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
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);
|
|
107
|
+
}
|
|
108
|
+
throw new CommitLayerError(status, "error", JSON.stringify(json).slice(0, 300));
|
|
109
|
+
}
|
|
110
|
+
return json;
|
|
111
|
+
}
|
|
112
|
+
// ---------------- actions and facts ----------------
|
|
113
|
+
/**
|
|
114
|
+
* `POST /v1/actions`: record one action. Returns `{action, verification, allowance}`. The verification is
|
|
115
|
+
* provisional until its settlement window closes and every source it reads has caught up.
|
|
116
|
+
*/
|
|
117
|
+
async recordAction(contractId, subjectId, opts = {}) {
|
|
118
|
+
const body = {
|
|
119
|
+
action_id: opts.actionId || newActionId(),
|
|
120
|
+
contract_id: contractId,
|
|
121
|
+
subject_id: String(subjectId),
|
|
122
|
+
params: opts.params ?? {},
|
|
123
|
+
requested_at: opts.requestedAt || now(),
|
|
124
|
+
};
|
|
125
|
+
const optional = [
|
|
126
|
+
["action_type", opts.actionType],
|
|
127
|
+
["subject_kind", opts.subjectKind],
|
|
128
|
+
["workflow_id", opts.workflowId],
|
|
129
|
+
["agent_id", opts.agentId ?? this.agentId],
|
|
130
|
+
["channel", opts.channel],
|
|
131
|
+
["compensates", opts.compensates],
|
|
132
|
+
["contract_version", opts.contractVersion],
|
|
133
|
+
];
|
|
134
|
+
for (const [k, v] of optional)
|
|
135
|
+
if (v != null)
|
|
136
|
+
body[k] = v;
|
|
137
|
+
return this.call("POST", "/v1/actions", body);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* `POST /v1/facts`. `watermarks` (source to time) states that everything up to that time has been sent for the
|
|
141
|
+
* source; settlement waits on it instead of the clock.
|
|
142
|
+
*/
|
|
143
|
+
async pushFacts(facts, opts = {}) {
|
|
144
|
+
const body = { facts };
|
|
145
|
+
if (opts.links?.length)
|
|
146
|
+
body.links = opts.links;
|
|
147
|
+
if (opts.watermarks && Object.keys(opts.watermarks).length)
|
|
148
|
+
body.watermarks = opts.watermarks;
|
|
149
|
+
return this.call("POST", "/v1/facts", body);
|
|
150
|
+
}
|
|
151
|
+
/** `POST /v1/actions/verify`: verify now, by id or inline. `dryRun` stores nothing. */
|
|
152
|
+
async verify(opts = {}) {
|
|
153
|
+
const body = { dry_run: opts.dryRun ?? false };
|
|
154
|
+
if (opts.actionId)
|
|
155
|
+
body.action_id = opts.actionId;
|
|
156
|
+
if (opts.action)
|
|
157
|
+
body.action = opts.action;
|
|
158
|
+
if (opts.facts?.length)
|
|
159
|
+
body.facts = opts.facts;
|
|
160
|
+
if (opts.links?.length)
|
|
161
|
+
body.links = opts.links;
|
|
162
|
+
return this.call("POST", "/v1/actions/verify", body);
|
|
163
|
+
}
|
|
164
|
+
/** Any endpoint, with the client's auth and error handling: `request("GET", "/v1/actions/x/wait?timeout=30")`. */
|
|
165
|
+
async request(method, path, body) {
|
|
166
|
+
return this.call(method, path, body);
|
|
167
|
+
}
|
|
168
|
+
/** `GET /v1/actions/{ref}`: `ref` is the `action_id` or the internal id. */
|
|
169
|
+
async getAction(ref) {
|
|
170
|
+
return this.call("GET", `/v1/actions/${ref}`);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The completion gate: resolves when the action's verdict settles or `timeoutMs` passes, with the
|
|
174
|
+
* verification (`status` is `settled` or, on timeout, `pending`; `timed_out` says which). The API holds each
|
|
175
|
+
* 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.
|
|
177
|
+
*/
|
|
178
|
+
async waitForSettlement(ref, opts = {}) {
|
|
179
|
+
const deadline = Date.now() + Math.max(0, opts.timeoutMs ?? 300_000);
|
|
180
|
+
for (;;) {
|
|
181
|
+
const budget = Math.max(0, Math.min(60_000, deadline - Date.now()));
|
|
182
|
+
const v = await this.call("GET", `/v1/actions/${ref}/wait?timeout=${Math.round(budget / 1000)}`);
|
|
183
|
+
if (!v.timed_out || budget < 1000 || Date.now() >= deadline)
|
|
184
|
+
return v;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// ---------------- contracts ----------------
|
|
188
|
+
/**
|
|
189
|
+
* `POST /v1/contracts/draft`: a contract drafted from recorded actions and the facts around them.
|
|
190
|
+
* Returns `{yaml, contract, errors, warnings, stats}`; nothing is saved.
|
|
191
|
+
*/
|
|
192
|
+
async draftContract(actionType, opts = {}) {
|
|
193
|
+
return this.call("POST", "/v1/contracts/draft", {
|
|
194
|
+
action_type: actionType ?? null,
|
|
195
|
+
contract_id: opts.contractId ?? null,
|
|
196
|
+
lookback_days: opts.lookbackDays ?? 30,
|
|
197
|
+
lookahead: opts.lookahead ?? "24h",
|
|
198
|
+
min_share: opts.minShare ?? 0.8,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
/** `POST /v1/contracts/validate`: errors, compiled lenses and weakening warnings against the version it would replace. */
|
|
202
|
+
async validateContract(yaml) {
|
|
203
|
+
return this.call("POST", "/v1/contracts/validate", { yaml });
|
|
204
|
+
}
|
|
205
|
+
/** `POST /v1/contracts`: save a version. The response carries `warnings` when it is weaker than the last one. */
|
|
206
|
+
async saveContract(yaml) {
|
|
207
|
+
return this.call("POST", "/v1/contracts", { yaml });
|
|
208
|
+
}
|
|
209
|
+
// ---------------- wrapper ----------------
|
|
210
|
+
/**
|
|
211
|
+
* Record each call of the wrapped function as an action under `contractId` before it runs.
|
|
212
|
+
*
|
|
213
|
+
* `subject` is a function over the call's arguments returning the subject id, or the 0-based index of the
|
|
214
|
+
* argument holding it. `params` is a function over the arguments returning the parameters the contract limits.
|
|
215
|
+
* `actionId` makes retries idempotent: give it the same id and the API updates the one claim rather than
|
|
216
|
+
* recording two. The API response is passed to `onRecorded` and stored on the function as `lastRecorded`.
|
|
217
|
+
*/
|
|
218
|
+
action(contractId, opts) {
|
|
219
|
+
const { subject, params, actionType, subjectKind, workflowId, agentId, actionId, compensates, onRecorded } = opts;
|
|
220
|
+
const failOpen = opts.failOpen ?? true;
|
|
221
|
+
const pick = (v, args) => typeof v === "function" ? v(...args) : v;
|
|
222
|
+
return (fn) => {
|
|
223
|
+
const client = this;
|
|
224
|
+
const wrapped = async function (...args) {
|
|
225
|
+
try {
|
|
226
|
+
const subj = typeof subject === "number" ? args[subject] : subject(...args);
|
|
227
|
+
if (subj == null)
|
|
228
|
+
throw new Error("subject id is missing from the call's arguments");
|
|
229
|
+
const rec = await client.recordAction(contractId, String(subj), {
|
|
230
|
+
params: params ? params(...args) : {},
|
|
231
|
+
actionId: actionId ? actionId(...args) : undefined,
|
|
232
|
+
actionType,
|
|
233
|
+
subjectKind,
|
|
234
|
+
workflowId: pick(workflowId, args),
|
|
235
|
+
agentId,
|
|
236
|
+
compensates: pick(compensates, args),
|
|
237
|
+
});
|
|
238
|
+
wrapped.lastRecorded = rec;
|
|
239
|
+
onRecorded?.(rec);
|
|
240
|
+
}
|
|
241
|
+
catch (e) {
|
|
242
|
+
// The business action must not depend on the verifier.
|
|
243
|
+
wrapped.lastRecorded = null;
|
|
244
|
+
if (!failOpen)
|
|
245
|
+
throw e;
|
|
246
|
+
console.warn(`commitlayer: action not recorded for ${fn.name || "<anonymous>"}: ${String(e)}`);
|
|
247
|
+
}
|
|
248
|
+
return fn.apply(this, args);
|
|
249
|
+
};
|
|
250
|
+
wrapped.lastRecorded = null;
|
|
251
|
+
return wrapped;
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "commitlayer",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "CommitLayer JavaScript SDK: record agent actions, push facts, read verdicts, draft contracts",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "tsc -p tsconfig.json",
|
|
25
|
+
"test": "tsc -p tsconfig.test.json && node --test \"dist-test/test/**/*.test.js\""
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"@types/node": "^22.20.5",
|
|
29
|
+
"typescript": "^5.9.3"
|
|
30
|
+
},
|
|
31
|
+
"homepage": "https://commitlayer.ai/docs",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/kobikwelu/stateprf-svcs.git",
|
|
35
|
+
"directory": "sdk/js"
|
|
36
|
+
},
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://commitlayer.ai/contact"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"ai-agents",
|
|
45
|
+
"verification",
|
|
46
|
+
"audit",
|
|
47
|
+
"mcp",
|
|
48
|
+
"observability"
|
|
49
|
+
]
|
|
50
|
+
}
|