@cygnuxlabs/tracekit 1.7.2 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -64,11 +64,17 @@ await client.close(); // waits for what is i
64
64
  same command.
65
65
  - **Protocol:** `hello` first; a signer that does not speak this client's RPC version is refused with `Incompatible`.
66
66
  Requests are validated against the RPC schemas before they are sent, pipelined on one connection and answered in
67
- order; a call whose connection drops is resent with the same `request_id`. Each handle's events carry the client's
68
- `stream` and a `client_seq` per run.
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.
69
71
  - **Fail modes:** only when the signer cannot be reached does `decide` return the run's fail mode for the tool class
70
72
  (`fields.tool_class_hint`, from `register_run`'s `fail_modes`, default closed) with `unavailable: true`. A refusal
71
73
  from the signer rejects with `RPCError`, never an allow.
74
+ - **Transfers (experimental):** `await run.transfer(sender, receiver, payload, modality, { projector, measured, keep })`
75
+ records and gates a hand-off of a model's internal state between agents before it happens, as Python's
76
+ `RunHandle.transfer` does ([latent transfers](../../docs/c2c.md#runtransfer)). It resolves the decision with `ok`: hand
77
+ the payload over only when `ok` is true. With the signer unreachable it is not ok, whatever the run's fail modes.
72
78
  - **Serverless:** `client.waitUntil(promise)` and `await client.flush()` before the host freezes the process.
73
79
  - `withRun(run, fn)` makes `run` the `currentRun()` of everything `fn` awaits (AsyncLocalStorage).
74
80
  - `argsDigest(tool, args)`, `canonicalize`, `strictParse`: JCS (RFC 8785) and the strict parser, byte-identical to
@@ -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. */
@@ -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 is a warning. Defaults decision_id and args_digest to
134
- * those of the last `decide` for this tool call. */
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. */
@@ -141,6 +148,21 @@ export declare class RunHandle {
141
148
  * reached, is incompatible or refuses) is `{ ok: false, reason }` (once decided there is no fail mode: the call
142
149
  * doesn't run). */
143
150
  approvalConsume(toolCallId: string, tool: string, args: unknown, approvalIdHint?: string, fields?: Frame): Promise<Frame>;
151
+ /** Experimental, as Python's `RunHandle.transfer` (docs/c2c.md#runtransfer): records and gates a transfer from `sender`
152
+ * to `receiver` before it happens, as the tool a2a:transfer. `payload` is hashed here: the signer gets its size and
153
+ * sha256 digest, never the payload. `measured` adds fields the caller computed itself and may not reuse the transfer's
154
+ * own (it throws). An `ask` waits up to 300 s for a person. Fails closed: with the signer unreachable the transfer
155
+ * may not happen, whatever the run's fail modes. Resolves the decision with `ok`, whether the transfer may happen now
156
+ * (and `reason` when it may not for one the signer gave); one that may is recorded as made before this resolves.
157
+ * `keep`: the payload (hex) goes in the result, for a signer keeping content. */
158
+ transfer(sender: string, receiver: string, payload: string | Uint8Array, modality: string, { projector, measured, keep }?: {
159
+ projector?: string;
160
+ measured?: Frame;
161
+ keep?: boolean;
162
+ }): Promise<Decision & {
163
+ ok: boolean;
164
+ reason?: string;
165
+ }>;
144
166
  /** Records content that entered the run other than as a tool result (a mail, a ticket, a page the app fetched) for
145
167
  * the signer's provenance index; the task or user prompt goes in with trust "trusted". Only its commitment is recorded. */
146
168
  observe(value: unknown, source: string, trust?: "trusted" | "untrusted", fields?: Frame): Promise<Frame>;
package/dist/v2/client.js CHANGED
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { AsyncLocalStorage } from "node:async_hooks";
25
25
  import { execFile } from "node:child_process";
26
- import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
26
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
27
27
  import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
28
28
  import { Agent, request } from "node:https";
29
29
  import { createConnection } from "node:net";
@@ -32,7 +32,7 @@ import { basename, extname, join } from "node:path";
32
32
  import { setTimeout as sleep } from "node:timers/promises";
33
33
  import { TracekitAgents } from "./adapters/openai-agents.js";
34
34
  import { tracekitAI } from "./adapters/vercel-ai.js";
35
- import { argsDigest } from "./jcs.js";
35
+ import { argsDigest, canonicalize } from "./jcs.js";
36
36
  import { INSTALL_HINT, signerCommand, signerEnv } from "./launcher.js";
37
37
  import { REQUESTS, RPC_VERSION } from "./rpc_schema.js";
38
38
  import { validate } from "./validate.js";
@@ -44,8 +44,10 @@ const RETRIES = 3; // tries of a call while its connection is lost; apart, while
44
44
  const BACKOFF_MS = 100, BACKOFF_CAP_MS = 2000; // the wait before an event call's second try, doubled for each next
45
45
  export class SignerUnavailable extends Error {
46
46
  name = "SignerUnavailable";
47
+ recorded = false; // a write call's error: see Client
47
48
  }
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"
49
51
  }
50
52
  /** The signer answered but does not speak this client's protocol version. It is left running. */
51
53
  export class Incompatible extends Error {
@@ -62,13 +64,29 @@ export class RPCError extends Error {
62
64
  code;
63
65
  retryAfterMs;
64
66
  name = "RPCError";
67
+ recorded = false; // a write call's error: see Client
65
68
  constructor(code, message, retryAfterMs) {
66
69
  super(`${code}: ${message}`);
67
70
  this.code = code;
68
71
  this.retryAfterMs = retryAfterMs;
69
72
  }
70
73
  }
74
+ /** The request may not have arrived. `sent` false: it never connected, so nothing went out. */
71
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;
72
90
  }
73
91
  /** Milliseconds to wait before sending a call of `schema` again after its `tries`th try was refused with `e`; null: not
74
92
  * again. Only an event call (one with a client_seq): the signer refuses a client_seq it already recorded before it
@@ -141,7 +159,7 @@ class Conn {
141
159
  send(frame) {
142
160
  return new Promise((resolve, reject) => {
143
161
  if (this.sock.destroyed)
144
- return reject(new ConnectionLost());
162
+ return reject(new ConnectionLost(false)); // nothing was written
145
163
  const line = JSON.stringify(frame) + "\n"; // may throw: before anything waits for an answer
146
164
  this.pending.push({ resolve, reject });
147
165
  this.sock.ref();
@@ -311,7 +329,8 @@ class Https {
311
329
  }
312
330
  /** The answer frame, read from the body whatever the HTTP status. The client doesn't ask for error statuses
313
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).
314
- * ConnectionLost when the request may not have arrived, SignerUnavailable on a timeout. */
332
+ * ConnectionLost when the request may not have arrived, SignerUnavailable on a timeout (`recorded` false when it timed
333
+ * out connecting: nothing went out). */
315
334
  post(frame, timeoutMs) {
316
335
  const body = JSON.stringify(frame), tokenFile = process.env.TRACEKIT_SIGNER_TOKEN_FILE;
317
336
  const apiKey = process.env.TRACEKIT_API_KEY?.trim();
@@ -345,18 +364,35 @@ class Https {
345
364
  }
346
365
  });
347
366
  });
367
+ let connected = false; // nothing goes out until it connects (and the TLS handshake is done)
348
368
  req.on("timeout", () => {
349
- reject(new TimeoutUnavailable(`no answer from the signer within ${timeoutMs / 1000}s`));
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
+ }
350
376
  req.destroy();
351
377
  });
352
- req.on("error", () => reject(new ConnectionLost()));
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)));
353
385
  req.end(body);
354
386
  });
355
387
  }
356
388
  async rpc(frame, timeoutMs) {
357
389
  const deadline = Date.now() + timeoutMs;
358
390
  if (!this.hello) {
359
- 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
+ });
360
396
  if (hello.error)
361
397
  throw new RPCError(hello.error.code, hello.error.message ?? "");
362
398
  check(hello, this.url.origin);
@@ -369,7 +405,9 @@ class Https {
369
405
  }
370
406
  }
371
407
  /** Methods take the request object of an RPC and return its response, or reject with RPCError (a refusal),
372
- * 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). */
373
411
  export class Client {
374
412
  signer;
375
413
  stream = newId();
@@ -446,7 +484,7 @@ export class Client {
446
484
  }
447
485
  return { method, ...req };
448
486
  };
449
- 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;
450
488
  let release = () => { };
451
489
  if (claim) {
452
490
  try {
@@ -454,11 +492,13 @@ export class Client {
454
492
  }
455
493
  catch (e) {
456
494
  frame(); // used up: the signer's client_counter_gap covers a call it never saw
495
+ e.recorded = false; // it was not sent
457
496
  throw e;
458
497
  }
459
498
  }
460
- // tries: the signer's refusals of an event call (retryWait), counted apart from lost connections
461
- let losses = 0, tries = 0, outage = null;
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;
462
502
  try {
463
503
  while (losses < RETRIES) {
464
504
  const left = deadline - Date.now();
@@ -482,27 +522,40 @@ export class Client {
482
522
  frame();
483
523
  throw new SignerUnavailable(`no answer from the signer within ${timeout / 1000}s`);
484
524
  }
485
- reply = await withTimeout(conn.send(frame()), rem, () => conn.sock.destroy());
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
+ });
486
530
  }
487
531
  }
488
532
  catch (e) {
489
533
  if (e instanceof ConnectionLost) {
490
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);
491
537
  continue;
492
538
  }
493
539
  if (e instanceof SignerUnavailable)
494
540
  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`);
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
+ }
497
546
  throw e;
498
547
  }
499
548
  if (reply.error) {
500
549
  const e = reply.error, err = new RPCError(e.code, e.message ?? "", e.retry_after_ms);
501
550
  if (["run_closed", "unknown_run"].includes(e.code))
502
551
  this.seqs.delete(req.run_id); // no more events for it
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;
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";
506
559
  const wait = retryWait(schema, e, ++tries);
507
560
  if (wait === null || tries === RETRIES || Date.now() + wait >= deadline)
508
561
  throw err;
@@ -517,6 +570,15 @@ export class Client {
517
570
  }
518
571
  throw new SignerUnavailable(`lost the connection to the signer ${RETRIES} times`);
519
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
+ }
520
582
  finally {
521
583
  release();
522
584
  }
@@ -609,6 +671,9 @@ export function failOpen(failModes, toolClass) {
609
671
  const NEW_WORK = new Set(["decide", "model_event", "observe", "state_write"]); // to the current run
610
672
  const BY_CALL = new Set(["complete", "approval_request", "approval_consume"]); // to the run the call was decided in
611
673
  const KEEP = 4096; // tool calls and approvals whose run is remembered
674
+ const TRANSFER = "a2a:transfer"; // the tool RunHandle.transfer decides
675
+ const TRANSFER_FIELDS = ["sender", "receiver", "modality", "projector", "size", "digest", "claimed", "measured"];
676
+ const MAX_LINE = 1 << 20; // bytes of one transport frame (MAX_LINE in tracekit/signer/quotas.py)
612
677
  function remember(m, k, v) {
613
678
  m.delete(k);
614
679
  m.set(k, v);
@@ -702,8 +767,9 @@ export class RunHandle {
702
767
  if (!(e instanceof SignerUnavailable))
703
768
  throw e;
704
769
  const open = failOpen(this.failModes, fields.tool_class_hint);
705
- warn(`tracekit: ${tool} ${open ? "runs unrecorded (fail open)" : "is denied (fail closed)"}: ${e.message}`);
706
- return { decision: open ? "allow" : "deny", rule_ids: [], reason: `signer unavailable: ${e.message}`.slice(0, 1024), unavailable: true };
770
+ const why = e.message.replace(UNKNOWN, ""); // the outage path, worded as before: `recorded` stays on the error
771
+ warn(`tracekit: ${tool} ${open ? "runs unrecorded (fail open)" : "is denied (fail closed)"}: ${why}`);
772
+ return { decision: open ? "allow" : "deny", rule_ids: [], reason: `signer unavailable: ${why}`.slice(0, 1024), unavailable: true };
707
773
  }
708
774
  try { // a denied call is never completed: nothing to remember; others are capped, as `at` is
709
775
  if (d.decision !== "deny")
@@ -714,8 +780,11 @@ export class RunHandle {
714
780
  }
715
781
  return d;
716
782
  }
717
- /** Never rejects: a failure to record a call that already ran is a warning. Defaults decision_id and args_digest to
718
- * those of the last `decide` for this tool call. */
783
+ /** Never rejects: a failure to record a call that already ran resolves null and warns that it was not recorded (the
784
+ * run's bundle shows the call as decided and not completed) or that it may not have been (no answer to a try that
785
+ * went out: the bundle has its tool.result or a decided_not_completed gap). A retry the signer refuses as already
786
+ * recorded (client_seq_reused) was recorded: null, no warning. Defaults decision_id and args_digest to those of the
787
+ * last `decide` for this tool call. */
719
788
  async complete(toolCallId, status = "ok", fields = {}) {
720
789
  const decided = this.decided.get(toolCallId);
721
790
  this.decided.delete(toolCallId);
@@ -723,7 +792,13 @@ export class RunHandle {
723
792
  return await this.call("complete", { tool_call_id: toolCallId, status, ...decided, ...fields });
724
793
  }
725
794
  catch (e) {
726
- warn(`tracekit: the result of ${toolCallId} was not recorded: ${e.message}`);
795
+ const recorded = e.recorded, message = e.message;
796
+ if (recorded === null)
797
+ warn(`tracekit: the result of ${toolCallId} may not have been recorded (${message.replace(UNKNOWN, "")}). Once ` +
798
+ `the run closes, its bundle has ${toolCallId}'s tool.result if it was, or a decided_not_completed gap if it wasn't.`);
799
+ else if (!recorded)
800
+ warn(`tracekit: the result of ${toolCallId} was not recorded: ${message}. Once the run closes, its bundle shows ` +
801
+ `${toolCallId} as decided and not completed.`);
727
802
  return null;
728
803
  }
729
804
  finally {
@@ -747,9 +822,54 @@ export class RunHandle {
747
822
  ...(approvalIdHint ? { approval_id_hint: approvalIdHint } : {}), ...fields });
748
823
  }
749
824
  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) };
825
+ const why = e.message.replace(UNKNOWN, ""); // handed to the model: `recorded` stays on the error
826
+ warn(`tracekit: ${tool} is blocked: approval_consume failed: ${why}`);
827
+ return { ok: false, rule_ids: [], reason: `approval_consume failed: ${why}`.slice(0, 1024) };
828
+ }
829
+ }
830
+ /** Experimental, as Python's `RunHandle.transfer` (docs/c2c.md#runtransfer): records and gates a transfer from `sender`
831
+ * to `receiver` before it happens, as the tool a2a:transfer. `payload` is hashed here: the signer gets its size and
832
+ * sha256 digest, never the payload. `measured` adds fields the caller computed itself and may not reuse the transfer's
833
+ * own (it throws). An `ask` waits up to 300 s for a person. Fails closed: with the signer unreachable the transfer
834
+ * may not happen, whatever the run's fail modes. Resolves the decision with `ok`, whether the transfer may happen now
835
+ * (and `reason` when it may not for one the signer gave); one that may is recorded as made before this resolves.
836
+ * `keep`: the payload (hex) goes in the result, for a signer keeping content. */
837
+ async transfer(sender, receiver, payload, modality, { projector, measured, keep = false } = {}) {
838
+ const data = Buffer.from(payload);
839
+ const more = measured ?? {};
840
+ const collision = TRANSFER_FIELDS.filter((k) => Object.hasOwn(more, k));
841
+ if (collision.length)
842
+ throw new Error(`measured keys replace reserved transfer fields: ${collision.sort().join(", ")}`);
843
+ const head = { sender, receiver, modality, ...(projector ? { projector } : {}) };
844
+ const args = { ...head, claimed: Object.keys(head).sort(), size: data.length, digest: `sha256:${createHash("sha256").update(data).digest("hex")}`,
845
+ // in Python's order, by code point (UTF-8 bytes): sort() alone compares UTF-16 units
846
+ ...more, measured: ["size", "digest", ...Object.keys(more)].sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b))) };
847
+ const toolCallId = `tx-${randomBytes(16).toString("hex")}`;
848
+ const d = await this.decide(toolCallId, TRANSFER, args);
849
+ if (d.unavailable || d.decision === "deny")
850
+ return { ...d, ok: false };
851
+ let hint;
852
+ if (d.decision === "ask") {
853
+ hint = (await this.approvalRequest(toolCallId)).approval_id;
854
+ const state = (await this.approvalWait(hint, 300_000)).state;
855
+ if (state !== "approved") {
856
+ if (state === "requested") // unanswered: withdrawn, so no one approves a transfer that is gone
857
+ await this.call("approval_abandon", { approval_id: hint, reason: "no answer within run.transfer's wait" });
858
+ return { ...d, ok: false, reason: `approval ${state}` };
859
+ }
860
+ }
861
+ const c = await this.approvalConsume(toolCallId, TRANSFER, args, hint);
862
+ if (c.ok) {
863
+ let kept = keep ? { payload: data.toString("hex") } : undefined;
864
+ // lean: up to a quarter frame of payload (its hex in half a frame) is kept; send it in parts, each a record of its
865
+ // own, once larger caches must be kept
866
+ if (kept && canonicalize(kept).length > MAX_LINE / 2) {
867
+ warn(`tracekit: transfer ${toolCallId} is recorded but not kept: its ${data.length} bytes are more than one frame carries (about ${MAX_LINE / 4}); keep a smaller one`);
868
+ kept = undefined;
869
+ }
870
+ await this.complete(toolCallId, "ok", kept ? { result: kept } : {});
752
871
  }
872
+ return { ...d, ok: c.ok, ...(c.reason ? { reason: c.reason } : {}) };
753
873
  }
754
874
  /** Records content that entered the run other than as a tool result (a mail, a ticket, a page the app fetched) for
755
875
  * the signer's provenance index; the task or user prompt goes in with trust "trusted". Only its commitment is recorded. */
@@ -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, so the Tracekit adapters leave them to the executor, which
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 {};
@@ -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
+ }
@@ -1,3 +1,3 @@
1
1
  import type { Schema } from "./validate.js";
2
- export declare const RPC_VERSION = 26;
2
+ export declare const RPC_VERSION = 29;
3
3
  export declare const REQUESTS: Record<string, Schema>;