@cygnuxlabs/tracekit 1.6.0 → 1.7.3
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 +8 -3
- package/dist/v2/adapters/gate.js +8 -5
- package/dist/v2/client.d.ts +11 -4
- package/dist/v2/client.js +178 -45
- package/dist/v2/executor.d.ts +11 -2
- package/dist/v2/executor.js +40 -0
- package/dist/v2/rpc_schema.d.ts +1 -1
- package/dist/v2/rpc_schema.js +5 -2
- package/dist/verify/index.d.ts +2 -2
- package/dist/verify/index.js +9 -3
- package/dist/verify.html +10 -4
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -53,7 +53,10 @@ await client.close(); // waits for what is i
|
|
|
53
53
|
|
|
54
54
|
- **Signer:** `$TRACEKIT_SIGNER` names a Unix socket, `tcp://127.0.0.1:port` (with `$TRACEKIT_SIGNER_TOKEN`; both sides
|
|
55
55
|
prove they hold it, it never goes on the wire) or `https://host:port` (`$TRACEKIT_SIGNER_TOKEN_FILE`: a bearer token
|
|
56
|
-
re-read per call; `$TRACEKIT_SIGNER_CERT`/`_KEY`: mTLS;
|
|
56
|
+
re-read per call, else `$TRACEKIT_API_KEY`: the token itself; `$TRACEKIT_SIGNER_CERT`/`_KEY`: mTLS;
|
|
57
|
+
`$TRACEKIT_SIGNER_CA`: the signer's CA). An event call (decide, complete, observe, state_write, model_event) the
|
|
58
|
+
signer refuses with a rate limit or an outage is sent again within the call's timeout
|
|
59
|
+
([remote clients](../../docs/remote-ingest.md#calling-the-signer-over-http)). In system mode the
|
|
57
60
|
signer named by the root-owned `/etc/tracekit/client.json` is used and a different `$TRACEKIT_SIGNER` is refused.
|
|
58
61
|
Otherwise the same-user dev signer is found, or started with `tracekit up --json`: `$TRACEKIT_PYTHON -m tracekit` if
|
|
59
62
|
set, else a pip-installed `tracekit` on PATH, else the Python bundled in this platform's
|
|
@@ -61,8 +64,10 @@ await client.close(); // waits for what is i
|
|
|
61
64
|
same command.
|
|
62
65
|
- **Protocol:** `hello` first; a signer that does not speak this client's RPC version is refused with `Incompatible`.
|
|
63
66
|
Requests are validated against the RPC schemas before they are sent, pipelined on one connection and answered in
|
|
64
|
-
order; a call whose connection drops is resent with the same `request_id`.
|
|
65
|
-
`
|
|
67
|
+
order; a call whose connection drops is resent with the same `request_id`. A write call's error has `recorded`:
|
|
68
|
+
`false` when it was not recorded, `null` when it went out with no answer, or the signer answered `unavailable`, and
|
|
69
|
+
may have been, `true` when a retry was refused as already recorded. Each handle's events carry the client's `stream`
|
|
70
|
+
and a `client_seq` per run.
|
|
66
71
|
- **Fail modes:** only when the signer cannot be reached does `decide` return the run's fail mode for the tool class
|
|
67
72
|
(`fields.tool_class_hint`, from `register_run`'s `fail_modes`, default closed) with `unavailable: true`. A refusal
|
|
68
73
|
from the signer rejects with `RPCError`, never an allow.
|
package/dist/v2/adapters/gate.js
CHANGED
|
@@ -32,12 +32,15 @@ export const refusal = (ruleIds, reason) => BLOCKED + (ruleIds.join(", ") || "de
|
|
|
32
32
|
export const failure = (e) => (e instanceof Error ? `${e.name}: ${e.message}` : String(e)).slice(0, 4096);
|
|
33
33
|
/** The run's approvals by tool call id: requested, approved, rejected or expired. */
|
|
34
34
|
export async function approvalStates(run) {
|
|
35
|
-
// lean: the first page of approval_list (the signer's default limit); follow `cursor` if runs hold more
|
|
36
|
-
const { approvals } = await run.client.call("approval_list", { run_id: run.runId });
|
|
37
35
|
const states = new Map();
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
36
|
+
let cursor;
|
|
37
|
+
do { // every page: a call approved after the first page's worth would stay waiting
|
|
38
|
+
const page = await run.client.call("approval_list", { run_id: run.runId, ...(cursor ? { cursor } : {}) });
|
|
39
|
+
for (const a of page.approvals)
|
|
40
|
+
if (!states.has(a.tool_call_id))
|
|
41
|
+
states.set(a.tool_call_id, a.state);
|
|
42
|
+
cursor = page.next_cursor;
|
|
43
|
+
} while (cursor);
|
|
41
44
|
return states;
|
|
42
45
|
}
|
|
43
46
|
export class Gate {
|
package/dist/v2/client.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export declare const SYSTEM_CONFIG = "/etc/tracekit/client.json";
|
|
|
8
8
|
export type Frame = Record<string, any>;
|
|
9
9
|
export declare class SignerUnavailable extends Error {
|
|
10
10
|
name: string;
|
|
11
|
+
recorded: boolean | null;
|
|
11
12
|
}
|
|
12
13
|
/** The signer answered but does not speak this client's protocol version. It is left running. */
|
|
13
14
|
export declare class Incompatible extends Error {
|
|
@@ -21,6 +22,7 @@ export declare class RPCError extends Error {
|
|
|
21
22
|
readonly code: string;
|
|
22
23
|
readonly retryAfterMs?: number | undefined;
|
|
23
24
|
name: string;
|
|
25
|
+
recorded: boolean | null;
|
|
24
26
|
constructor(code: string, message: string, retryAfterMs?: number | undefined);
|
|
25
27
|
}
|
|
26
28
|
/** Newline-delimited JSON frames on one socket; answers are matched to requests in order. */
|
|
@@ -33,7 +35,7 @@ declare class Conn {
|
|
|
33
35
|
send(frame: Frame): Promise<Frame>;
|
|
34
36
|
}
|
|
35
37
|
/** A connection to the signer at `path` (a Unix socket or tcp://host:port) and its hello, after the version check. */
|
|
36
|
-
export declare function connect(path: string, token?: string): Promise<{
|
|
38
|
+
export declare function connect(path: string, token?: string, timeoutMs?: number): Promise<{
|
|
37
39
|
conn: Conn;
|
|
38
40
|
hello: Frame;
|
|
39
41
|
}>;
|
|
@@ -56,7 +58,9 @@ export interface ClientOptions {
|
|
|
56
58
|
timeoutMs?: number;
|
|
57
59
|
}
|
|
58
60
|
/** Methods take the request object of an RPC and return its response, or reject with RPCError (a refusal),
|
|
59
|
-
* SignerUnavailable or Incompatible.
|
|
61
|
+
* SignerUnavailable or Incompatible. The error of a write call (one with a `request_id`) has `recorded`: false, it was
|
|
62
|
+
* not; null, a try of it may have been (its message says so); true, it was and only its answer was lost (an event's
|
|
63
|
+
* retry refused client_seq_reused). */
|
|
60
64
|
export declare class Client {
|
|
61
65
|
readonly signer: string | null;
|
|
62
66
|
readonly stream: string;
|
|
@@ -130,8 +134,11 @@ export declare class RunHandle {
|
|
|
130
134
|
/** `args` is the model's raw arguments string, or an already parsed value. Only when the signer can't be reached
|
|
131
135
|
* does the run's fail mode for `fields.tool_class_hint` decide; a refusal rejects. */
|
|
132
136
|
decide(toolCallId: string, tool: string, args: unknown, fields?: Frame): Promise<Decision>;
|
|
133
|
-
/** Never rejects: a failure to record a call that already ran
|
|
134
|
-
*
|
|
137
|
+
/** Never rejects: a failure to record a call that already ran resolves null and warns that it was not recorded (the
|
|
138
|
+
* run's bundle shows the call as decided and not completed) or that it may not have been (no answer to a try that
|
|
139
|
+
* went out: the bundle has its tool.result or a decided_not_completed gap). A retry the signer refuses as already
|
|
140
|
+
* recorded (client_seq_reused) was recorded: null, no warning. Defaults decision_id and args_digest to those of the
|
|
141
|
+
* last `decide` for this tool call. */
|
|
135
142
|
complete(toolCallId: string, status?: "ok" | "error", fields?: Frame): Promise<Frame | null>;
|
|
136
143
|
approvalRequest(toolCallId: string, fields?: Frame): Promise<Frame>;
|
|
137
144
|
/** Waits up to `timeoutMs` (signer cap 300 s) for a decision, on a connection of its own. */
|
package/dist/v2/client.js
CHANGED
|
@@ -9,15 +9,17 @@
|
|
|
9
9
|
*
|
|
10
10
|
* The signer is the Unix socket in $TRACEKIT_SIGNER, `tcp://host:port` with $TRACEKIT_SIGNER_TOKEN (the loopback dev
|
|
11
11
|
* transport, mutual HMAC proof of the token), or an `https://host:port` URL (each call is one POST /v2/rpc;
|
|
12
|
-
* $TRACEKIT_SIGNER_TOKEN_FILE names a bearer token file re-read per call, $
|
|
13
|
-
* certificate for mTLS, $TRACEKIT_SIGNER_CA the signer's CA). In system mode the
|
|
14
|
-
* /etc/tracekit/client.json names, and a $TRACEKIT_SIGNER naming another is refused.
|
|
15
|
-
* signer of the runtime dir is used, started with `tracekit up --json` (found as src/v2/launcher.ts says) when none answers.
|
|
12
|
+
* $TRACEKIT_SIGNER_TOKEN_FILE names a bearer token file re-read per call, else $TRACEKIT_API_KEY is the token itself;
|
|
13
|
+
* $TRACEKIT_SIGNER_CERT/_KEY a client certificate for mTLS, $TRACEKIT_SIGNER_CA the signer's CA). In system mode the
|
|
14
|
+
* signer is the one the root-owned /etc/tracekit/client.json names, and a $TRACEKIT_SIGNER naming another is refused.
|
|
15
|
+
* Without either, the same-user dev signer of the runtime dir is used, started with `tracekit up --json` (found as src/v2/launcher.ts says) when none answers.
|
|
16
16
|
* Requests go out in order on one connection and are answered in order; `approval_wait` gets a connection of its own.
|
|
17
17
|
* Every request is validated against the RPC contract before it is sent. Calls that change state carry a `request_id`
|
|
18
18
|
* and are resent with it when the connection drops. Event calls carry this client's `stream` and a `client_seq` per run;
|
|
19
|
-
* a run's events go out one at a time, each once the one before it is answered, so they reach the signer in order.
|
|
20
|
-
*
|
|
19
|
+
* a run's events go out one at a time, each once the one before it is answered, so they reach the signer in order. An
|
|
20
|
+
* event call the signer refuses with `quota_exceeded` (a rate or count limit: one with `retry_after_ms`) or
|
|
21
|
+
* `unavailable` is sent again as it was, within the call's timeout (retryWait); no other call is. The client writes
|
|
22
|
+
* nothing to disk.
|
|
21
23
|
*/
|
|
22
24
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
23
25
|
import { execFile } from "node:child_process";
|
|
@@ -27,6 +29,7 @@ import { Agent, request } from "node:https";
|
|
|
27
29
|
import { createConnection } from "node:net";
|
|
28
30
|
import { homedir } from "node:os";
|
|
29
31
|
import { basename, extname, join } from "node:path";
|
|
32
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
30
33
|
import { TracekitAgents } from "./adapters/openai-agents.js";
|
|
31
34
|
import { tracekitAI } from "./adapters/vercel-ai.js";
|
|
32
35
|
import { argsDigest } from "./jcs.js";
|
|
@@ -37,9 +40,14 @@ export { RPC_VERSION };
|
|
|
37
40
|
export { argsDigest, canonicalize, digest, strictParse, StrictJSONError } from "./jcs.js";
|
|
38
41
|
export const SYSTEM_CONFIG = "/etc/tracekit/client.json";
|
|
39
42
|
const CONNECT_TIMEOUT_MS = 2000;
|
|
40
|
-
const RETRIES = 3;
|
|
43
|
+
const RETRIES = 3; // tries of a call while its connection is lost; apart, while the signer refuses an event call (retryWait)
|
|
44
|
+
const BACKOFF_MS = 100, BACKOFF_CAP_MS = 2000; // the wait before an event call's second try, doubled for each next
|
|
41
45
|
export class SignerUnavailable extends Error {
|
|
42
46
|
name = "SignerUnavailable";
|
|
47
|
+
recorded = false; // a write call's error: see Client
|
|
48
|
+
}
|
|
49
|
+
class TimeoutUnavailable extends SignerUnavailable {
|
|
50
|
+
what = "no answer from the signer"; // the message Client.call re-raises it with, before " within {timeout}s"
|
|
43
51
|
}
|
|
44
52
|
/** The signer answered but does not speak this client's protocol version. It is left running. */
|
|
45
53
|
export class Incompatible extends Error {
|
|
@@ -56,13 +64,42 @@ export class RPCError extends Error {
|
|
|
56
64
|
code;
|
|
57
65
|
retryAfterMs;
|
|
58
66
|
name = "RPCError";
|
|
67
|
+
recorded = false; // a write call's error: see Client
|
|
59
68
|
constructor(code, message, retryAfterMs) {
|
|
60
69
|
super(`${code}: ${message}`);
|
|
61
70
|
this.code = code;
|
|
62
71
|
this.retryAfterMs = retryAfterMs;
|
|
63
72
|
}
|
|
64
73
|
}
|
|
74
|
+
/** The request may not have arrived. `sent` false: it never connected, so nothing went out. */
|
|
65
75
|
class ConnectionLost extends Error {
|
|
76
|
+
sent;
|
|
77
|
+
constructor(sent = true) {
|
|
78
|
+
super();
|
|
79
|
+
this.sent = sent;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Added to the message of a write call's error when a try of it may have been recorded (`recorded` null). */
|
|
83
|
+
const UNKNOWN = ". It may have been recorded: once the run closes, its bundle shows whether it was. Don't send it again " +
|
|
84
|
+
"as a new call: if it was recorded, it would be recorded twice";
|
|
85
|
+
/** The error of a request that went out and got no answer in time: it may have been recorded. */
|
|
86
|
+
function unanswered(ms) {
|
|
87
|
+
const e = new TimeoutUnavailable(`no answer from the signer within ${ms / 1000}s`);
|
|
88
|
+
e.recorded = null;
|
|
89
|
+
return e;
|
|
90
|
+
}
|
|
91
|
+
/** Milliseconds to wait before sending a call of `schema` again after its `tries`th try was refused with `e`; null: not
|
|
92
|
+
* again. Only an event call (one with a client_seq): the signer refuses a client_seq it already recorded before it
|
|
93
|
+
* writes anything, even after a restart or a write whose outcome it couldn't tell, so a retry is recorded once or
|
|
94
|
+
* refused (then the call rejects with that `unavailable`, as without a retry); any other call's request_id is
|
|
95
|
+
* remembered in memory only (tracekit/sdk/client.py _retry_wait). A quota_exceeded without retry_after_ms is a size
|
|
96
|
+
* limit the same request never fits. */
|
|
97
|
+
function retryWait(schema, e, tries) {
|
|
98
|
+
const limited = e.code === "quota_exceeded" && typeof e.retry_after_ms === "number";
|
|
99
|
+
if (!("client_seq" in schema.properties) || !(limited || e.code === "unavailable"))
|
|
100
|
+
return null;
|
|
101
|
+
const backoff = Math.min(BACKOFF_CAP_MS, BACKOFF_MS * 2 ** (tries - 1)) * (0.5 + Math.random() / 2); // jitter
|
|
102
|
+
return Math.max(typeof e.retry_after_ms === "number" ? e.retry_after_ms : 0, backoff);
|
|
66
103
|
}
|
|
67
104
|
const newId = () => randomUUID().replaceAll("-", "");
|
|
68
105
|
const hmac = (token, label, nonce) => createHmac("sha256", token).update(`${label}\n${nonce}`).digest("hex");
|
|
@@ -74,7 +111,7 @@ function withTimeout(p, ms, onTimeout) {
|
|
|
74
111
|
const t = new Promise((_, reject) => {
|
|
75
112
|
timer = setTimeout(() => {
|
|
76
113
|
onTimeout();
|
|
77
|
-
reject(new
|
|
114
|
+
reject(new TimeoutUnavailable(`no answer from the signer within ${ms / 1000}s`));
|
|
78
115
|
}, ms);
|
|
79
116
|
});
|
|
80
117
|
return Promise.race([p, t]).finally(() => clearTimeout(timer));
|
|
@@ -122,7 +159,7 @@ class Conn {
|
|
|
122
159
|
send(frame) {
|
|
123
160
|
return new Promise((resolve, reject) => {
|
|
124
161
|
if (this.sock.destroyed)
|
|
125
|
-
return reject(new ConnectionLost());
|
|
162
|
+
return reject(new ConnectionLost(false)); // nothing was written
|
|
126
163
|
const line = JSON.stringify(frame) + "\n"; // may throw: before anything waits for an answer
|
|
127
164
|
this.pending.push({ resolve, reject });
|
|
128
165
|
this.sock.ref();
|
|
@@ -130,9 +167,9 @@ class Conn {
|
|
|
130
167
|
});
|
|
131
168
|
}
|
|
132
169
|
}
|
|
133
|
-
function open(sock) {
|
|
170
|
+
function open(sock, timeoutMs = CONNECT_TIMEOUT_MS) {
|
|
134
171
|
return new Promise((resolve, reject) => {
|
|
135
|
-
sock.setTimeout(
|
|
172
|
+
sock.setTimeout(timeoutMs, () => sock.destroy(new Error("connect timed out")));
|
|
136
173
|
sock.once("connect", () => {
|
|
137
174
|
sock.setTimeout(0);
|
|
138
175
|
resolve(sock);
|
|
@@ -148,7 +185,8 @@ function check(hello, where) {
|
|
|
148
185
|
"Stop it with `tracekit down`, or replace it with `tracekit up --replace`", Array.isArray(proto) && proto.length === 2 && typeof proto[1] === "number" && proto[1] < RPC_VERSION);
|
|
149
186
|
}
|
|
150
187
|
/** A connection to the signer at `path` (a Unix socket or tcp://host:port) and its hello, after the version check. */
|
|
151
|
-
export async function connect(path, token) {
|
|
188
|
+
export async function connect(path, token, timeoutMs = CONNECT_TIMEOUT_MS) {
|
|
189
|
+
const deadline = Date.now() + timeoutMs, leftMs = () => Math.max(deadline - Date.now(), 1);
|
|
152
190
|
let conn, hello;
|
|
153
191
|
try {
|
|
154
192
|
if (path.startsWith("tcp://")) {
|
|
@@ -158,10 +196,10 @@ export async function connect(path, token) {
|
|
|
158
196
|
token ||= process.env.TRACEKIT_SIGNER_TOKEN;
|
|
159
197
|
if (!token)
|
|
160
198
|
throw new SignerUnavailable(`${path}: tcp:// signers need TRACEKIT_SIGNER_TOKEN`);
|
|
161
|
-
conn = new Conn(await open(createConnection({ host, port: Number(hostPort.slice(k + 1)) })));
|
|
199
|
+
conn = new Conn(await open(createConnection({ host, port: Number(hostPort.slice(k + 1)) }), leftMs()));
|
|
162
200
|
// the signer proves it holds the token over our nonce before we prove it over its own (transport/tcp_dev.py)
|
|
163
201
|
const nonce = randomBytes(16).toString("hex");
|
|
164
|
-
const reply = await withTimeout(conn.send({ method: "hello", nonce }),
|
|
202
|
+
const reply = await withTimeout(conn.send({ method: "hello", nonce }), leftMs(), () => conn.sock.destroy());
|
|
165
203
|
const proof = Buffer.from(String(reply.proof)), want = Buffer.from(hmac(token, "signer", nonce));
|
|
166
204
|
if (proof.length !== want.length || !timingSafeEqual(proof, want))
|
|
167
205
|
throw new Error("dev token proof mismatch");
|
|
@@ -170,19 +208,20 @@ export async function connect(path, token) {
|
|
|
170
208
|
conn.write({ proof: hmac(token, "client", reply.nonce) });
|
|
171
209
|
}
|
|
172
210
|
else if (process.platform !== "win32") {
|
|
173
|
-
conn = new Conn(await open(createConnection(path)));
|
|
211
|
+
conn = new Conn(await open(createConnection(path), leftMs()));
|
|
174
212
|
}
|
|
175
213
|
else {
|
|
176
214
|
throw new SignerUnavailable(`this platform has no Unix sockets: name the signer tcp://host:port, not ${path}`);
|
|
177
215
|
}
|
|
178
216
|
const c = conn;
|
|
179
|
-
hello = await withTimeout(c.send({ method: "hello" }),
|
|
217
|
+
hello = await withTimeout(c.send({ method: "hello" }), leftMs(), () => c.sock.destroy());
|
|
180
218
|
}
|
|
181
219
|
catch (e) {
|
|
182
220
|
conn?.sock.destroy();
|
|
183
221
|
if (e instanceof SignerUnavailable && !conn)
|
|
184
222
|
throw e;
|
|
185
|
-
|
|
223
|
+
const msg = `no signer answering at ${path}: ${e.message}`;
|
|
224
|
+
throw e instanceof TimeoutUnavailable && timeoutMs < CONNECT_TIMEOUT_MS ? new TimeoutUnavailable(msg) : new SignerUnavailable(msg);
|
|
186
225
|
}
|
|
187
226
|
try {
|
|
188
227
|
check(hello, path);
|
|
@@ -288,18 +327,25 @@ class Https {
|
|
|
288
327
|
this.agent = new Agent({ keepAlive: true, ca: file(env.TRACEKIT_SIGNER_CA), cert: file(cert),
|
|
289
328
|
key: cert ? file(env.TRACEKIT_SIGNER_KEY || cert) : undefined });
|
|
290
329
|
}
|
|
291
|
-
/** The answer frame
|
|
330
|
+
/** The answer frame, read from the body whatever the HTTP status. The client doesn't ask for error statuses
|
|
331
|
+
* (Tracekit-Errors), so a proxy in front sees 200 for a refusal and acts on none (no retry of a 503, no host ejected).
|
|
332
|
+
* ConnectionLost when the request may not have arrived, SignerUnavailable on a timeout (`recorded` false when it timed
|
|
333
|
+
* out connecting: nothing went out). */
|
|
292
334
|
post(frame, timeoutMs) {
|
|
293
335
|
const body = JSON.stringify(frame), tokenFile = process.env.TRACEKIT_SIGNER_TOKEN_FILE;
|
|
336
|
+
const apiKey = process.env.TRACEKIT_API_KEY?.trim();
|
|
294
337
|
const headers = { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) };
|
|
295
|
-
if (tokenFile) {
|
|
338
|
+
if (tokenFile) { // wins over an API key: it is re-read per call, so a rotated token is picked up
|
|
296
339
|
try {
|
|
297
|
-
headers.Authorization = "Bearer " + readFileSync(tokenFile, "utf8").trim();
|
|
340
|
+
headers.Authorization = "Bearer " + readFileSync(tokenFile, "utf8").trim();
|
|
298
341
|
}
|
|
299
342
|
catch (e) {
|
|
300
343
|
throw new SignerUnavailable(`cannot read the signer token file: ${e.message}`);
|
|
301
344
|
}
|
|
302
345
|
}
|
|
346
|
+
else if (apiKey) {
|
|
347
|
+
headers.Authorization = "Bearer " + apiKey;
|
|
348
|
+
}
|
|
303
349
|
return new Promise((resolve, reject) => {
|
|
304
350
|
const req = request(routeUrl(this.url, frame), { method: "POST", agent: this.agent, headers, timeout: timeoutMs }, (res) => {
|
|
305
351
|
let data = "";
|
|
@@ -318,27 +364,50 @@ class Https {
|
|
|
318
364
|
}
|
|
319
365
|
});
|
|
320
366
|
});
|
|
367
|
+
let connected = false; // nothing goes out until it connects (and the TLS handshake is done)
|
|
321
368
|
req.on("timeout", () => {
|
|
322
|
-
|
|
369
|
+
if (connected)
|
|
370
|
+
reject(unanswered(timeoutMs));
|
|
371
|
+
else {
|
|
372
|
+
const e = new TimeoutUnavailable(`could not connect to the signer at ${this.url.origin} within ${timeoutMs / 1000}s`);
|
|
373
|
+
e.what = `could not connect to the signer at ${this.url.origin}`;
|
|
374
|
+
reject(e);
|
|
375
|
+
}
|
|
323
376
|
req.destroy();
|
|
324
377
|
});
|
|
325
|
-
req.on("
|
|
378
|
+
req.on("socket", (s) => {
|
|
379
|
+
if (s.connecting)
|
|
380
|
+
s.once("secureConnect", () => (connected = true));
|
|
381
|
+
else
|
|
382
|
+
connected = true; // a kept-alive socket
|
|
383
|
+
});
|
|
384
|
+
req.on("error", () => reject(new ConnectionLost(connected)));
|
|
326
385
|
req.end(body);
|
|
327
386
|
});
|
|
328
387
|
}
|
|
329
388
|
async rpc(frame, timeoutMs) {
|
|
389
|
+
const deadline = Date.now() + timeoutMs;
|
|
330
390
|
if (!this.hello) {
|
|
331
|
-
const hello = await this.post({ method: "hello" }, timeoutMs)
|
|
391
|
+
const hello = await this.post({ method: "hello" }, timeoutMs).catch((e) => {
|
|
392
|
+
if (e instanceof SignerUnavailable)
|
|
393
|
+
e.recorded = false; // only the hello went out
|
|
394
|
+
throw e;
|
|
395
|
+
});
|
|
332
396
|
if (hello.error)
|
|
333
397
|
throw new RPCError(hello.error.code, hello.error.message ?? "");
|
|
334
398
|
check(hello, this.url.origin);
|
|
335
399
|
this.hello = hello;
|
|
336
400
|
}
|
|
337
|
-
|
|
401
|
+
const rem = deadline - Date.now();
|
|
402
|
+
if (rem <= 0)
|
|
403
|
+
throw new TimeoutUnavailable(`no answer from the signer within ${timeoutMs / 1000}s`);
|
|
404
|
+
return this.post(frame, rem);
|
|
338
405
|
}
|
|
339
406
|
}
|
|
340
407
|
/** Methods take the request object of an RPC and return its response, or reject with RPCError (a refusal),
|
|
341
|
-
* SignerUnavailable or Incompatible.
|
|
408
|
+
* SignerUnavailable or Incompatible. The error of a write call (one with a `request_id`) has `recorded`: false, it was
|
|
409
|
+
* not; null, a try of it may have been (its message says so); true, it was and only its answer was lost (an event's
|
|
410
|
+
* retry refused client_seq_reused). */
|
|
342
411
|
export class Client {
|
|
343
412
|
signer;
|
|
344
413
|
stream = newId();
|
|
@@ -415,7 +484,7 @@ export class Client {
|
|
|
415
484
|
}
|
|
416
485
|
return { method, ...req };
|
|
417
486
|
};
|
|
418
|
-
const timeout = this.timeoutMs + (req.timeout_ms ?? 0), deadline = Date.now() + timeout;
|
|
487
|
+
const timeout = this.timeoutMs + (req.timeout_ms ?? 0), deadline = Date.now() + timeout, assigned = claim;
|
|
419
488
|
let release = () => { };
|
|
420
489
|
if (claim) {
|
|
421
490
|
try {
|
|
@@ -423,12 +492,20 @@ export class Client {
|
|
|
423
492
|
}
|
|
424
493
|
catch (e) {
|
|
425
494
|
frame(); // used up: the signer's client_counter_gap covers a call it never saw
|
|
495
|
+
e.recorded = false; // it was not sent
|
|
426
496
|
throw e;
|
|
427
497
|
}
|
|
428
498
|
}
|
|
499
|
+
// tries: the signer's refusals of an event call (retryWait), counted apart from lost connections; sent: a try may
|
|
500
|
+
// have been recorded (no answer, or unavailable); recorded: one was (see Client)
|
|
501
|
+
let losses = 0, tries = 0, outage = null, sent = false, recorded = false;
|
|
429
502
|
try {
|
|
430
|
-
|
|
431
|
-
const left =
|
|
503
|
+
while (losses < RETRIES) {
|
|
504
|
+
const left = deadline - Date.now();
|
|
505
|
+
if (left <= 0) {
|
|
506
|
+
frame();
|
|
507
|
+
throw new SignerUnavailable(`no answer from the signer within ${timeout / 1000}s`);
|
|
508
|
+
}
|
|
432
509
|
let reply;
|
|
433
510
|
try {
|
|
434
511
|
if (this.https) {
|
|
@@ -439,22 +516,53 @@ export class Client {
|
|
|
439
516
|
reply = await this.poll(frame(), left);
|
|
440
517
|
}
|
|
441
518
|
else {
|
|
442
|
-
const conn = await this.connection();
|
|
443
|
-
|
|
519
|
+
const conn = await withTimeout(this.connection(), left, () => { });
|
|
520
|
+
const rem = deadline - Date.now();
|
|
521
|
+
if (rem <= 0) {
|
|
522
|
+
frame();
|
|
523
|
+
throw new SignerUnavailable(`no answer from the signer within ${timeout / 1000}s`);
|
|
524
|
+
}
|
|
525
|
+
reply = await withTimeout(conn.send(frame()), rem, () => conn.sock.destroy()).catch((e) => {
|
|
526
|
+
if (e instanceof TimeoutUnavailable)
|
|
527
|
+
e.recorded = null; // the request went out
|
|
528
|
+
throw e;
|
|
529
|
+
});
|
|
444
530
|
}
|
|
445
531
|
}
|
|
446
532
|
catch (e) {
|
|
447
|
-
if (e instanceof ConnectionLost)
|
|
533
|
+
if (e instanceof ConnectionLost) {
|
|
534
|
+
losses++;
|
|
535
|
+
// a lost hello, or a connect that failed, sent nothing; past both, the request may have gone out
|
|
536
|
+
sent ||= e.sent && (!this.https || this.https.hello !== null);
|
|
448
537
|
continue;
|
|
538
|
+
}
|
|
449
539
|
if (e instanceof SignerUnavailable)
|
|
450
540
|
frame(); // used up: the signer's client_counter_gap covers a call it never saw
|
|
541
|
+
if (e instanceof TimeoutUnavailable) { // worded with the call's timeout; keeps whether the try went out
|
|
542
|
+
const err = new SignerUnavailable(`${e.what} within ${timeout / 1000}s`);
|
|
543
|
+
err.recorded = e.recorded;
|
|
544
|
+
throw err;
|
|
545
|
+
}
|
|
451
546
|
throw e;
|
|
452
547
|
}
|
|
453
548
|
if (reply.error) {
|
|
454
|
-
const e = reply.error;
|
|
549
|
+
const e = reply.error, err = new RPCError(e.code, e.message ?? "", e.retry_after_ms);
|
|
455
550
|
if (["run_closed", "unknown_run"].includes(e.code))
|
|
456
551
|
this.seqs.delete(req.run_id); // no more events for it
|
|
457
|
-
|
|
552
|
+
// a try that may have been written was, if this client gave it its client_seq; a try the signer answered
|
|
553
|
+
// unavailable: that answer stands (the caller's outage path)
|
|
554
|
+
if (sent && e.code === "client_seq_reused") {
|
|
555
|
+
recorded = assigned;
|
|
556
|
+
throw outage ?? err;
|
|
557
|
+
}
|
|
558
|
+
sent ||= e.code === "unavailable";
|
|
559
|
+
const wait = retryWait(schema, e, ++tries);
|
|
560
|
+
if (wait === null || tries === RETRIES || Date.now() + wait >= deadline)
|
|
561
|
+
throw err;
|
|
562
|
+
if (e.code === "unavailable")
|
|
563
|
+
outage = err;
|
|
564
|
+
await sleep(wait); // then the same request: its request_id, stream and client_seq
|
|
565
|
+
continue;
|
|
458
566
|
}
|
|
459
567
|
if (method === "close_run")
|
|
460
568
|
this.seqs.delete(req.run_id);
|
|
@@ -462,6 +570,15 @@ export class Client {
|
|
|
462
570
|
}
|
|
463
571
|
throw new SignerUnavailable(`lost the connection to the signer ${RETRIES} times`);
|
|
464
572
|
}
|
|
573
|
+
catch (e) {
|
|
574
|
+
if (e instanceof SignerUnavailable || e instanceof RPCError) {
|
|
575
|
+
// not a write: null means a write's unknown outcome only
|
|
576
|
+
e.recorded = !("request_id" in req) ? false : recorded ? true : sent || e.recorded === null ? null : false;
|
|
577
|
+
if (e.recorded === null)
|
|
578
|
+
e.message += UNKNOWN;
|
|
579
|
+
}
|
|
580
|
+
throw e;
|
|
581
|
+
}
|
|
465
582
|
finally {
|
|
466
583
|
release();
|
|
467
584
|
}
|
|
@@ -489,9 +606,13 @@ export class Client {
|
|
|
489
606
|
}
|
|
490
607
|
/** One request on a connection of its own, closed after the answer. */
|
|
491
608
|
async poll(frame, timeout) {
|
|
492
|
-
const
|
|
609
|
+
const deadline = Date.now() + timeout;
|
|
610
|
+
const { conn } = await this.dial(Math.min(CONNECT_TIMEOUT_MS, timeout));
|
|
493
611
|
try {
|
|
494
|
-
|
|
612
|
+
const rem = deadline - Date.now();
|
|
613
|
+
if (rem <= 0)
|
|
614
|
+
throw new TimeoutUnavailable(`no answer from the signer within ${timeout / 1000}s`);
|
|
615
|
+
return await withTimeout(conn.send(frame), rem, () => { });
|
|
495
616
|
}
|
|
496
617
|
finally {
|
|
497
618
|
conn.sock.destroy();
|
|
@@ -511,10 +632,10 @@ export class Client {
|
|
|
511
632
|
}
|
|
512
633
|
return this.conn;
|
|
513
634
|
}
|
|
514
|
-
async dial() {
|
|
635
|
+
async dial(timeoutMs = CONNECT_TIMEOUT_MS) {
|
|
515
636
|
let c;
|
|
516
637
|
if (this.signer) {
|
|
517
|
-
c = await connect(this.signer);
|
|
638
|
+
c = await connect(this.signer, undefined, Math.min(CONNECT_TIMEOUT_MS, timeoutMs));
|
|
518
639
|
}
|
|
519
640
|
else {
|
|
520
641
|
const d = devRuntimeDir();
|
|
@@ -616,7 +737,8 @@ export class RunHandle {
|
|
|
616
737
|
if (closed !== this.runId)
|
|
617
738
|
return Promise.resolve(); // renewed already
|
|
618
739
|
this.renewing ??= (async () => {
|
|
619
|
-
|
|
740
|
+
// a later run of the process's agent, whose model may still hold what the closed run read
|
|
741
|
+
const agent = { agent: { name: this.renewAs }, continues: true };
|
|
620
742
|
let r;
|
|
621
743
|
try { // linked to the closed run while it is still closing
|
|
622
744
|
r = await this.client.call("register_run", { ...agent, parent: { run_id: this.runId, run_token: this.runToken } });
|
|
@@ -642,8 +764,9 @@ export class RunHandle {
|
|
|
642
764
|
if (!(e instanceof SignerUnavailable))
|
|
643
765
|
throw e;
|
|
644
766
|
const open = failOpen(this.failModes, fields.tool_class_hint);
|
|
645
|
-
|
|
646
|
-
|
|
767
|
+
const why = e.message.replace(UNKNOWN, ""); // the outage path, worded as before: `recorded` stays on the error
|
|
768
|
+
warn(`tracekit: ${tool} ${open ? "runs unrecorded (fail open)" : "is denied (fail closed)"}: ${why}`);
|
|
769
|
+
return { decision: open ? "allow" : "deny", rule_ids: [], reason: `signer unavailable: ${why}`.slice(0, 1024), unavailable: true };
|
|
647
770
|
}
|
|
648
771
|
try { // a denied call is never completed: nothing to remember; others are capped, as `at` is
|
|
649
772
|
if (d.decision !== "deny")
|
|
@@ -654,8 +777,11 @@ export class RunHandle {
|
|
|
654
777
|
}
|
|
655
778
|
return d;
|
|
656
779
|
}
|
|
657
|
-
/** Never rejects: a failure to record a call that already ran
|
|
658
|
-
*
|
|
780
|
+
/** Never rejects: a failure to record a call that already ran resolves null and warns that it was not recorded (the
|
|
781
|
+
* run's bundle shows the call as decided and not completed) or that it may not have been (no answer to a try that
|
|
782
|
+
* went out: the bundle has its tool.result or a decided_not_completed gap). A retry the signer refuses as already
|
|
783
|
+
* recorded (client_seq_reused) was recorded: null, no warning. Defaults decision_id and args_digest to those of the
|
|
784
|
+
* last `decide` for this tool call. */
|
|
659
785
|
async complete(toolCallId, status = "ok", fields = {}) {
|
|
660
786
|
const decided = this.decided.get(toolCallId);
|
|
661
787
|
this.decided.delete(toolCallId);
|
|
@@ -663,7 +789,13 @@ export class RunHandle {
|
|
|
663
789
|
return await this.call("complete", { tool_call_id: toolCallId, status, ...decided, ...fields });
|
|
664
790
|
}
|
|
665
791
|
catch (e) {
|
|
666
|
-
|
|
792
|
+
const recorded = e.recorded, message = e.message;
|
|
793
|
+
if (recorded === null)
|
|
794
|
+
warn(`tracekit: the result of ${toolCallId} may not have been recorded (${message.replace(UNKNOWN, "")}). Once ` +
|
|
795
|
+
`the run closes, its bundle has ${toolCallId}'s tool.result if it was, or a decided_not_completed gap if it wasn't.`);
|
|
796
|
+
else if (!recorded)
|
|
797
|
+
warn(`tracekit: the result of ${toolCallId} was not recorded: ${message}. Once the run closes, its bundle shows ` +
|
|
798
|
+
`${toolCallId} as decided and not completed.`);
|
|
667
799
|
return null;
|
|
668
800
|
}
|
|
669
801
|
finally {
|
|
@@ -687,8 +819,9 @@ export class RunHandle {
|
|
|
687
819
|
...(approvalIdHint ? { approval_id_hint: approvalIdHint } : {}), ...fields });
|
|
688
820
|
}
|
|
689
821
|
catch (e) {
|
|
690
|
-
|
|
691
|
-
|
|
822
|
+
const why = e.message.replace(UNKNOWN, ""); // handed to the model: `recorded` stays on the error
|
|
823
|
+
warn(`tracekit: ${tool} is blocked: approval_consume failed: ${why}`);
|
|
824
|
+
return { ok: false, rule_ids: [], reason: `approval_consume failed: ${why}`.slice(0, 1024) };
|
|
692
825
|
}
|
|
693
826
|
}
|
|
694
827
|
/** Records content that entered the run other than as a tool result (a mail, a ticket, a page the app fetched) for
|
package/dist/v2/executor.d.ts
CHANGED
|
@@ -8,10 +8,13 @@
|
|
|
8
8
|
* const actions = await executorActions("https://executor.internal:8090", run, { headers: { authorization: `Bearer ${token}` } });
|
|
9
9
|
* new Agent({ tools: actions.map((a) => openaiAgentsTool(tool, a)) });
|
|
10
10
|
* generateText({ tools: Object.fromEntries(actions.map((a) => [a.name, vercelTool(a, jsonSchema)])) });
|
|
11
|
+
* // Claude Agent SDK: its `tool` and `createSdkMcpServer`, and zod's `z`
|
|
12
|
+
* const mcpServers = { [SERVER]: createSdkMcpServer({ name: SERVER, tools: actions.map((a) => claudeAgentSdkTool(tool, z, a)) }) };
|
|
13
|
+
* query({ prompt, options: { mcpServers, hooks: tracekitHooks(run, { mcpServers, executorActions: actions }) } });
|
|
11
14
|
*
|
|
12
15
|
* `headers` authenticate the agent to the executor (a bearer or service-account token); for a client certificate pass
|
|
13
|
-
* a `fetch` that presents one. The tools carry EXECUTOR
|
|
14
|
-
* decides and records them (T2). A
|
|
16
|
+
* a `fetch` that presents one. The tools carry EXECUTOR (the Claude Agent SDK hooks know theirs by SERVER and the
|
|
17
|
+
* actions), so the Tracekit adapters leave them to the executor, which decides and records them (T2). A
|
|
15
18
|
* refusal (deny, an approval not given, the signer unreachable) throws ExecutorRefused with the executor's message,
|
|
16
19
|
* which the framework hands the model as the tool's error.
|
|
17
20
|
*/
|
|
@@ -47,4 +50,10 @@ export declare const vercelTool: (a: Action, jsonSchema: (s: any) => unknown) =>
|
|
|
47
50
|
toolCallId?: string;
|
|
48
51
|
}) => Promise<Frame>;
|
|
49
52
|
};
|
|
53
|
+
/** A Claude Agent SDK tool for the in-process MCP server under SERVER; `tool` is the SDK's, `z` is zod. The SDK's
|
|
54
|
+
* `tool()` takes zod only, so the action's JSON Schema is converted: an object whose properties are strings, numbers,
|
|
55
|
+
* integers, booleans, string enums or arrays of those, and which requires only properties it declares; anything else
|
|
56
|
+
* throws, naming the property. Arguments it doesn't declare reach the executor, which checks them, unless it is closed
|
|
57
|
+
* (`additionalProperties: false`). The handler passes the executor the model's tool-use id, which the CLI sends. */
|
|
58
|
+
export declare function claudeAgentSdkTool<T>(tool: (name: string, description: string, schema: any, handler: (args: any, extra?: any) => Promise<any>) => T, z: any, a: Action): T;
|
|
50
59
|
export {};
|
package/dist/v2/executor.js
CHANGED
|
@@ -56,3 +56,43 @@ export const vercelTool = (a, jsonSchema) => ({
|
|
|
56
56
|
[EXECUTOR]: true, description: a.description, inputSchema: jsonSchema(a.args),
|
|
57
57
|
execute: (input, opts) => a.call(input, opts?.toolCallId),
|
|
58
58
|
});
|
|
59
|
+
const SCALARS = new Map([["string", (z) => z.string()], ["number", (z) => z.number()],
|
|
60
|
+
["integer", (z) => z.number().int()], ["boolean", (z) => z.boolean()]]);
|
|
61
|
+
/** A Claude Agent SDK tool for the in-process MCP server under SERVER; `tool` is the SDK's, `z` is zod. The SDK's
|
|
62
|
+
* `tool()` takes zod only, so the action's JSON Schema is converted: an object whose properties are strings, numbers,
|
|
63
|
+
* integers, booleans, string enums or arrays of those, and which requires only properties it declares; anything else
|
|
64
|
+
* throws, naming the property. Arguments it doesn't declare reach the executor, which checks them, unless it is closed
|
|
65
|
+
* (`additionalProperties: false`). The handler passes the executor the model's tool-use id, which the CLI sends. */
|
|
66
|
+
export function claudeAgentSdkTool(tool, z, a) {
|
|
67
|
+
if (a.args?.type !== "object")
|
|
68
|
+
throw new Error(`${a.name}: the arguments' schema must be an object`);
|
|
69
|
+
const props = a.args.properties ?? {};
|
|
70
|
+
const required = Array.isArray(a.args.required) ? a.args.required : [];
|
|
71
|
+
for (const k of required) {
|
|
72
|
+
if (!Object.hasOwn(props, String(k)))
|
|
73
|
+
throw new Error(`${a.name}: argument ${JSON.stringify(k)}: required but not in properties`);
|
|
74
|
+
}
|
|
75
|
+
// lean: string enums only; a number or mixed enum throws until an action needs one
|
|
76
|
+
const one = (s) => s?.enum === undefined ? SCALARS.get(s?.type)?.(z)
|
|
77
|
+
: Array.isArray(s.enum) && s.enum.length && s.enum.every((v) => typeof v === "string") ? z.enum(s.enum) : undefined;
|
|
78
|
+
const shape = Object.fromEntries(Object.entries(props).map(([k, s]) => {
|
|
79
|
+
const item = s?.type === "array" ? one(s.items) : undefined;
|
|
80
|
+
const t = s?.type === "array" ? item && z.array(item) : one(s);
|
|
81
|
+
if (!t)
|
|
82
|
+
throw new Error(`${a.name}: argument ${JSON.stringify(k)}: unsupported schema ${JSON.stringify(s)?.slice(0, 200)}`);
|
|
83
|
+
const d = typeof s.description === "string" ? t.describe(s.description) : t;
|
|
84
|
+
return [k, required.includes(k) ? d : d.optional()];
|
|
85
|
+
}));
|
|
86
|
+
// zod strips undeclared keys by default: keep them for the executor, or refuse them as it would
|
|
87
|
+
const schema = a.args.additionalProperties === false ? z.object(shape).strict() : z.object(shape).passthrough();
|
|
88
|
+
return tool(a.name, a.description, schema, async (args, extra) => {
|
|
89
|
+
try {
|
|
90
|
+
return { content: [{ type: "text", text: JSON.stringify(await a.call(args, extra?._meta?.["claudecode/toolUseId"])) }] };
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
if (e instanceof ExecutorRefused)
|
|
94
|
+
return { content: [{ type: "text", text: e.message }], isError: true };
|
|
95
|
+
throw e;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
package/dist/v2/rpc_schema.d.ts
CHANGED
package/dist/v2/rpc_schema.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export const RPC_VERSION =
|
|
1
|
+
export const RPC_VERSION = 26;
|
|
2
2
|
export const REQUESTS = {
|
|
3
|
-
"register_run": { "type": "object", "additionalProperties": false, "required": ["request_id", "agent"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "tenant": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "principal": { "type": "string", "maxLength": 256 }, "principal_token": { "type": "string", "maxLength": 16384 }, "source": { "const": "migrated" }, "analyzes": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "replay_of": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "investigation": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "parent": { "type": "object", "additionalProperties": false, "required": ["run_id", "run_token"], "properties": { "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 } } }, "caller": { "type": "string", "maxLength": 256, "pattern": "^[a-z0-9_]+:[^\\n]+(?![\\s\\S])" }, "box": { "type": "object", "additionalProperties": false, "required": ["id", "image_digest", "allow"], "properties": { "id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "image_digest": { "type": "string", "maxLength": 71, "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])" }, "channel": { "const": "agent" }, "allow": { "type": "array", "maxItems": 256, "items": { "type": "string", "maxLength": 261, "minLength": 1, "pattern": "^[A-Za-z0-9.*:\\[\\]_-]+(?![\\s\\S])" } } } }, "agent": { "type": "object", "additionalProperties": false, "required": ["name"], "properties": { "name": { "type": "string", "maxLength": 128, "minLength": 1 }, "version": { "type": "string", "maxLength": 64 } } } } },
|
|
3
|
+
"register_run": { "type": "object", "additionalProperties": false, "required": ["request_id", "agent"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "tenant": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "principal": { "type": "string", "maxLength": 256 }, "principal_token": { "type": "string", "maxLength": 16384 }, "source": { "const": "migrated" }, "analyzes": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "replay_of": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "investigation": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "parent": { "type": "object", "additionalProperties": false, "required": ["run_id", "run_token"], "properties": { "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 } } }, "caller": { "type": "string", "maxLength": 256, "pattern": "^[a-z0-9_]+:[^\\n]+(?![\\s\\S])" }, "box": { "type": "object", "additionalProperties": false, "required": ["id", "image_digest", "allow"], "properties": { "id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "image_digest": { "type": "string", "maxLength": 71, "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])" }, "channel": { "const": "agent" }, "allow": { "type": "array", "maxItems": 256, "items": { "type": "string", "maxLength": 261, "minLength": 1, "pattern": "^[A-Za-z0-9.*:\\[\\]_-]+(?![\\s\\S])" } } } }, "continues": { "const": true }, "agent": { "type": "object", "additionalProperties": false, "required": ["name"], "properties": { "name": { "type": "string", "maxLength": 128, "minLength": 1 }, "version": { "type": "string", "maxLength": 64 } } } } },
|
|
4
4
|
"decide": { "type": "object", "additionalProperties": false, "required": ["request_id", "run_id", "run_token", "stream", "client_seq", "tool_call_id", "tool", "args_source", "args"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 }, "stream": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "client_seq": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "caller": { "type": "string", "maxLength": 256, "pattern": "^[a-z0-9_]+:[^\\n]+(?![\\s\\S])" }, "tool_call_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "attempt": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "tool": { "type": "string", "maxLength": 256, "minLength": 1 }, "tool_class_hint": { "type": "string", "maxLength": 64 }, "args_source": { "enum": ["raw", "parsed", "coerced"] }, "args": {} }, "if": { "properties": { "args_source": { "const": "raw" } } }, "then": { "properties": { "args": { "type": "string", "maxLength": 1048576 } } } },
|
|
5
5
|
"complete": { "type": "object", "additionalProperties": false, "required": ["request_id", "run_id", "run_token", "stream", "client_seq", "tool_call_id", "decision_id", "args_digest", "status"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 }, "stream": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "client_seq": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "caller": { "type": "string", "maxLength": 256, "pattern": "^[a-z0-9_]+:[^\\n]+(?![\\s\\S])" }, "tool_call_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "attempt": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "decision_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "args_digest": { "type": "string", "maxLength": 71, "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])" }, "status": { "enum": ["ok", "error"] }, "result": {}, "error": { "type": "string", "maxLength": 4096 }, "redacted": { "const": true }, "redaction": { "type": "object", "additionalProperties": false, "required": [], "properties": { "rules": { "type": "array", "maxItems": 32, "items": { "type": "string", "maxLength": 64 } }, "count": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } } } },
|
|
6
6
|
"observe": { "type": "object", "additionalProperties": false, "required": ["request_id", "run_id", "run_token", "stream", "client_seq", "source", "trust", "value"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 }, "stream": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "client_seq": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "caller": { "type": "string", "maxLength": 256, "pattern": "^[a-z0-9_]+:[^\\n]+(?![\\s\\S])" }, "source": { "type": "string", "maxLength": 256, "minLength": 1 }, "trust": { "enum": ["trusted", "untrusted"] }, "value": {} } },
|
|
@@ -50,4 +50,7 @@ export const REQUESTS = {
|
|
|
50
50
|
"grant_issue": { "type": "object", "additionalProperties": false, "required": ["request_id", "run_id", "intent", "caveats", "limits", "expires_at"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "approval_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "intent": { "type": "string", "maxLength": 64, "pattern": "^[a-z][a-z0-9_.-]{0,63}(?![\\s\\S])" }, "caveats": { "type": "array", "maxItems": 16, "items": { "type": "object", "additionalProperties": false, "required": ["field", "op", "value"], "properties": { "field": { "type": "string", "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*(?![\\s\\S])" }, "op": { "enum": ["==", "<=", ">=", "<", ">", "in"] }, "value": {} } } }, "limits": { "type": "array", "minItems": 1, "maxItems": 4, "items": { "type": "object", "additionalProperties": false, "required": ["op", "max"], "properties": { "op": { "enum": ["sum", "count"] }, "field": { "type": "string", "maxLength": 64, "pattern": "^[a-z][a-z0-9_]*(?![\\s\\S])" }, "max": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } } } }, "expires_at": { "type": "string", "maxLength": 27, "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{6}Z(?![\\s\\S])" }, "description": { "type": "string", "maxLength": 512 }, "tools": { "type": "array", "maxItems": 16, "items": { "type": "string", "maxLength": 256, "minLength": 1 } } } },
|
|
51
51
|
"grant_list": { "type": "object", "additionalProperties": false, "required": [], "properties": { "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" } } },
|
|
52
52
|
"grant_revoke": { "type": "object", "additionalProperties": false, "required": ["request_id", "grant_id"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "grant_id": { "type": "string", "maxLength": 18, "pattern": "^g-[0-9a-f]{16}(?![\\s\\S])" }, "reason": { "type": "string", "maxLength": 1024 } } },
|
|
53
|
+
"export_run": { "type": "object", "additionalProperties": false, "required": ["run_id"], "properties": { "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "offset": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "digest": { "type": "string", "maxLength": 71, "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])" } } },
|
|
54
|
+
"call_state": { "type": "object", "additionalProperties": false, "required": ["run_id", "run_token", "tool_call_id"], "properties": { "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 }, "tool_call_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "args_digest": { "type": "string", "maxLength": 71, "pattern": "^sha256:[0-9a-f]{64}(?![\\s\\S])" } } },
|
|
55
|
+
"call_claim": { "type": "object", "additionalProperties": false, "required": ["request_id", "run_id", "run_token", "tool_call_id", "attempt", "answers"], "properties": { "request_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "run_token": { "type": "string", "maxLength": 1024, "minLength": 1 }, "tool_call_id": { "type": "string", "maxLength": 128, "minLength": 1, "pattern": "^[A-Za-z0-9._:-]+(?![\\s\\S])" }, "attempt": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 }, "answers": { "type": "integer", "minimum": 0, "maximum": 9007199254740991 } } },
|
|
53
56
|
};
|
package/dist/verify/index.d.ts
CHANGED
|
@@ -23,10 +23,10 @@ import { type Floats } from "./jcs.js";
|
|
|
23
23
|
export { MAX_ENTRIES, MAX_ENTRY, MAX_TOTAL, Unusable, readZip } from "./zip.js";
|
|
24
24
|
export { StrictJSONError, canonicalize, strictParse, strictParseBytes } from "./jcs.js";
|
|
25
25
|
/** This verifier's release (the package's). */
|
|
26
|
-
export declare const VERSION = "1.
|
|
26
|
+
export declare const VERSION = "1.7.3";
|
|
27
27
|
/** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
|
|
28
28
|
* or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
|
|
29
|
-
export declare const READS = "1.
|
|
29
|
+
export declare const READS = "1.7.3";
|
|
30
30
|
export declare const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
|
|
31
31
|
/** The integrity of a trust config that can't be used: nothing in the bundle was checked. */
|
|
32
32
|
export declare const TRUST_UNUSABLE = "UNVERIFIABLE (the trust file can't be used)";
|
package/dist/verify/index.js
CHANGED
|
@@ -20,7 +20,7 @@
|
|
|
20
20
|
* verifier as a browser page (verify.html).
|
|
21
21
|
*/
|
|
22
22
|
import { StrictJSONError, canonicalize, repr as quoted, strictParseBytes } from "./jcs.js";
|
|
23
|
-
import { HYBRID, NoteError, SIGNER_LEAVES, b64decode, bytes, checkWitnesses, equal, keyAlg, leafHash, openNote, parseLeaf, parseVkey, registryOrigin, runHash, sha256hex, spkiKid, unhex, verifyConsistency, verifyInclusion, verifyV2, vkey, } from "./primitives.js";
|
|
23
|
+
import { ED25519, HYBRID, NoteError, SIGNER_LEAVES, b64decode, bytes, checkWitnesses, equal, keyAlg, leafHash, openNote, parseLeaf, parseVkey, registryOrigin, runHash, sha256hex, spkiKid, unhex, verifyConsistency, verifyInclusion, verifyV2, vkey, } from "./primitives.js";
|
|
24
24
|
import { Detector } from "./detect.js";
|
|
25
25
|
import { same, validateEvent } from "./schema.js";
|
|
26
26
|
import { BadZipFile, MAX_ENTRY, Unusable, readZip } from "./zip.js";
|
|
@@ -28,10 +28,10 @@ import VERSIONS_JSON from "./versions.json" with { type: "json" };
|
|
|
28
28
|
export { MAX_ENTRIES, MAX_ENTRY, MAX_TOTAL, Unusable, readZip } from "./zip.js";
|
|
29
29
|
export { StrictJSONError, canonicalize, strictParse, strictParseBytes } from "./jcs.js";
|
|
30
30
|
/** This verifier's release (the package's). */
|
|
31
|
-
export const VERSION = "1.
|
|
31
|
+
export const VERSION = "1.7.3";
|
|
32
32
|
/** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
|
|
33
33
|
* or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
|
|
34
|
-
export const READS = "1.
|
|
34
|
+
export const READS = "1.7.3";
|
|
35
35
|
/** The browser verifier of the latest release (docs/RELEASING.md). */
|
|
36
36
|
const PAGE = "https://cygnux-labs.github.io/Tracekit/verify/";
|
|
37
37
|
export const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
|
|
@@ -219,6 +219,12 @@ async function loadTrust(data, name) {
|
|
|
219
219
|
throw new ValueError(`pinned key ${repr(cut(k, 80))} is not a vkey: ${e.message}`);
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
|
+
for (const k of t.logs) { // a log key named after another key's fingerprint pins nothing a note could be signed under
|
|
223
|
+
const p = await parseVkey(k), m = /^tracekit\.local\/k([0-9a-f]{64})(?=\/|$)/.exec(p.name);
|
|
224
|
+
if (p.type === ED25519 && m && m[1] !== await sha256hex(p.pub))
|
|
225
|
+
throw new ValueError(`pinned log key ${p.name} is named after another key: a key-derived origin is `
|
|
226
|
+
+ "tracekit.local/k + the SHA-256 of the key it names");
|
|
227
|
+
}
|
|
222
228
|
await checkWitnesses(opt(t, "witnesses").map((w) => w.vkey));
|
|
223
229
|
const classes = new Map();
|
|
224
230
|
for (const w of opt(t, "witnesses")) {
|
package/dist/verify.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="utf-8">
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
6
|
-
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-
|
|
6
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-CrGVVBeDJZ+9XrI+RkBx1lPQW8b45d4O1uuz6U2oRc0='; style-src 'sha256-41aEPfNKIK0vxFn3JTgv68G+SOVBoDbHT4QPLHGL360='; worker-src blob:; connect-src 'none'">
|
|
7
7
|
<title>tracekit verify</title>
|
|
8
8
|
<style>
|
|
9
9
|
:root {
|
|
@@ -1181,7 +1181,7 @@ const __index = (() => {
|
|
|
1181
1181
|
* verifier as a browser page (verify.html).
|
|
1182
1182
|
*/
|
|
1183
1183
|
const { StrictJSONError: StrictJSONError, canonicalize: canonicalize, repr: quoted, strictParseBytes: strictParseBytes } = __jcs;
|
|
1184
|
-
const { HYBRID: HYBRID, NoteError: NoteError, SIGNER_LEAVES: SIGNER_LEAVES, b64decode: b64decode, bytes: bytes, checkWitnesses: checkWitnesses, equal: equal, keyAlg: keyAlg, leafHash: leafHash, openNote: openNote, parseLeaf: parseLeaf, parseVkey: parseVkey, registryOrigin: registryOrigin, runHash: runHash, sha256hex: sha256hex, spkiKid: spkiKid, unhex: unhex, verifyConsistency: verifyConsistency, verifyInclusion: verifyInclusion, verifyV2: verifyV2, vkey: vkey } = __primitives;
|
|
1184
|
+
const { ED25519: ED25519, HYBRID: HYBRID, NoteError: NoteError, SIGNER_LEAVES: SIGNER_LEAVES, b64decode: b64decode, bytes: bytes, checkWitnesses: checkWitnesses, equal: equal, keyAlg: keyAlg, leafHash: leafHash, openNote: openNote, parseLeaf: parseLeaf, parseVkey: parseVkey, registryOrigin: registryOrigin, runHash: runHash, sha256hex: sha256hex, spkiKid: spkiKid, unhex: unhex, verifyConsistency: verifyConsistency, verifyInclusion: verifyInclusion, verifyV2: verifyV2, vkey: vkey } = __primitives;
|
|
1185
1185
|
const { Detector: Detector } = __detect;
|
|
1186
1186
|
const { same: same, validateEvent: validateEvent } = __schema;
|
|
1187
1187
|
const { BadZipFile: BadZipFile, MAX_ENTRY: MAX_ENTRY, Unusable: Unusable, readZip: readZip } = __zip;
|
|
@@ -1189,10 +1189,10 @@ const VERSIONS_JSON = {"1.1.0":{"types":["input.observed","content.accessed","co
|
|
|
1189
1189
|
|
|
1190
1190
|
|
|
1191
1191
|
/** This verifier's release (the package's). */
|
|
1192
|
-
const VERSION = "1.
|
|
1192
|
+
const VERSION = "1.7.3";
|
|
1193
1193
|
/** The newest bundle format version this verifier reads: the reference's VERSIONS' newest row (tracekit/bundle_v2.py),
|
|
1194
1194
|
* or VERSION when later (tracekit/verify/v2.py READS); a bundle needing a later one is UNVERIFIABLE. */
|
|
1195
|
-
const READS = "1.
|
|
1195
|
+
const READS = "1.7.3";
|
|
1196
1196
|
/** The browser verifier of the latest release (docs/RELEASING.md). */
|
|
1197
1197
|
const PAGE = "https://cygnux-labs.github.io/Tracekit/verify/";
|
|
1198
1198
|
const EXIT_OK = 0, EXIT_FAIL = 1, EXIT_BAD = 2, EXIT_WARN = 3;
|
|
@@ -1380,6 +1380,12 @@ async function loadTrust(data, name) {
|
|
|
1380
1380
|
throw new ValueError(`pinned key ${repr(cut(k, 80))} is not a vkey: ${e.message}`);
|
|
1381
1381
|
}
|
|
1382
1382
|
}
|
|
1383
|
+
for (const k of t.logs) { // a log key named after another key's fingerprint pins nothing a note could be signed under
|
|
1384
|
+
const p = await parseVkey(k), m = /^tracekit\.local\/k([0-9a-f]{64})(?=\/|$)/.exec(p.name);
|
|
1385
|
+
if (p.type === ED25519 && m && m[1] !== await sha256hex(p.pub))
|
|
1386
|
+
throw new ValueError(`pinned log key ${p.name} is named after another key: a key-derived origin is `
|
|
1387
|
+
+ "tracekit.local/k + the SHA-256 of the key it names");
|
|
1388
|
+
}
|
|
1383
1389
|
await checkWitnesses(opt(t, "witnesses").map((w) => w.vkey));
|
|
1384
1390
|
const classes = new Map();
|
|
1385
1391
|
for (const w of opt(t, "witnesses")) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cygnuxlabs/tracekit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.3",
|
|
4
4
|
"description": "Tracekit for TypeScript/JavaScript agents: a native client of the Tracekit signer: policy-gated tool calls and signed evidence, no runtime dependencies.",
|
|
5
5
|
"keywords": ["ai-agents", "agent-security", "audit-log", "tamper-evident", "guardrails", "mcp", "openai-agents",
|
|
6
6
|
"vercel-ai", "claude-agent-sdk", "observability", "provenance", "llm"],
|
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
"test": "npm run build && node --test test/*.test.mjs"
|
|
28
28
|
},
|
|
29
29
|
"optionalDependencies": {
|
|
30
|
-
"@cygnuxlabs/tracekit-signer-darwin-arm64": "1.
|
|
31
|
-
"@cygnuxlabs/tracekit-signer-linux-x64-gnu": "1.
|
|
32
|
-
"@cygnuxlabs/tracekit-signer-linux-arm64-gnu": "1.
|
|
33
|
-
"@cygnuxlabs/tracekit-signer-win32-x64": "1.
|
|
30
|
+
"@cygnuxlabs/tracekit-signer-darwin-arm64": "1.7.3",
|
|
31
|
+
"@cygnuxlabs/tracekit-signer-linux-x64-gnu": "1.7.3",
|
|
32
|
+
"@cygnuxlabs/tracekit-signer-linux-arm64-gnu": "1.7.3",
|
|
33
|
+
"@cygnuxlabs/tracekit-signer-win32-x64": "1.7.3"
|
|
34
34
|
},
|
|
35
35
|
"peerDependencies": { "@openai/agents": ">=0.20.0", "ai": ">=7.0.0", "@anthropic-ai/claude-agent-sdk": ">=0.3.0" },
|
|
36
36
|
"peerDependenciesMeta": {
|