@cygnuxlabs/tracekit 1.5.3 → 1.7.2

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
@@ -39,11 +39,13 @@ const client = new Client(); // or new Client({ sig
39
39
  const run = await client.registerRun("research-bot");
40
40
  const d = await run.decide(call.id, "Bash", call.function.arguments); // the raw model string, or a parsed value
41
41
  if (d.decision === "allow") {
42
- const out = await runShell(call);
43
- await run.complete(call.id, "ok", { result: out }); // never throws: a recording failure is a warning
42
+ if ((await run.approvalConsume(call.id, "Bash", call.function.arguments)).ok) // never throws: ok false means it doesn't run
43
+ await run.complete(call.id, "ok", { result: await runShell(call) }); // never throws: a recording failure is a warning
44
44
  } else if (d.decision === "ask") {
45
45
  const { approval_id } = await run.approvalRequest(call.id);
46
46
  const { state } = await run.approvalWait(approval_id, 300_000); // on a connection of its own
47
+ if (state === "approved" && (await run.approvalConsume(call.id, "Bash", call.function.arguments, approval_id)).ok)
48
+ await run.complete(call.id, "ok", { result: await runShell(call) });
47
49
  }
48
50
  await run.close();
49
51
  await client.close(); // waits for what is in flight
@@ -51,7 +53,10 @@ await client.close(); // waits for what is i
51
53
 
52
54
  - **Signer:** `$TRACEKIT_SIGNER` names a Unix socket, `tcp://127.0.0.1:port` (with `$TRACEKIT_SIGNER_TOKEN`; both sides
53
55
  prove they hold it, it never goes on the wire) or `https://host:port` (`$TRACEKIT_SIGNER_TOKEN_FILE`: a bearer token
54
- re-read per call; `$TRACEKIT_SIGNER_CERT`/`_KEY`: mTLS; `$TRACEKIT_SIGNER_CA`: the signer's CA). In system mode the
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
55
60
  signer named by the root-owned `/etc/tracekit/client.json` is used and a different `$TRACEKIT_SIGNER` is refused.
56
61
  Otherwise the same-user dev signer is found, or started with `tracekit up --json`: `$TRACEKIT_PYTHON -m tracekit` if
57
62
  set, else a pip-installed `tracekit` on PATH, else the Python bundled in this platform's
@@ -127,7 +132,8 @@ applies only when the signer cannot be reached at the decision; a refusal, or a
127
132
  never lets the call run. Recording a finished call never throws and never changes its result (a failure is a
128
133
  `TracekitWarning`). The frameworks are optional peer dependencies: the adapters import none of them, and the client
129
134
  keeps no runtime dependencies. No adapter wraps a provider client, so the SDKs' own `APIPromise` (`.withResponse()`)
130
- and streams (`messages.stream()`, `streamText`) work as without Tracekit. Offline examples: `examples/v2_*.mjs`.
135
+ and streams (`messages.stream()`, `streamText`) work as without Tracekit. Offline examples: `examples/v2_*.mjs`, and
136
+ [a Mastra workflow](examples/mastra/) that suspends on a held call and resumes with its approval id.
131
137
 
132
138
  - **A server: a run per conversation.** Register a run per conversation and make it current around each request with
133
139
  `withRun(run, () => runner.run(...))`: every adapter decides the calls made inside it in that run (its complete and
@@ -1,8 +1,15 @@
1
1
  import { type RunHandle } from "../client.js";
2
2
  export declare const HOOK_TIMEOUT_S = 600;
3
3
  export declare const APPROVAL_WAIT_MS = 540000;
4
- /** The `hooks` option of `query()`. To add hooks of your own, extend the lists. */
5
- export declare function tracekitHooks(run: RunHandle): {
4
+ /** The `hooks` option of `query()`. `mcpServers`: the option given `query()`, when it holds a tool executor's server
5
+ * under SERVER; `executorActions`: the actions that server serves (executorActions()). To add hooks of your own,
6
+ * extend the lists. */
7
+ export declare function tracekitHooks(run: RunHandle, { mcpServers, executorActions }?: {
8
+ mcpServers?: Record<string, any>;
9
+ executorActions?: {
10
+ name: string;
11
+ }[];
12
+ }): {
6
13
  PreToolUse: {
7
14
  hooks: ((inp: any, toolUseID?: string) => Promise<{
8
15
  hookSpecificOutput: {
@@ -13,9 +13,12 @@
13
13
  * gets as the tool's error result, and the session goes on. `ask` holds the call in the hook until a person decides in
14
14
  * the signer, for at most APPROVAL_WAIT_MS, below the hook's own timeout (HOOK_TIMEOUT_S, set on the matcher); a call
15
15
  * not approved by then is blocked. An approval with a T2 executor runs the signer's copy of the arguments (the hook's
16
- * `updatedInput`). PostToolUse and PostToolUseFailure complete the call; SessionEnd closes the run. The tools of an MCP
17
- * server named SERVER (`tracekit-executor`), whose handlers call a tool executor, are left to the executor.
18
- * The tools run in the CLI subprocess, so the signer's coding packs apply to them.
16
+ * `updatedInput`). PostToolUse and PostToolUseFailure complete the call; SessionEnd closes the run. The tools of the
17
+ * MCP server under SERVER (`tracekit-executor`), whose handlers call a tool executor, are left to the executor, by
18
+ * the exact names of the `executorActions` the app hands the hooks, when the `mcpServers` it also hands them (those it
19
+ * gives `query()`) hold that server in-process (`type: "sdk"`, from createSdkMcpServer): the CLI connects it in place
20
+ * of a project .mcp.json server of the same name, and the hooks gate every other tool. The tools run in the CLI
21
+ * subprocess, so the signer's coding packs apply to them.
19
22
  */
20
23
  import { randomUUID } from "node:crypto";
21
24
  import { RPCError, SignerUnavailable } from "../client.js";
@@ -25,14 +28,20 @@ import { BLOCKED, Gate, failure, warn } from "./gate.js";
25
28
  export const HOOK_TIMEOUT_S = 600; // the SDK's default (60 s) is too short to wait for a person
26
29
  export const APPROVAL_WAIT_MS = 540_000; // below HOOK_TIMEOUT_S, so the hook answers before the CLI gives up on it
27
30
  const deny = (why) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: why } });
28
- /** The `hooks` option of `query()`. To add hooks of your own, extend the lists. */
29
- export function tracekitHooks(run) {
31
+ /** The `hooks` option of `query()`. `mcpServers`: the option given `query()`, when it holds a tool executor's server
32
+ * under SERVER; `executorActions`: the actions that server serves (executorActions()). To add hooks of your own,
33
+ * extend the lists. */
34
+ export function tracekitHooks(run, { mcpServers, executorActions = [] } = {}) {
30
35
  const gate = new Gate(run);
36
+ // the exact tool names of the app's in-process executor server: what the CLI routes to it, never a tool of a server
37
+ // a project file names (a key like `tracekit-executor__x` included)
38
+ const executor = (tool) => mcpServers?.[SERVER]?.type === "sdk" && mcpServers[SERVER].instance != null
39
+ && executorActions.some((a) => tool === `mcp__${SERVER}__${a.name}`);
31
40
  async function pre(inp, toolUseID) {
32
41
  const id = inp.tool_use_id ?? toolUseID;
33
42
  if (!id)
34
43
  return deny(BLOCKED + "the hook got no tool_use_id"); // never defaulted: a result could not be bound to its decision
35
- if (String(inp.tool_name ?? "").startsWith(`mcp__${SERVER}__`))
44
+ if (executor(String(inp.tool_name ?? "")))
36
45
  return {}; // the executor decides and records it (T2)
37
46
  const why = await gate.admit(id, inp.tool_name ?? "?", inp.tool_input, { waitMs: APPROVAL_WAIT_MS });
38
47
  if (why !== null)
@@ -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
- for (const a of approvals)
39
- if (!states.has(a.tool_call_id))
40
- states.set(a.tool_call_id, a.state);
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 {
@@ -33,7 +33,7 @@ declare class Conn {
33
33
  send(frame: Frame): Promise<Frame>;
34
34
  }
35
35
  /** 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<{
36
+ export declare function connect(path: string, token?: string, timeoutMs?: number): Promise<{
37
37
  conn: Conn;
38
38
  hello: Frame;
39
39
  }>;
@@ -136,6 +136,11 @@ export declare class RunHandle {
136
136
  approvalRequest(toolCallId: string, fields?: Frame): Promise<Frame>;
137
137
  /** Waits up to `timeoutMs` (signer cap 300 s) for a decision, on a connection of its own. */
138
138
  approvalWait(approvalId: string, timeoutMs?: number): Promise<Frame>;
139
+ /** Call right before running a call that was not denied: `{ ok: true }` when it may run now. `args` as for `decide`;
140
+ * `approvalIdHint` is the approval id the framework saved, if any. Never rejects: any failure (a signer that can't be
141
+ * reached, is incompatible or refuses) is `{ ok: false, reason }` (once decided there is no fail mode: the call
142
+ * doesn't run). */
143
+ approvalConsume(toolCallId: string, tool: string, args: unknown, approvalIdHint?: string, fields?: Frame): Promise<Frame>;
139
144
  /** Records content that entered the run other than as a tool result (a mail, a ticket, a page the app fetched) for
140
145
  * the signer's provenance index; the task or user prompt goes in with trust "trusted". Only its commitment is recorded. */
141
146
  observe(value: unknown, source: string, trust?: "trusted" | "untrusted", fields?: Frame): Promise<Frame>;
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, $TRACEKIT_SIGNER_CERT/_KEY a client
13
- * certificate for mTLS, $TRACEKIT_SIGNER_CA the signer's CA). In system mode the signer is the one the root-owned
14
- * /etc/tracekit/client.json names, and a $TRACEKIT_SIGNER naming another is refused. Without either, the same-user dev
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
- * The client writes nothing to disk.
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,10 +40,13 @@ 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";
43
47
  }
48
+ class TimeoutUnavailable extends SignerUnavailable {
49
+ }
44
50
  /** The signer answered but does not speak this client's protocol version. It is left running. */
45
51
  export class Incompatible extends Error {
46
52
  older;
@@ -64,6 +70,19 @@ export class RPCError extends Error {
64
70
  }
65
71
  class ConnectionLost extends Error {
66
72
  }
73
+ /** Milliseconds to wait before sending a call of `schema` again after its `tries`th try was refused with `e`; null: not
74
+ * again. Only an event call (one with a client_seq): the signer refuses a client_seq it already recorded before it
75
+ * writes anything, even after a restart or a write whose outcome it couldn't tell, so a retry is recorded once or
76
+ * refused (then the call rejects with that `unavailable`, as without a retry); any other call's request_id is
77
+ * remembered in memory only (tracekit/sdk/client.py _retry_wait). A quota_exceeded without retry_after_ms is a size
78
+ * limit the same request never fits. */
79
+ function retryWait(schema, e, tries) {
80
+ const limited = e.code === "quota_exceeded" && typeof e.retry_after_ms === "number";
81
+ if (!("client_seq" in schema.properties) || !(limited || e.code === "unavailable"))
82
+ return null;
83
+ const backoff = Math.min(BACKOFF_CAP_MS, BACKOFF_MS * 2 ** (tries - 1)) * (0.5 + Math.random() / 2); // jitter
84
+ return Math.max(typeof e.retry_after_ms === "number" ? e.retry_after_ms : 0, backoff);
85
+ }
67
86
  const newId = () => randomUUID().replaceAll("-", "");
68
87
  const hmac = (token, label, nonce) => createHmac("sha256", token).update(`${label}\n${nonce}`).digest("hex");
69
88
  function warn(message) {
@@ -74,7 +93,7 @@ function withTimeout(p, ms, onTimeout) {
74
93
  const t = new Promise((_, reject) => {
75
94
  timer = setTimeout(() => {
76
95
  onTimeout();
77
- reject(new SignerUnavailable(`no answer from the signer within ${ms / 1000}s`));
96
+ reject(new TimeoutUnavailable(`no answer from the signer within ${ms / 1000}s`));
78
97
  }, ms);
79
98
  });
80
99
  return Promise.race([p, t]).finally(() => clearTimeout(timer));
@@ -130,9 +149,9 @@ class Conn {
130
149
  });
131
150
  }
132
151
  }
133
- function open(sock) {
152
+ function open(sock, timeoutMs = CONNECT_TIMEOUT_MS) {
134
153
  return new Promise((resolve, reject) => {
135
- sock.setTimeout(CONNECT_TIMEOUT_MS, () => sock.destroy(new Error("connect timed out")));
154
+ sock.setTimeout(timeoutMs, () => sock.destroy(new Error("connect timed out")));
136
155
  sock.once("connect", () => {
137
156
  sock.setTimeout(0);
138
157
  resolve(sock);
@@ -148,7 +167,8 @@ function check(hello, where) {
148
167
  "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
168
  }
150
169
  /** 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) {
170
+ export async function connect(path, token, timeoutMs = CONNECT_TIMEOUT_MS) {
171
+ const deadline = Date.now() + timeoutMs, leftMs = () => Math.max(deadline - Date.now(), 1);
152
172
  let conn, hello;
153
173
  try {
154
174
  if (path.startsWith("tcp://")) {
@@ -158,10 +178,10 @@ export async function connect(path, token) {
158
178
  token ||= process.env.TRACEKIT_SIGNER_TOKEN;
159
179
  if (!token)
160
180
  throw new SignerUnavailable(`${path}: tcp:// signers need TRACEKIT_SIGNER_TOKEN`);
161
- conn = new Conn(await open(createConnection({ host, port: Number(hostPort.slice(k + 1)) })));
181
+ conn = new Conn(await open(createConnection({ host, port: Number(hostPort.slice(k + 1)) }), leftMs()));
162
182
  // the signer proves it holds the token over our nonce before we prove it over its own (transport/tcp_dev.py)
163
183
  const nonce = randomBytes(16).toString("hex");
164
- const reply = await withTimeout(conn.send({ method: "hello", nonce }), CONNECT_TIMEOUT_MS, () => conn.sock.destroy());
184
+ const reply = await withTimeout(conn.send({ method: "hello", nonce }), leftMs(), () => conn.sock.destroy());
165
185
  const proof = Buffer.from(String(reply.proof)), want = Buffer.from(hmac(token, "signer", nonce));
166
186
  if (proof.length !== want.length || !timingSafeEqual(proof, want))
167
187
  throw new Error("dev token proof mismatch");
@@ -170,19 +190,20 @@ export async function connect(path, token) {
170
190
  conn.write({ proof: hmac(token, "client", reply.nonce) });
171
191
  }
172
192
  else if (process.platform !== "win32") {
173
- conn = new Conn(await open(createConnection(path)));
193
+ conn = new Conn(await open(createConnection(path), leftMs()));
174
194
  }
175
195
  else {
176
196
  throw new SignerUnavailable(`this platform has no Unix sockets: name the signer tcp://host:port, not ${path}`);
177
197
  }
178
198
  const c = conn;
179
- hello = await withTimeout(c.send({ method: "hello" }), CONNECT_TIMEOUT_MS, () => c.sock.destroy());
199
+ hello = await withTimeout(c.send({ method: "hello" }), leftMs(), () => c.sock.destroy());
180
200
  }
181
201
  catch (e) {
182
202
  conn?.sock.destroy();
183
203
  if (e instanceof SignerUnavailable && !conn)
184
204
  throw e;
185
- throw new SignerUnavailable(`no signer answering at ${path}: ${e.message}`);
205
+ const msg = `no signer answering at ${path}: ${e.message}`;
206
+ throw e instanceof TimeoutUnavailable && timeoutMs < CONNECT_TIMEOUT_MS ? new TimeoutUnavailable(msg) : new SignerUnavailable(msg);
186
207
  }
187
208
  try {
188
209
  check(hello, path);
@@ -288,18 +309,24 @@ class Https {
288
309
  this.agent = new Agent({ keepAlive: true, ca: file(env.TRACEKIT_SIGNER_CA), cert: file(cert),
289
310
  key: cert ? file(env.TRACEKIT_SIGNER_KEY || cert) : undefined });
290
311
  }
291
- /** The answer frame; ConnectionLost when the request may not have arrived, SignerUnavailable on a timeout. */
312
+ /** The answer frame, read from the body whatever the HTTP status. The client doesn't ask for error statuses
313
+ * (Tracekit-Errors), so a proxy in front sees 200 for a refusal and acts on none (no retry of a 503, no host ejected).
314
+ * ConnectionLost when the request may not have arrived, SignerUnavailable on a timeout. */
292
315
  post(frame, timeoutMs) {
293
316
  const body = JSON.stringify(frame), tokenFile = process.env.TRACEKIT_SIGNER_TOKEN_FILE;
317
+ const apiKey = process.env.TRACEKIT_API_KEY?.trim();
294
318
  const headers = { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) };
295
- if (tokenFile) {
319
+ if (tokenFile) { // wins over an API key: it is re-read per call, so a rotated token is picked up
296
320
  try {
297
- headers.Authorization = "Bearer " + readFileSync(tokenFile, "utf8").trim(); // re-read: a rotated token is picked up
321
+ headers.Authorization = "Bearer " + readFileSync(tokenFile, "utf8").trim();
298
322
  }
299
323
  catch (e) {
300
324
  throw new SignerUnavailable(`cannot read the signer token file: ${e.message}`);
301
325
  }
302
326
  }
327
+ else if (apiKey) {
328
+ headers.Authorization = "Bearer " + apiKey;
329
+ }
303
330
  return new Promise((resolve, reject) => {
304
331
  const req = request(routeUrl(this.url, frame), { method: "POST", agent: this.agent, headers, timeout: timeoutMs }, (res) => {
305
332
  let data = "";
@@ -319,7 +346,7 @@ class Https {
319
346
  });
320
347
  });
321
348
  req.on("timeout", () => {
322
- reject(new SignerUnavailable(`no answer from the signer within ${timeoutMs / 1000}s`));
349
+ reject(new TimeoutUnavailable(`no answer from the signer within ${timeoutMs / 1000}s`));
323
350
  req.destroy();
324
351
  });
325
352
  req.on("error", () => reject(new ConnectionLost()));
@@ -327,6 +354,7 @@ class Https {
327
354
  });
328
355
  }
329
356
  async rpc(frame, timeoutMs) {
357
+ const deadline = Date.now() + timeoutMs;
330
358
  if (!this.hello) {
331
359
  const hello = await this.post({ method: "hello" }, timeoutMs);
332
360
  if (hello.error)
@@ -334,7 +362,10 @@ class Https {
334
362
  check(hello, this.url.origin);
335
363
  this.hello = hello;
336
364
  }
337
- return this.post(frame, timeoutMs);
365
+ const rem = deadline - Date.now();
366
+ if (rem <= 0)
367
+ throw new TimeoutUnavailable(`no answer from the signer within ${timeoutMs / 1000}s`);
368
+ return this.post(frame, rem);
338
369
  }
339
370
  }
340
371
  /** Methods take the request object of an RPC and return its response, or reject with RPCError (a refusal),
@@ -426,9 +457,15 @@ export class Client {
426
457
  throw e;
427
458
  }
428
459
  }
460
+ // tries: the signer's refusals of an event call (retryWait), counted apart from lost connections
461
+ let losses = 0, tries = 0, outage = null;
429
462
  try {
430
- for (let i = 0; i < RETRIES; i++) {
431
- const left = Math.max(deadline - Date.now(), 1);
463
+ while (losses < RETRIES) {
464
+ const left = deadline - Date.now();
465
+ if (left <= 0) {
466
+ frame();
467
+ throw new SignerUnavailable(`no answer from the signer within ${timeout / 1000}s`);
468
+ }
432
469
  let reply;
433
470
  try {
434
471
  if (this.https) {
@@ -439,22 +476,40 @@ export class Client {
439
476
  reply = await this.poll(frame(), left);
440
477
  }
441
478
  else {
442
- const conn = await this.connection();
443
- reply = await withTimeout(conn.send(frame()), left, () => conn.sock.destroy());
479
+ const conn = await withTimeout(this.connection(), left, () => { });
480
+ const rem = deadline - Date.now();
481
+ if (rem <= 0) {
482
+ frame();
483
+ throw new SignerUnavailable(`no answer from the signer within ${timeout / 1000}s`);
484
+ }
485
+ reply = await withTimeout(conn.send(frame()), rem, () => conn.sock.destroy());
444
486
  }
445
487
  }
446
488
  catch (e) {
447
- if (e instanceof ConnectionLost)
489
+ if (e instanceof ConnectionLost) {
490
+ losses++;
448
491
  continue;
492
+ }
449
493
  if (e instanceof SignerUnavailable)
450
494
  frame(); // used up: the signer's client_counter_gap covers a call it never saw
495
+ if (e instanceof TimeoutUnavailable)
496
+ throw new SignerUnavailable(`no answer from the signer within ${timeout / 1000}s`);
451
497
  throw e;
452
498
  }
453
499
  if (reply.error) {
454
- const e = reply.error;
500
+ const e = reply.error, err = new RPCError(e.code, e.message ?? "", e.retry_after_ms);
455
501
  if (["run_closed", "unknown_run"].includes(e.code))
456
502
  this.seqs.delete(req.run_id); // no more events for it
457
- throw new RPCError(e.code, e.message ?? "", e.retry_after_ms);
503
+ // the try the signer answered unavailable was written after all: that answer stands (the caller's outage path)
504
+ if (outage && e.code === "client_seq_reused")
505
+ throw outage;
506
+ const wait = retryWait(schema, e, ++tries);
507
+ if (wait === null || tries === RETRIES || Date.now() + wait >= deadline)
508
+ throw err;
509
+ if (e.code === "unavailable")
510
+ outage = err;
511
+ await sleep(wait); // then the same request: its request_id, stream and client_seq
512
+ continue;
458
513
  }
459
514
  if (method === "close_run")
460
515
  this.seqs.delete(req.run_id);
@@ -489,9 +544,13 @@ export class Client {
489
544
  }
490
545
  /** One request on a connection of its own, closed after the answer. */
491
546
  async poll(frame, timeout) {
492
- const { conn } = await this.dial();
547
+ const deadline = Date.now() + timeout;
548
+ const { conn } = await this.dial(Math.min(CONNECT_TIMEOUT_MS, timeout));
493
549
  try {
494
- return await withTimeout(conn.send(frame), timeout, () => { });
550
+ const rem = deadline - Date.now();
551
+ if (rem <= 0)
552
+ throw new TimeoutUnavailable(`no answer from the signer within ${timeout / 1000}s`);
553
+ return await withTimeout(conn.send(frame), rem, () => { });
495
554
  }
496
555
  finally {
497
556
  conn.sock.destroy();
@@ -511,10 +570,10 @@ export class Client {
511
570
  }
512
571
  return this.conn;
513
572
  }
514
- async dial() {
573
+ async dial(timeoutMs = CONNECT_TIMEOUT_MS) {
515
574
  let c;
516
575
  if (this.signer) {
517
- c = await connect(this.signer);
576
+ c = await connect(this.signer, undefined, Math.min(CONNECT_TIMEOUT_MS, timeoutMs));
518
577
  }
519
578
  else {
520
579
  const d = devRuntimeDir();
@@ -616,7 +675,8 @@ export class RunHandle {
616
675
  if (closed !== this.runId)
617
676
  return Promise.resolve(); // renewed already
618
677
  this.renewing ??= (async () => {
619
- const agent = { agent: { name: this.renewAs } };
678
+ // a later run of the process's agent, whose model may still hold what the closed run read
679
+ const agent = { agent: { name: this.renewAs }, continues: true };
620
680
  let r;
621
681
  try { // linked to the closed run while it is still closing
622
682
  r = await this.client.call("register_run", { ...agent, parent: { run_id: this.runId, run_token: this.runToken } });
@@ -677,6 +737,20 @@ export class RunHandle {
677
737
  approvalWait(approvalId, timeoutMs) {
678
738
  return this.call("approval_wait", { approval_id: approvalId, ...(timeoutMs === undefined ? {} : { timeout_ms: timeoutMs }) });
679
739
  }
740
+ /** Call right before running a call that was not denied: `{ ok: true }` when it may run now. `args` as for `decide`;
741
+ * `approvalIdHint` is the approval id the framework saved, if any. Never rejects: any failure (a signer that can't be
742
+ * reached, is incompatible or refuses) is `{ ok: false, reason }` (once decided there is no fail mode: the call
743
+ * doesn't run). */
744
+ async approvalConsume(toolCallId, tool, args, approvalIdHint, fields = {}) {
745
+ try {
746
+ return await this.call("approval_consume", { tool_call_id: toolCallId, tool, args, args_source: typeof args === "string" ? "raw" : "parsed",
747
+ ...(approvalIdHint ? { approval_id_hint: approvalIdHint } : {}), ...fields });
748
+ }
749
+ catch (e) {
750
+ warn(`tracekit: ${tool} is blocked: approval_consume failed: ${e.message}`);
751
+ return { ok: false, rule_ids: [], reason: `approval_consume failed: ${e.message}`.slice(0, 1024) };
752
+ }
753
+ }
680
754
  /** Records content that entered the run other than as a tool result (a mail, a ticket, a page the app fetched) for
681
755
  * the signer's provenance index; the task or user prompt goes in with trust "trusted". Only its commitment is recorded. */
682
756
  observe(value, source, trust = "untrusted", fields = {}) {
@@ -20,7 +20,8 @@ export declare class ExecutorRefused extends Error {
20
20
  }
21
21
  /** Set on the tools built here: the Tracekit adapters don't gate them. */
22
22
  export declare const EXECUTOR: unique symbol;
23
- /** The Claude Agent SDK hooks leave the tools of an MCP server of this name (mcp__tracekit-executor__<action>) alone. */
23
+ /** The Claude Agent SDK hooks leave the actions' tools of the in-process MCP server under this key
24
+ * (mcp__tracekit-executor__<action>) alone when the app hands them its `mcpServers` and `executorActions`. */
24
25
  export declare const SERVER = "tracekit-executor";
25
26
  export type Action = {
26
27
  name: string;
@@ -2,7 +2,8 @@ export class ExecutorRefused extends Error {
2
2
  }
3
3
  /** Set on the tools built here: the Tracekit adapters don't gate them. */
4
4
  export const EXECUTOR = Symbol.for("tracekit.executor");
5
- /** The Claude Agent SDK hooks leave the tools of an MCP server of this name (mcp__tracekit-executor__<action>) alone. */
5
+ /** The Claude Agent SDK hooks leave the actions' tools of the in-process MCP server under this key
6
+ * (mcp__tracekit-executor__<action>) alone when the app hands them its `mcpServers` and `executorActions`. */
6
7
  export const SERVER = "tracekit-executor";
7
8
  /** Why `url` may not receive the run token and the agent's credential, or null: https, or plain http to loopback. */
8
9
  function remoteUrlError(url) {
@@ -1,3 +1,3 @@
1
1
  import type { Schema } from "./validate.js";
2
- export declare const RPC_VERSION = 20;
2
+ export declare const RPC_VERSION = 26;
3
3
  export declare const REQUESTS: Record<string, Schema>;