@goodtiming/baton-sdk 0.6.8 → 1.0.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.6.8";
2
+ var SDK_VERSION = "ts-1.0.0";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -129,6 +129,11 @@ var ClientObservedSchema = z.object({
129
129
  info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),
130
130
  headers: z.object({ "user-agent": z.string().optional(), "x-anthropic-client": z.string().optional() }).strict().optional()
131
131
  }).strict();
132
+ var CaptureObservedSchema = z.object({
133
+ settings_version: z.number().int().min(1).optional(),
134
+ audience: z.string().optional(),
135
+ overlay: z.string().optional()
136
+ }).strict();
132
137
  var PrincipalWireSchema = z.object({
133
138
  id: z.string(),
134
139
  source: z.string(),
@@ -149,6 +154,10 @@ var envelopeShape = {
149
154
  agent_runtime: z.string().default("unknown"),
150
155
  principal: PrincipalWireSchema.nullable().default(null),
151
156
  organization: PrincipalWireSchema.nullable().default(null),
157
+ // No length rules here: zod counts UTF-16 units, SPEC §11.4 code points.
158
+ // `cleanLabels` applies them.
159
+ labels: z.array(z.string()).nullable().default(null),
160
+ capture: CaptureObservedSchema.nullable().default(null),
152
161
  transport_observed: z.string().nullable().default(null),
153
162
  session_id_origin: z.string().nullable().default(null),
154
163
  client_observed: ClientObservedSchema.nullable().default(null),
@@ -508,7 +517,8 @@ function identityScrub(value) {
508
517
  }
509
518
 
510
519
  // src/sinks.ts
511
- import { closeSync, openSync, writeSync } from "fs";
520
+ import { appendFileSync } from "fs";
521
+ import { open } from "fs/promises";
512
522
 
513
523
  // src/_text.ts
514
524
  var WHITE_SPACE = /^\p{White_Space}$/u;
@@ -648,6 +658,7 @@ function timerMsOption(given, name, fallback) {
648
658
  function shutdownBudgetMs(sink) {
649
659
  try {
650
660
  if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
661
+ if (sink instanceof QueuedSink) return shutdownBudgetMs(sink.inner);
651
662
  const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
652
663
  if (isTimerMs(budget)) return budget;
653
664
  } catch {
@@ -692,22 +703,32 @@ var FileSink = class {
692
703
  this.path = path;
693
704
  }
694
705
  path;
695
- fd = null;
706
+ file = null;
707
+ closeOnce;
708
+ /** Writes run one after another: two at once on one file can interleave. */
709
+ last = Promise.resolve();
696
710
  closed = false;
697
711
  async write(event) {
698
712
  if (this.closed) throw new SinkClosedError("FileSink is closed");
699
- this.fd ??= openSync(this.path, "a");
700
- writeSync(this.fd, JSON.stringify(event) + "\n");
713
+ const line = JSON.stringify(event) + "\n";
714
+ const written = this.last.then(async () => {
715
+ this.file ??= await open(this.path, "a");
716
+ await this.file.appendFile(line);
717
+ });
718
+ this.last = written.catch(() => void 0);
719
+ await written;
701
720
  }
702
721
  async flush() {
722
+ await this.last;
703
723
  }
704
- async aclose() {
705
- if (this.closed) return;
724
+ /** A second call waits for the first (SPEC §11.2 rule 7). */
725
+ aclose() {
706
726
  this.closed = true;
707
- if (this.fd !== null) {
708
- closeSync(this.fd);
709
- this.fd = null;
710
- }
727
+ this.closeOnce ??= this.last.then(async () => {
728
+ await this.file?.close();
729
+ this.file = null;
730
+ });
731
+ return this.closeOnce;
711
732
  }
712
733
  };
713
734
  var MultiSink = class {
@@ -740,6 +761,194 @@ var MultiSink = class {
740
761
  throw new AggregateError(errors, "MultiSink fan-out failures");
741
762
  }
742
763
  };
764
+ var QUEUE_BOUND = 1e3;
765
+ var WRITES_PER_TURN = 100;
766
+ var CLOSE_GRACE_MS = 250;
767
+ var later = (run) => {
768
+ if (typeof setImmediate === "function") setImmediate(run);
769
+ else setTimeout(run, 0);
770
+ };
771
+ var withUnwrittenEvents = /* @__PURE__ */ new Set();
772
+ var exitHooked = false;
773
+ function hookExit() {
774
+ if (exitHooked) return;
775
+ exitHooked = true;
776
+ try {
777
+ process.on("exit", () => {
778
+ try {
779
+ let unsure = 0;
780
+ for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
781
+ if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
782
+ } catch {
783
+ }
784
+ });
785
+ } catch {
786
+ }
787
+ }
788
+ function writeNow(sink, events) {
789
+ const lines = events.map((event) => JSON.stringify(event) + "\n").join("");
790
+ if (sink instanceof StdoutSink) {
791
+ const stream = sink["stream"];
792
+ if (stream !== process.stdout && stream !== process.stderr) return false;
793
+ if (!sink["closed"]) stream.write(lines);
794
+ } else if (sink instanceof FileSink) {
795
+ if (!sink["closed"]) appendFileSync(sink["path"], lines);
796
+ } else return false;
797
+ return true;
798
+ }
799
+ var QueuedSink = class {
800
+ constructor(inner) {
801
+ this.inner = inner;
802
+ }
803
+ inner;
804
+ queue = [];
805
+ closed = false;
806
+ draining = false;
807
+ /** Set when close ran out of time or the process is exiting: what was left is already handled. */
808
+ abandoned = false;
809
+ inFlight = 0;
810
+ /** A flush waits until `settled`, the events written or lost, reaches `taken` as it was. */
811
+ taken = 0;
812
+ settled = 0;
813
+ /** Writes that returned, so a dropped event does not look like progress. */
814
+ ended = 0;
815
+ /** `ended` when a flush waited its whole budget: until a write ends, later flushes return at once. */
816
+ stuckAt = null;
817
+ waiters = [];
818
+ overflowWarned = false;
819
+ failWarned = false;
820
+ copyWarned = false;
821
+ closeOnce;
822
+ get unwritten() {
823
+ return this.queue.length + this.inFlight;
824
+ }
825
+ /** Writes what waits to a `StdoutSink` or `FileSink` at once; answers how
826
+ * many events may not be written. */
827
+ handOffAtExit() {
828
+ this.abandoned = true;
829
+ const waiting = this.queue.splice(0);
830
+ let written = false;
831
+ try {
832
+ written = waiting.length === 0 || writeNow(this.inner, waiting);
833
+ } catch {
834
+ }
835
+ return this.inFlight + (written ? 0 : waiting.length);
836
+ }
837
+ async write(event) {
838
+ if (this.closed) throw new SinkClosedError("the sink is closed");
839
+ let copy;
840
+ try {
841
+ copy = JSON.parse(JSON.stringify(event));
842
+ } catch (err) {
843
+ PROCESS_DROPS.add("encode_failed");
844
+ if (!this.copyWarned) {
845
+ this.copyWarned = true;
846
+ warn(`baton: an event could not be copied and was dropped (${err?.name ?? "Error"}). Later ones are not logged.`);
847
+ }
848
+ return;
849
+ }
850
+ this.queue.push(copy);
851
+ this.taken++;
852
+ if (this.queue.length > QUEUE_BOUND) {
853
+ this.queue.shift();
854
+ this.settle();
855
+ PROCESS_DROPS.add("buffer_full");
856
+ if (!this.overflowWarned) {
857
+ this.overflowWarned = true;
858
+ warn(`baton: the sink's queue is full (${QUEUE_BOUND}); oldest events dropped. Further overflows will be silent.`);
859
+ }
860
+ }
861
+ withUnwrittenEvents.add(this);
862
+ hookExit();
863
+ if (!this.draining) {
864
+ this.draining = true;
865
+ later(() => void this.drain());
866
+ }
867
+ }
868
+ /** Waits for the events written before it, not for later ones (SPEC §11.2 rule 7). */
869
+ async flush() {
870
+ if (this.closed || this.stuckAt === this.ended) return;
871
+ const budget = shutdownBudgetMs(this.inner);
872
+ const start = performance.now();
873
+ if (await raceDeadline(this.settledUpTo(this.taken), budget) === TIMED_OUT) this.stuckAt = this.ended;
874
+ await callWithin(this.inner, "flush", Math.max(0, budget - (performance.now() - start)));
875
+ }
876
+ /** A second call waits for the first (SPEC §11.2 rule 7). */
877
+ aclose() {
878
+ this.closeOnce ??= this.close(shutdownBudgetMs(this.inner));
879
+ return this.closeOnce;
880
+ }
881
+ /** Takes events until the queue is empty, as `HttpSink` does, so an event
882
+ * recorded while close runs is not refused. */
883
+ async close(ms) {
884
+ const start = performance.now();
885
+ const deadline = start + ms - Math.min(CLOSE_GRACE_MS, ms / 2);
886
+ let timedOut = false;
887
+ while (this.settled < this.taken && !timedOut) {
888
+ timedOut = await raceDeadline(this.settledUpTo(this.taken), deadline - performance.now()) === TIMED_OUT;
889
+ }
890
+ this.closed = true;
891
+ if (timedOut) {
892
+ const unwritten = this.unwritten;
893
+ this.abandoned = true;
894
+ this.queue.length = 0;
895
+ withUnwrittenEvents.delete(this);
896
+ PROCESS_DROPS.add("unsent_at_close", unwritten);
897
+ warn(`baton: closed with ${unwritten} event(s) not yet written to the sink.`);
898
+ }
899
+ await callWithin(this.inner, "aclose", Math.max(0, ms - (performance.now() - start)));
900
+ }
901
+ async drain() {
902
+ try {
903
+ let event;
904
+ let written = 0;
905
+ while (!this.abandoned && (event = this.queue.shift()) !== void 0) {
906
+ this.inFlight = 1;
907
+ try {
908
+ await this.inner.write(event);
909
+ } catch (err) {
910
+ if (!this.abandoned) this.lose(err);
911
+ } finally {
912
+ this.inFlight = 0;
913
+ this.ended++;
914
+ this.settle();
915
+ }
916
+ if (++written % WRITES_PER_TURN === 0) await new Promise((resolve) => later(resolve));
917
+ }
918
+ } catch {
919
+ } finally {
920
+ this.draining = false;
921
+ if (this.queue.length === 0) withUnwrittenEvents.delete(this);
922
+ else if (!this.abandoned) {
923
+ this.draining = true;
924
+ later(() => void this.drain());
925
+ }
926
+ }
927
+ }
928
+ lose(err) {
929
+ if (isSinkClosed(err)) return droppedAfterClose(this);
930
+ PROCESS_DROPS.add("write_failed");
931
+ if (this.failWarned) return;
932
+ this.failWarned = true;
933
+ warn(`baton: the sink failed to write an event; it was dropped. Later failures are not logged: ${printable(err)}`);
934
+ }
935
+ settle() {
936
+ this.settled++;
937
+ this.waiters = this.waiters.filter((w) => {
938
+ if (w.upTo > this.settled) return true;
939
+ w.resolve();
940
+ return false;
941
+ });
942
+ }
943
+ settledUpTo(upTo) {
944
+ if (this.settled >= upTo) return Promise.resolve();
945
+ return new Promise((resolve) => this.waiters.push({ upTo, resolve }));
946
+ }
947
+ };
948
+ function offTheCall(sink) {
949
+ if (sink instanceof QueuedSink || sink instanceof HttpSink && sink.write === HttpSink.prototype.write) return sink;
950
+ return new QueuedSink(sink);
951
+ }
743
952
  var BATCH_OPEN = '{"events":[';
744
953
  var BATCH_CLOSE = "]}";
745
954
  var BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;
@@ -1509,6 +1718,9 @@ function buildServerInstructions(options) {
1509
1718
  function buildAnnotationToolDescription(options) {
1510
1719
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
1511
1720
  }
1721
+ function buildRefusalText(options) {
1722
+ return `${options.annotationToolName} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`;
1723
+ }
1512
1724
  var USER_GOAL_PARAM_NAME = "user_goal";
1513
1725
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
1514
1726
  var OVERALL_TASK_PARAM_NAME = "overall_task";
@@ -1586,9 +1798,12 @@ var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
1586
1798
  function pythonStrip(value) {
1587
1799
  return stripEdges(value, PYTHON_SPACE);
1588
1800
  }
1801
+ function isPlaceholderLiteral(name) {
1802
+ return PLACEHOLDER_LITERALS.has(pythonStrip(name).toLowerCase());
1803
+ }
1589
1804
  function isLibraryPlaceholder(serverName, className) {
1805
+ if (isPlaceholderLiteral(serverName)) return true;
1590
1806
  const stripped = pythonStrip(serverName);
1591
- if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
1592
1807
  const stem = stripped.replace(RANDOM_SUFFIX, "");
1593
1808
  return stem !== stripped && stem === className;
1594
1809
  }
@@ -1643,8 +1858,15 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
1643
1858
  }
1644
1859
  return candidate;
1645
1860
  }
1861
+ function toolNameForDisplayName(vendorDisplayName) {
1862
+ if (isPlaceholderLiteral(vendorDisplayName)) return void 0;
1863
+ const candidate = toolNameCandidate(vendorDisplayName);
1864
+ return candidate !== void 0 && fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate }) ? candidate : void 0;
1865
+ }
1646
1866
  function deriveAnnotationToolName(vendorId2, override) {
1647
- const name = override || `${vendorId2}${SUFFIX}`;
1867
+ return validateAnnotationToolName(override || `${vendorId2}${SUFFIX}`);
1868
+ }
1869
+ function validateAnnotationToolName(name) {
1648
1870
  if (!TOOL_NAME_PATTERN.test(name)) {
1649
1871
  throw new Error(
1650
1872
  `Annotation tool name ${JSON.stringify(name)} violates the cross-runtime pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject names with dots or other separators).`
@@ -1680,9 +1902,27 @@ var PRINCIPAL_FORM_RAW = "raw";
1680
1902
  var PRINCIPAL_ID_MAX_LEN = 128;
1681
1903
  var DISPLAY_NAME_MAX_LEN = 128;
1682
1904
  function wireDisplayName(value) {
1683
- if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
1684
- if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
1685
- return value;
1905
+ return usableText(value, DISPLAY_NAME_MAX_LEN) ? value : null;
1906
+ }
1907
+ function usableText(value, maxCodePoints) {
1908
+ if (typeof value !== "string" || exceedsCodePoints(value, maxCodePoints)) return false;
1909
+ return !LONE_SURROGATE.test(value) && !value.includes("\0") && !isBlank(value);
1910
+ }
1911
+ var LABELS_MAX = 20;
1912
+ var LABEL_MAX_LEN = 64;
1913
+ var LABELS_READ_MAX = 1e3;
1914
+ function wireLabels(labels) {
1915
+ return labels.length > 0 ? labels : null;
1916
+ }
1917
+ function cleanLabels(values) {
1918
+ const kept = /* @__PURE__ */ new Set();
1919
+ for (const value of values) {
1920
+ if (usableText(value, LABEL_MAX_LEN)) {
1921
+ kept.add(value);
1922
+ if (kept.size === LABELS_MAX) break;
1923
+ }
1924
+ }
1925
+ return [...kept];
1686
1926
  }
1687
1927
  var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
1688
1928
  var LONE_SURROGATE = /\p{Surrogate}/u;
@@ -1700,7 +1940,7 @@ function readIdentity(result, idKey) {
1700
1940
  const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
1701
1941
  return { id, form: candidate.form, displayName };
1702
1942
  }
1703
- var NO_CALLER = Object.freeze({ principal: null, organization: null });
1943
+ var NO_CALLER = Object.freeze({ principal: null, organization: null, labels: [] });
1704
1944
  function callerFor(result, warn3) {
1705
1945
  try {
1706
1946
  return readCaller(result, warn3);
@@ -1717,7 +1957,11 @@ function readCaller(result, warn3) {
1717
1957
  }
1718
1958
  if (!("principalId" in result) && !("organization" in result)) {
1719
1959
  if ("organizationId" in result) {
1720
- return { principal: null, organization: identityFor(result, "organization", warn3) };
1960
+ return {
1961
+ principal: null,
1962
+ organization: identityFor(result, "organization", warn3),
1963
+ labels: labelsOf([result], warn3)
1964
+ };
1721
1965
  }
1722
1966
  if (typeof result.userId === "string") {
1723
1967
  warn3(
@@ -1735,9 +1979,29 @@ function readCaller(result, warn3) {
1735
1979
  const nested = result.organization;
1736
1980
  return {
1737
1981
  principal: identityFor(result, "principal", warn3),
1738
- organization: nested == null ? null : identityFor(nested, "organization", warn3)
1982
+ organization: nested == null ? null : identityFor(nested, "organization", warn3),
1983
+ labels: labelsOf([result, nested], warn3)
1739
1984
  };
1740
1985
  }
1986
+ function labelsOf(sources, warn3) {
1987
+ const labels = [];
1988
+ for (const source of sources) {
1989
+ try {
1990
+ const given = source?.labels;
1991
+ if (typeof given === "string" || typeof given?.[Symbol.iterator] !== "function") {
1992
+ continue;
1993
+ }
1994
+ let read = 0;
1995
+ for (const label of given) {
1996
+ labels.push(label);
1997
+ if (++read === LABELS_READ_MAX) break;
1998
+ }
1999
+ } catch {
2000
+ warn3("labels", "labels could not be read \u2014 sending the ones read before the failure.");
2001
+ }
2002
+ }
2003
+ return cleanLabels(labels);
2004
+ }
1741
2005
  function identityFor(value, member, warn3) {
1742
2006
  const idKey = member === "principal" ? "principalId" : "organizationId";
1743
2007
  const identity = readIdentity(value, idKey);
@@ -1848,7 +2112,35 @@ function warnOnce(key, message) {
1848
2112
  warned.add(key);
1849
2113
  warn(`baton: resolvePrincipal ${message}`);
1850
2114
  }
1851
- async function resolveCaller(hook, call) {
2115
+ function callerEnvelope(caller) {
2116
+ return {
2117
+ principal: caller.principal,
2118
+ organization: caller.organization,
2119
+ labels: wireLabels(caller.labels),
2120
+ capture: caller.settings?.capture ?? null
2121
+ };
2122
+ }
2123
+ var settingsWarned = false;
2124
+ async function resolveCaller(hook, call, settings, client = null) {
2125
+ const caller = await resolveIdentity(hook, call);
2126
+ if (settings === void 0) return caller;
2127
+ try {
2128
+ const identity = caller.principal ?? caller.organization;
2129
+ const callSettings = settings.forCaller({
2130
+ labels: caller.labels,
2131
+ clientName: client?.info?.name ?? null,
2132
+ shareKey: identity?.id ?? null
2133
+ });
2134
+ return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2135
+ } catch {
2136
+ if (!settingsWarned) {
2137
+ settingsWarned = true;
2138
+ warn("baton: applying capture settings failed; this request uses the config's values");
2139
+ }
2140
+ return caller;
2141
+ }
2142
+ }
2143
+ async function resolveIdentity(hook, call) {
1852
2144
  if (hook === void 0) return NO_CALLER;
1853
2145
  try {
1854
2146
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
@@ -1998,6 +2290,15 @@ function sessionIdFromHeader(extra) {
1998
2290
 
1999
2291
  // src/integrations/mcp/annotation.ts
2000
2292
  var TOOL_NAME_PARAM_NAME = "tool_name";
2293
+ var ANNOTATION_INPUT_SHAPE = {
2294
+ user_goal: z2.string(),
2295
+ what_happened: z2.string().optional(),
2296
+ // Nullable so a report whose agent sends an explicit null is taken,
2297
+ // not rejected by validation.
2298
+ tool_name: z2.string().nullable().optional(),
2299
+ suggested_improvement: z2.string().optional(),
2300
+ context: z2.record(z2.string(), z2.unknown()).optional()
2301
+ };
2001
2302
  function isReport(whatHappened) {
2002
2303
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2003
2304
  }
@@ -2006,19 +2307,12 @@ function registerAnnotationTool(server, options) {
2006
2307
  const description = buildAnnotationToolDescription({
2007
2308
  vendorDisplayName: options.vendorDisplayName
2008
2309
  });
2310
+ const refusal = buildRefusalText({ annotationToolName: name });
2009
2311
  server.registerTool(
2010
2312
  name,
2011
2313
  {
2012
2314
  description,
2013
- inputSchema: {
2014
- user_goal: z2.string(),
2015
- what_happened: z2.string().optional(),
2016
- // Nullable so a report whose agent sends an explicit null is taken,
2017
- // not rejected by validation.
2018
- tool_name: z2.string().nullable().optional(),
2019
- suggested_improvement: z2.string().optional(),
2020
- context: z2.record(z2.string(), z2.unknown()).optional()
2021
- }
2315
+ inputSchema: ANNOTATION_INPUT_SHAPE
2022
2316
  },
2023
2317
  async (args, extra) => {
2024
2318
  const whatHappened = args.what_happened;
@@ -2029,7 +2323,7 @@ function registerAnnotationTool(server, options) {
2029
2323
  type: "text",
2030
2324
  text: JSON.stringify({
2031
2325
  ok: false,
2032
- error: `${name} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`
2326
+ error: refusal
2033
2327
  })
2034
2328
  }
2035
2329
  ]
@@ -2043,9 +2337,12 @@ function registerAnnotationTool(server, options) {
2043
2337
  "_meta"
2044
2338
  );
2045
2339
  const session = await resolveSessionId(options.fallbackSessionId, extra);
2340
+ const client = observeClient(extra, { server, scrubber: options.scrubber });
2046
2341
  const caller = await resolveCaller(
2047
2342
  options.resolvePrincipal,
2048
- { extra, toolName: name, arguments: args }
2343
+ { extra, toolName: name, arguments: args },
2344
+ options.captureSettings,
2345
+ client
2049
2346
  );
2050
2347
  await emit(
2051
2348
  options.sink,
@@ -2056,11 +2353,10 @@ function registerAnnotationTool(server, options) {
2056
2353
  sequence_number: options.counter.nextFor(session),
2057
2354
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2058
2355
  consent_token: options.consentToken,
2059
- principal: caller.principal,
2060
- organization: caller.organization,
2356
+ ...callerEnvelope(caller),
2061
2357
  transport_observed: observeTransport(extra),
2062
2358
  session_id_origin: session.origin,
2063
- client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
2359
+ client_observed: client,
2064
2360
  runtime_meta: scrubbedMeta,
2065
2361
  payload: {
2066
2362
  // The agent-facing `user_goal` is stored as the wire key `intent`.
@@ -2353,10 +2649,195 @@ function scrubbedErrorBody(scrubber, text) {
2353
2649
  return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2354
2650
  }
2355
2651
 
2356
- // src/integrations/mcp/config.ts
2652
+ // src/integrations/mcp/captureSettings.ts
2653
+ import { createHash } from "crypto";
2654
+ var SETTINGS_PATH = "/v0/settings";
2655
+ var TENANT_HEADER = "X-Baton-Tenant-Id";
2656
+ var SETTINGS_MODES = ["local", "console"];
2657
+ var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
2658
+ var MIN_SETTINGS_REFRESH_MS = 15e3;
2659
+ var REQUEST_TIMEOUT_MS = 1e4;
2660
+ var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
2357
2661
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2358
2662
  var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2359
2663
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2664
+ function shareBucket(vendorId2, key) {
2665
+ const digest = createHash("sha256").update(`${vendorId2}
2666
+ ${key}`, "utf-8").digest();
2667
+ return Number(digest.readBigUInt64BE(0) % 10000n);
2668
+ }
2669
+ function matchesEveryone(audience) {
2670
+ return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
2671
+ }
2672
+ function matches(audience, caller, bucket) {
2673
+ if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
2674
+ if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
2675
+ return false;
2676
+ }
2677
+ if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
2678
+ return true;
2679
+ }
2680
+ var SettingsDocument = class {
2681
+ constructor(version, audiences) {
2682
+ this.version = version;
2683
+ this.audiences = audiences;
2684
+ this.usesShare = audiences.some((a) => a.shareThreshold !== null);
2685
+ this.unmatched = { capture: { settings_version: version } };
2686
+ this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
2687
+ }
2688
+ version;
2689
+ audiences;
2690
+ usesShare;
2691
+ unmatched;
2692
+ /** Whether some caller can get reports, so the instructions point to the
2693
+ * tool. Read only where the code's value is "on": no tool exists otherwise. */
2694
+ reportsOnForAnyone;
2695
+ settingsFor(caller, vendorId2) {
2696
+ const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
2697
+ return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
2698
+ }
2699
+ };
2700
+ function stringSet(value) {
2701
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
2702
+ return new Set(value);
2703
+ }
2704
+ function readAudience(version, id, match, capture) {
2705
+ if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
2706
+ let labels = null;
2707
+ let clients = null;
2708
+ let shareThreshold = null;
2709
+ if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
2710
+ if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
2711
+ if (Object.hasOwn(match, "share")) {
2712
+ const share = match.share;
2713
+ if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
2714
+ shareThreshold = Math.floor(share * 1e4 + 0.5);
2715
+ }
2716
+ const settings = { capture: { settings_version: version, audience: id } };
2717
+ const { results, goal, reports } = capture;
2718
+ if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
2719
+ settings.resultCaptureMode = results;
2720
+ }
2721
+ if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
2722
+ if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
2723
+ return { settings, labels, clients, shareThreshold };
2724
+ }
2725
+ function parseDocument(body) {
2726
+ let data;
2727
+ try {
2728
+ data = JSON.parse(body);
2729
+ } catch {
2730
+ return null;
2731
+ }
2732
+ if (!isRecord(data)) return null;
2733
+ const { version, audiences } = data;
2734
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
2735
+ if (!Array.isArray(audiences) || audiences.length === 0) return null;
2736
+ const parsed = [];
2737
+ for (const audience of audiences) {
2738
+ if (!isRecord(audience)) return null;
2739
+ const { id, match, capture } = audience;
2740
+ if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
2741
+ const readable = readAudience(version, id, match, capture);
2742
+ if (readable !== null) parsed.push(readable);
2743
+ }
2744
+ return new SettingsDocument(version, parsed);
2745
+ }
2746
+ var SettingsFetcher = class {
2747
+ url;
2748
+ // `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
2749
+ #headers;
2750
+ refreshMs;
2751
+ fetchImpl;
2752
+ etag = null;
2753
+ held = null;
2754
+ timer = null;
2755
+ reading = null;
2756
+ warned = false;
2757
+ constructor(options) {
2758
+ this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2759
+ this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2760
+ this.refreshMs = options.refreshMs;
2761
+ this.fetchImpl = options.fetchImpl ?? fetch;
2762
+ }
2763
+ get document() {
2764
+ return this.held;
2765
+ }
2766
+ start() {
2767
+ if (this.timer !== null) return;
2768
+ this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
2769
+ this.timer.unref?.();
2770
+ void this.readOnce();
2771
+ }
2772
+ stop() {
2773
+ if (this.timer !== null) clearInterval(this.timer);
2774
+ this.timer = null;
2775
+ this.reading?.abort();
2776
+ this.reading = null;
2777
+ }
2778
+ /** One request. Never rejects: a failure keeps what is held. */
2779
+ async readOnce() {
2780
+ if (this.reading !== null) return;
2781
+ const reading = new AbortController();
2782
+ this.reading = reading;
2783
+ const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
2784
+ timeout.unref?.();
2785
+ try {
2786
+ await this.read(reading.signal);
2787
+ } catch {
2788
+ } finally {
2789
+ clearTimeout(timeout);
2790
+ if (this.reading === reading) this.reading = null;
2791
+ }
2792
+ }
2793
+ async read(signal) {
2794
+ const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
2795
+ const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
2796
+ if (response.status !== 200) {
2797
+ void response.body?.cancel().catch(() => void 0);
2798
+ }
2799
+ if (signal.aborted) return;
2800
+ if (response.status === 204) {
2801
+ this.held = null;
2802
+ this.etag = null;
2803
+ } else if (response.status === 200) {
2804
+ const document = parseDocument(await response.text());
2805
+ if (signal.aborted) return;
2806
+ if (document === null) {
2807
+ if (!this.warned) {
2808
+ this.warned = true;
2809
+ warn("baton: the collector sent capture settings this SDK cannot read");
2810
+ }
2811
+ return;
2812
+ }
2813
+ this.held = document;
2814
+ this.etag = response.headers.get("etag");
2815
+ }
2816
+ }
2817
+ };
2818
+ var CaptureSettings = class {
2819
+ constructor(vendorId2, source) {
2820
+ this.vendorId = vendorId2;
2821
+ this.source = source;
2822
+ }
2823
+ vendorId;
2824
+ source;
2825
+ start() {
2826
+ this.source.start();
2827
+ }
2828
+ stop() {
2829
+ this.source.stop();
2830
+ }
2831
+ get document() {
2832
+ return this.source.document;
2833
+ }
2834
+ /** `undefined` while no document is held, and the config's values apply. */
2835
+ forCaller(caller) {
2836
+ return this.document?.settingsFor(caller, this.vendorId);
2837
+ }
2838
+ };
2839
+
2840
+ // src/integrations/mcp/config.ts
2360
2841
  function resolveTenantId(explicit, vendorId2) {
2361
2842
  if (explicit) return explicit;
2362
2843
  const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
@@ -2394,6 +2875,11 @@ function resolveBatonConfig(config) {
2394
2875
  consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
2395
2876
  };
2396
2877
  validateBatonConfig(defaulted);
2878
+ if (defaulted.settings === "console") {
2879
+ throw new Error(
2880
+ `BatonConfig.settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`
2881
+ );
2882
+ }
2397
2883
  return defaulted;
2398
2884
  }
2399
2885
  const dsn = parseDsn(dsnString);
@@ -2415,14 +2901,27 @@ function resolveBatonConfig(config) {
2415
2901
  // `??`, not `||`: an explicit empty string must survive to the validation
2416
2902
  // below and be REFUSED there, rather than be quietly replaced by the
2417
2903
  // default it was deliberately not left as.
2418
- consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
2904
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,
2905
+ ...config.reportMode === void 0 && config.settings === "console" ? { reportMode: "on" } : {}
2419
2906
  };
2420
2907
  validateBatonConfig(identity);
2421
2908
  return {
2422
2909
  ...identity,
2423
2910
  // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2424
2911
  // itself, exactly as it does for an explicitly-constructed sink.
2425
- sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2912
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
2913
+ ...identity.settings === "console" ? {
2914
+ captureSettings: new CaptureSettings(
2915
+ dsn.vendorId,
2916
+ new SettingsFetcher({
2917
+ origin: dsn.origin,
2918
+ apiKey: dsn.key,
2919
+ tenantId: dsn.tenantId,
2920
+ vendorId: dsn.vendorId,
2921
+ refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
2922
+ })
2923
+ )
2924
+ } : {}
2426
2925
  };
2427
2926
  }
2428
2927
  function withServerDisplayName(resolved, supplied, serverName) {
@@ -2487,6 +2986,17 @@ function validateBatonConfig(config) {
2487
2986
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
2488
2987
  );
2489
2988
  }
2989
+ if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
2990
+ throw new Error(
2991
+ `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
2992
+ );
2993
+ }
2994
+ const refresh = config.settingsRefreshMs;
2995
+ if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
2996
+ throw new Error(
2997
+ `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
2998
+ );
2999
+ }
2490
3000
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
2491
3001
  throw new Error("BatonConfig.scrubber must be a function.");
2492
3002
  }
@@ -2548,7 +3058,9 @@ function resumesPausedCall(extra) {
2548
3058
 
2549
3059
  // src/integrations/mcp/handle.ts
2550
3060
  var BatonHandle = class {
3061
+ /** The sink the vendor passed, or the default one. */
2551
3062
  sink;
3063
+ #queue;
2552
3064
  vendorId;
2553
3065
  /** The install's own session id: what stdio and in-memory calls, and the
2554
3066
  * surface snapshot, carry when no session id resolves. A call over HTTP
@@ -2560,6 +3072,7 @@ var BatonHandle = class {
2560
3072
  annotationToolName;
2561
3073
  constructor(options) {
2562
3074
  this.sink = options.sink;
3075
+ this.#queue = options.queue ?? options.sink;
2563
3076
  this.vendorId = options.vendorId;
2564
3077
  this.sessionId = options.sessionId;
2565
3078
  this.annotationToolName = options.annotationToolName;
@@ -2567,14 +3080,83 @@ var BatonHandle = class {
2567
3080
  /** Flush any pending events held by the sink. Never rejects; returns within
2568
3081
  * the shutdown budget (SPEC §11.2 rule 7). */
2569
3082
  async flush() {
2570
- await boundedSinkCall(this.sink, "flush");
3083
+ await boundedSinkCall(this.#queue, "flush");
2571
3084
  }
2572
3085
  /** Flush and release sink resources, on the same terms as `flush()`. */
2573
3086
  async aclose() {
2574
- await boundedSinkCall(this.sink, "aclose");
3087
+ await boundedSinkCall(this.#queue, "aclose");
2575
3088
  }
2576
3089
  };
2577
3090
 
3091
+ // src/integrations/mcp/perCaller.ts
3092
+ var PerCallerSurface = class {
3093
+ constructor(options) {
3094
+ this.options = options;
3095
+ }
3096
+ options;
3097
+ pointerOn = true;
3098
+ /** Called at install and on every request; writes only when the report
3099
+ * pointer should change. */
3100
+ followSettings() {
3101
+ if (this.options.annotationToolName === "") return;
3102
+ try {
3103
+ const document = this.options.settings.document;
3104
+ const pointerOn = document === null || document.reportsOnForAnyone;
3105
+ if (pointerOn === this.pointerOn) return;
3106
+ this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
3107
+ this.pointerOn = pointerOn;
3108
+ } catch (err) {
3109
+ process.stderr.write(`baton: could not update the server instructions for new settings: ${printable(err)}
3110
+ `);
3111
+ }
3112
+ }
3113
+ /** `result` with the caller's goal and reports settings; as served on any failure. */
3114
+ toolsFor(result, caller) {
3115
+ const settings = caller.settings;
3116
+ if (settings === void 0) return result;
3117
+ const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3118
+ const goal = settings.intentParamMode ?? intentParamMode;
3119
+ const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3120
+ if (goal === intentParamMode && !hideReports) return result;
3121
+ try {
3122
+ const tools = result?.tools;
3123
+ if (!Array.isArray(tools)) return result;
3124
+ const served = [];
3125
+ for (const tool of tools) {
3126
+ const name = tool?.name;
3127
+ if (hideReports && name === annotationToolName) continue;
3128
+ const rewrite = goal !== intentParamMode && typeof name === "string" && injectsGoal(name);
3129
+ served.push(rewrite ? withGoalMode(tool, goal) : tool);
3130
+ }
3131
+ return { ...result, tools: served };
3132
+ } catch (err) {
3133
+ process.stderr.write(`baton: could not apply capture settings to the tool list: ${printable(err)}
3134
+ `);
3135
+ return result;
3136
+ }
3137
+ }
3138
+ };
3139
+ function withGoalMode(tool, goal) {
3140
+ const entry = tool;
3141
+ const schema = entry.inputSchema;
3142
+ const properties = schema?.properties;
3143
+ const param = properties?.[USER_GOAL_PARAM_NAME];
3144
+ if (typeof param !== "object" || param === null) return tool;
3145
+ const others = Array.isArray(schema.required) ? schema.required.filter((name) => name !== USER_GOAL_PARAM_NAME) : [];
3146
+ const required = goal === "required" ? [...others, USER_GOAL_PARAM_NAME] : others;
3147
+ return {
3148
+ ...entry,
3149
+ inputSchema: {
3150
+ ...schema,
3151
+ properties: {
3152
+ ...properties,
3153
+ [USER_GOAL_PARAM_NAME]: { ...param, description: buildUserGoalParamDescription({ intentParamMode: goal }) }
3154
+ },
3155
+ ...required.length > 0 || Array.isArray(schema.required) ? { required } : {}
3156
+ }
3157
+ };
3158
+ }
3159
+
2578
3160
  // src/integrations/mcp/sessionCounter.ts
2579
3161
  var SESSION_CAP = 4096;
2580
3162
  var SessionCounter = class {
@@ -2687,16 +3269,16 @@ import { z as zV4 } from "zod";
2687
3269
  import { z as zV3 } from "zod/v3";
2688
3270
  var DEFAULT_INTENT_PARAM_MODE = "required";
2689
3271
  var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
2690
- function injectGoalParams(inputSchema, intentParamMode) {
2691
- const objSchema = normalizeObjectSchema(inputSchema);
2692
- if (!objSchema) return { schema: inputSchema, dispositions: {} };
3272
+ function injectGoalParams(inputSchema2, intentParamMode) {
3273
+ const objSchema = normalizeObjectSchema(inputSchema2);
3274
+ if (!objSchema) return { schema: inputSchema2, dispositions: {} };
2693
3275
  const existingShape = getObjectShape(objSchema) ?? {};
2694
3276
  const values = Object.values(existingShape);
2695
3277
  const useV4 = values.length === 0 || isZ4Schema(values[0]);
2696
3278
  const zodImpl = useV4 ? zV4 : zV3;
2697
3279
  const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
2698
3280
  if (Object.keys(toInject).length === 0)
2699
- return { schema: inputSchema, dispositions };
3281
+ return { schema: inputSchema2, dispositions };
2700
3282
  const mergedShape = { ...existingShape, ...toInject };
2701
3283
  const newSchema = objectFromShape(mergedShape);
2702
3284
  return { schema: newSchema, dispositions };
@@ -2715,15 +3297,15 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
2715
3297
  }
2716
3298
  return { dispositions, toInject };
2717
3299
  }
2718
- function injectGoalParamsV2(inputSchema, intentParamMode) {
2719
- const candidate = inputSchema;
3300
+ function injectGoalParamsV2(inputSchema2, intentParamMode) {
3301
+ const candidate = inputSchema2;
2720
3302
  const shape = candidate?.shape;
2721
3303
  if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
2722
- return { schema: inputSchema, dispositions: {} };
3304
+ return { schema: inputSchema2, dispositions: {} };
2723
3305
  }
2724
3306
  const { dispositions, toInject } = buildIntentFields(shape, zV4, intentParamMode);
2725
3307
  if (Object.keys(toInject).length === 0)
2726
- return { schema: inputSchema, dispositions };
3308
+ return { schema: inputSchema2, dispositions };
2727
3309
  return { schema: candidate.extend(toInject), dispositions };
2728
3310
  }
2729
3311
  function advertiseIntentParamsRequired(result, names, isInjected) {
@@ -2746,8 +3328,8 @@ function advertiseIntentParamsRequired(result, names, isInjected) {
2746
3328
  });
2747
3329
  return changed ? { ...result, tools: advertised } : result;
2748
3330
  }
2749
- function toolInputJsonSchema(inputSchema) {
2750
- const objSchema = normalizeObjectSchema(inputSchema);
3331
+ function toolInputJsonSchema(inputSchema2) {
3332
+ const objSchema = normalizeObjectSchema(inputSchema2);
2751
3333
  if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
2752
3334
  return toJsonSchemaCompat(objSchema, {
2753
3335
  strictUnions: true,
@@ -2756,10 +3338,10 @@ function toolInputJsonSchema(inputSchema) {
2756
3338
  }
2757
3339
 
2758
3340
  // src/integrations/mcp/surface.ts
2759
- import { createHash } from "crypto";
3341
+ import { createHash as createHash2 } from "crypto";
2760
3342
  function surfaceHash(surface) {
2761
3343
  const canonical = canonicalJson(surface);
2762
- const digest = createHash("sha256").update(canonical, "utf-8").digest("hex");
3344
+ const digest = createHash2("sha256").update(canonical, "utf-8").digest("hex");
2763
3345
  return `sha256:${digest}`;
2764
3346
  }
2765
3347
  function canonicalJson(value) {
@@ -2803,9 +3385,6 @@ var SentSurfaces = class {
2803
3385
  this.hashes.delete(this.hashes.values().next().value);
2804
3386
  }
2805
3387
  }
2806
- unmark(digest) {
2807
- this.hashes.delete(digest);
2808
- }
2809
3388
  };
2810
3389
  function buildSeamAugmentations(options) {
2811
3390
  return {
@@ -2895,10 +3474,14 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
2895
3474
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
2896
3475
  (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
2897
3476
  );
3477
+ const client = observeClient(extra, ctx);
2898
3478
  const caller = await resolveCaller(
2899
3479
  ctx.resolvePrincipal,
2900
- { extra, toolName, arguments: params }
3480
+ { extra, toolName, arguments: params },
3481
+ ctx.captureSettings,
3482
+ client
2901
3483
  );
3484
+ const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
2902
3485
  const common = {
2903
3486
  tenant_id: ctx.tenantId,
2904
3487
  vendor_id: ctx.vendorId,
@@ -2908,15 +3491,14 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
2908
3491
  // it. `surface_snapshot` is deliberately not among them: it describes the
2909
3492
  // SERVER and is captured outside any call, so it has no caller, transport
2910
3493
  // or client to name.
2911
- principal: caller.principal,
2912
- organization: caller.organization,
3494
+ ...callerEnvelope(caller),
2913
3495
  transport_observed: observeTransport(extra),
2914
3496
  session_id_origin: session.origin,
2915
- client_observed: observeClient(extra, ctx),
3497
+ client_observed: client,
2916
3498
  runtime_meta: scrubbedMeta,
2917
3499
  call_id: uuid7()
2918
3500
  };
2919
- if (resumesPausedCall(extra)) return { common, session };
3501
+ if (resumesPausedCall(extra)) return { common, session, resultCaptureMode };
2920
3502
  await emit(
2921
3503
  ctx.sink,
2922
3504
  () => ToolCallStartEventSchema.parse({
@@ -2934,7 +3516,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
2934
3516
  }
2935
3517
  })
2936
3518
  );
2937
- return { common, session };
3519
+ return { common, session, resultCaptureMode };
2938
3520
  }
2939
3521
  function batonWrap(nameRef, original, ctx) {
2940
3522
  return async (...callArgs) => {
@@ -2945,7 +3527,7 @@ function batonWrap(nameRef, original, ctx) {
2945
3527
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
2946
3528
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
2947
3529
  if (slot) slot.strippedFor = null;
2948
- const { common, session } = await openCall(ctx, toolName, extra, params, stripped);
3530
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
2949
3531
  const terminate = async (build, replacement) => {
2950
3532
  if (!slot) {
2951
3533
  if (build !== null) await emit(ctx.sink, build);
@@ -2978,7 +3560,7 @@ function batonWrap(nameRef, original, ctx) {
2978
3560
  // SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
2979
3561
  // raised message public, so under "off" every one is withheld.
2980
3562
  ...resultDerivedFields(
2981
- ctx.resultCaptureMode,
3563
+ resultCaptureMode,
2982
3564
  () => messageOf(err),
2983
3565
  null,
2984
3566
  (text) => errorBody(ctx, text),
@@ -3038,7 +3620,7 @@ function batonWrap(nameRef, original, ctx) {
3038
3620
  // nothing on the wire has; the loss is deliberate and worth
3039
3621
  // knowing when debugging one of these.
3040
3622
  ...resultDerivedFields(
3041
- ctx.resultCaptureMode,
3623
+ resultCaptureMode,
3042
3624
  () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
3043
3625
  // ⚠ `null` on the `raised` lane, never `undefined`, and the
3044
3626
  // union is what forces the branch rather than a comment: the
@@ -3077,7 +3659,7 @@ function batonWrap(nameRef, original, ctx) {
3077
3659
  // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
3078
3660
  // names the test that enforces it.
3079
3661
  ...returnedErrorFields(
3080
- ctx.resultCaptureMode,
3662
+ resultCaptureMode,
3081
3663
  result,
3082
3664
  (text) => errorBody(ctx, text),
3083
3665
  ctx.scrubber
@@ -3095,7 +3677,7 @@ function batonWrap(nameRef, original, ctx) {
3095
3677
  payload: {
3096
3678
  tool_name: toolName,
3097
3679
  duration_ms: durationMs,
3098
- ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
3680
+ ...endResultFields(resultCaptureMode, result, ctx.scrubber)
3099
3681
  }
3100
3682
  }),
3101
3683
  (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
@@ -3158,14 +3740,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3158
3740
  requiredParamNames: requiredParamNames(ctx.intentParamMode),
3159
3741
  instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
3160
3742
  });
3161
- try {
3162
- await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
3163
- } catch (err) {
3164
- process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
3165
- `);
3166
- sent.unmark(digest);
3167
- ctx.surfaceState.dirty = true;
3168
- }
3743
+ await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
3169
3744
  }
3170
3745
  function declaredIntentParams(vendorSchema) {
3171
3746
  const declared2 = {};
@@ -3248,6 +3823,7 @@ var LIFECYCLE_SEAMS = {
3248
3823
  };
3249
3824
  function installLifecycleSeam(lowLevel, ctx, spec) {
3250
3825
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
3826
+ ctx.perCaller?.followSettings();
3251
3827
  const request = args[0];
3252
3828
  const requestParams = request?.params ?? {};
3253
3829
  const extra = args[1];
@@ -3268,8 +3844,9 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3268
3844
  const startedAt = performance.now();
3269
3845
  const elapsed = () => Math.round(performance.now() - startedAt);
3270
3846
  try {
3271
- const result = await handler(...args);
3272
- if (isInputRequired(result)) return result;
3847
+ const served = await handler(...args);
3848
+ if (isInputRequired(served)) return served;
3849
+ const result = opened !== null && spec.rewriteResult !== void 0 ? spec.rewriteResult(ctx, served, opened.caller) : served;
3273
3850
  await fire(spec.schemas.end, {
3274
3851
  ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
3275
3852
  duration_ms: elapsed()
@@ -3291,24 +3868,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3291
3868
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
3292
3869
  try {
3293
3870
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3294
- const caller = await resolveCaller(ctx.resolvePrincipal, {
3295
- extra,
3296
- toolName: null,
3297
- arguments: {}
3298
- });
3871
+ const client = observeClient(extra, ctx);
3872
+ const caller = await resolveCaller(
3873
+ ctx.resolvePrincipal,
3874
+ { extra, toolName: null, arguments: {} },
3875
+ ctx.captureSettings,
3876
+ client
3877
+ );
3299
3878
  return {
3300
3879
  session,
3880
+ caller,
3301
3881
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
3302
3882
  common: {
3303
3883
  tenant_id: ctx.tenantId,
3304
3884
  vendor_id: ctx.vendorId,
3305
3885
  session_id: session.sessionId,
3306
3886
  consent_token: ctx.consentToken,
3307
- principal: caller.principal,
3308
- organization: caller.organization,
3887
+ ...callerEnvelope(caller),
3309
3888
  transport_observed: observeTransport(extra),
3310
3889
  session_id_origin: session.origin,
3311
- client_observed: observeClient(extra, ctx),
3890
+ client_observed: client,
3312
3891
  runtime_meta: scrubbedMeta
3313
3892
  }
3314
3893
  };
@@ -3391,7 +3970,8 @@ var LIFECYCLE_SPECS = [
3391
3970
  error: ToolListErrorEventSchema
3392
3971
  },
3393
3972
  countKey: "tools",
3394
- startParams: NO_PARAMS
3973
+ startParams: NO_PARAMS,
3974
+ rewriteResult: (ctx, result, caller) => ctx.perCaller?.toolsFor(result, caller) ?? result
3395
3975
  }
3396
3976
  ];
3397
3977
  function installLifecycleSeams(lowLevel, ctx) {
@@ -3433,6 +4013,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
3433
4013
  TOOLS_CALL_METHOD,
3434
4014
  TOOLS_CALL_SEAM,
3435
4015
  (handler) => async (...args) => {
4016
+ ctx.perCaller?.followSettings();
3436
4017
  const request = args[0];
3437
4018
  const name = request?.params?.name;
3438
4019
  const slot = {
@@ -3500,7 +4081,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3500
4081
  const entry = toolEntry(toolName);
3501
4082
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
3502
4083
  const params = { ...request?.params?.arguments ?? {} };
3503
- const { common, session } = await openCall(
4084
+ const { common, session, resultCaptureMode } = await openCall(
3504
4085
  ctx,
3505
4086
  toolName,
3506
4087
  args[1],
@@ -3543,7 +4124,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3543
4124
  ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3544
4125
  ...requestSideFailureFields(
3545
4126
  failureKind,
3546
- ctx.resultCaptureMode,
4127
+ resultCaptureMode,
3547
4128
  text,
3548
4129
  outcome.raised ? null : outcome.result,
3549
4130
  (value) => errorBody(ctx, value),
@@ -3620,8 +4201,28 @@ function withBaton(server, supplied = {}) {
3620
4201
  const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);
3621
4202
  if (unconfigured) logUnconfigured("withBaton");
3622
4203
  else warnAboutSettings(resolved);
3623
- return handle;
3624
- }
4204
+ const settings = resolved.captureSettings;
4205
+ if (settings === void 0) return handle;
4206
+ settings.start();
4207
+ return new SettingsHandle(handle, settings);
4208
+ }
4209
+ var SettingsHandle = class extends BatonHandle {
4210
+ constructor(inner, settings) {
4211
+ super(inner);
4212
+ this.inner = inner;
4213
+ this.settings = settings;
4214
+ }
4215
+ inner;
4216
+ settings;
4217
+ // The inner handle holds the queue in front of the sink.
4218
+ flush() {
4219
+ return this.inner.flush();
4220
+ }
4221
+ async aclose() {
4222
+ this.settings.stop();
4223
+ await this.inner.aclose();
4224
+ }
4225
+ };
3625
4226
  function createBaton(supplied = {}) {
3626
4227
  const disabledBy = captureDisabled();
3627
4228
  if (disabledBy !== null) {
@@ -3638,19 +4239,23 @@ function createBaton(supplied = {}) {
3638
4239
  if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
3639
4240
  if (unconfigured) logUnconfigured("createBaton");
3640
4241
  else warnAboutSettings(resolved);
3641
- const sink = unconfigured ? new DisabledSink() : resolved.sink ?? new StdoutSink();
4242
+ const sink = unconfigured ? new DisabledSink() : offTheCall(resolved.sink ?? new StdoutSink());
3642
4243
  const config = {
3643
4244
  ...resolved,
3644
4245
  sink,
3645
4246
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
3646
4247
  };
3647
4248
  const state = newBatonState(resolved);
4249
+ resolved.captureSettings?.start();
3648
4250
  return {
3649
4251
  wrap: (server) => {
3650
4252
  install(server, supplied, config, state, unconfigured);
3651
4253
  },
3652
4254
  flush: () => boundedSinkCall(sink, "flush"),
3653
- aclose: () => boundedSinkCall(sink, "aclose")
4255
+ aclose: () => {
4256
+ resolved.captureSettings?.stop();
4257
+ return boundedSinkCall(sink, "aclose");
4258
+ }
3654
4259
  };
3655
4260
  }
3656
4261
  function inertHandle(sink, sessionId) {
@@ -3684,7 +4289,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3684
4289
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
3685
4290
  const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3686
4291
  if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
3687
- const sink = config.sink ?? new StdoutSink();
4292
+ const given = config.sink ?? new StdoutSink();
4293
+ const sink = offTheCall(given);
3688
4294
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
3689
4295
  const fallbackSessionId = `sdk-${uuid7()}`;
3690
4296
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
@@ -3692,29 +4298,26 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3692
4298
  const serverMeta = buildServerMeta(server.server);
3693
4299
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
3694
4300
  const emitSurface = async (sessionId, digest, snapshot) => {
3695
- const event = SurfaceSnapshotEventSchema.parse({
3696
- tenant_id: tenantId,
3697
- vendor_id: config.vendorId,
3698
- session_id: sessionId,
3699
- session_id_origin: "minted",
3700
- consent_token: config.consentToken,
3701
- sequence_number: counter2.next(sessionId, false),
3702
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3703
- payload: {
3704
- surface_hash: digest,
3705
- server_info: snapshot.server_info,
3706
- capabilities: snapshot.capabilities,
3707
- instructions: snapshot.instructions,
3708
- tools: snapshot.tools,
3709
- seam_augmentations: snapshot.seam_augmentations
3710
- }
3711
- });
3712
- try {
3713
- await sink.write(event);
3714
- } catch (err) {
3715
- if (isSinkClosed(err)) return droppedAfterClose(sink);
3716
- throw err;
3717
- }
4301
+ await emit(
4302
+ sink,
4303
+ () => SurfaceSnapshotEventSchema.parse({
4304
+ tenant_id: tenantId,
4305
+ vendor_id: config.vendorId,
4306
+ session_id: sessionId,
4307
+ session_id_origin: "minted",
4308
+ consent_token: config.consentToken,
4309
+ sequence_number: counter2.next(sessionId, false),
4310
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
4311
+ payload: {
4312
+ surface_hash: digest,
4313
+ server_info: snapshot.server_info,
4314
+ capabilities: snapshot.capabilities,
4315
+ instructions: snapshot.instructions,
4316
+ tools: snapshot.tools,
4317
+ seam_augmentations: snapshot.seam_augmentations
4318
+ }
4319
+ })
4320
+ );
3718
4321
  };
3719
4322
  const bustSchemaMemo = (name) => {
3720
4323
  const memo = internals._toolInputSchemaJson;
@@ -3741,7 +4344,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3741
4344
  );
3742
4345
  };
3743
4346
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
3744
- const vendorToolJsonSchema = (name, inputSchema) => {
4347
+ const vendorToolJsonSchema = (name, inputSchema2) => {
3745
4348
  if (isV2Server) {
3746
4349
  try {
3747
4350
  const json = internals.toolInputSchemaJson(name);
@@ -3749,14 +4352,14 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3749
4352
  } catch {
3750
4353
  }
3751
4354
  try {
3752
- const standard = inputSchema?.["~standard"];
4355
+ const standard = inputSchema2?.["~standard"];
3753
4356
  const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
3754
4357
  if (json) return json;
3755
4358
  } catch {
3756
4359
  }
3757
4360
  }
3758
4361
  try {
3759
- return toolInputJsonSchema(inputSchema);
4362
+ return toolInputJsonSchema(inputSchema2);
3760
4363
  } catch {
3761
4364
  return { type: "object", properties: {} };
3762
4365
  }
@@ -3773,9 +4376,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3773
4376
  scrubber,
3774
4377
  annotationToolName,
3775
4378
  intentParamMode,
3776
- resultCaptureMode: config.resultCaptureMode ?? "full",
4379
+ configResultCaptureMode: config.resultCaptureMode ?? "full",
3777
4380
  paramRegistry: /* @__PURE__ */ new Map(),
3778
4381
  resolvePrincipal: config.resolvePrincipal,
4382
+ captureSettings: config.captureSettings,
4383
+ perCaller: void 0,
3779
4384
  vendorToolJsonSchema,
3780
4385
  bustSchemaMemo,
3781
4386
  dropSubagentClause,
@@ -3783,11 +4388,29 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3783
4388
  surfaceState,
3784
4389
  emitSurface
3785
4390
  };
3786
- internals.server._instructions = withVendorInstructions(
3787
- internals.server,
3788
- ours,
3789
- (message) => warnOnce2("instructions-length", message)
3790
- );
4391
+ const writeInstructions = (text) => {
4392
+ internals.server._instructions = withVendorInstructions(
4393
+ internals.server,
4394
+ text,
4395
+ (message) => warnOnce2("instructions-length", message)
4396
+ );
4397
+ };
4398
+ writeInstructions(ours);
4399
+ if (config.captureSettings !== void 0) {
4400
+ ctx.perCaller = new PerCallerSurface({
4401
+ settings: config.captureSettings,
4402
+ intentParamMode,
4403
+ annotationToolName,
4404
+ instructions: ours,
4405
+ writeInstructions: (text) => {
4406
+ writeInstructions(text);
4407
+ const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4408
+ if (native !== void 0) dropSubagentClause(native[0]);
4409
+ },
4410
+ injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4411
+ });
4412
+ ctx.perCaller.followSettings();
4413
+ }
3791
4414
  installToolsListSeam(internals.server, ctx);
3792
4415
  installToolsCallSeam(
3793
4416
  internals.server,
@@ -3813,6 +4436,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3813
4436
  vendorDisplayName: reports.vendorDisplayName,
3814
4437
  consentToken: ctx.consentToken,
3815
4438
  resolvePrincipal: ctx.resolvePrincipal,
4439
+ captureSettings: ctx.captureSettings,
3816
4440
  fallbackSessionId: ctx.fallbackSessionId,
3817
4441
  scrubber: ctx.scrubber,
3818
4442
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -3833,7 +4457,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3833
4457
  return registered;
3834
4458
  };
3835
4459
  return new BatonHandle({
3836
- sink,
4460
+ sink: given,
4461
+ queue: sink,
3837
4462
  vendorId: config.vendorId,
3838
4463
  sessionId: fallbackSessionId,
3839
4464
  annotationToolName: resolvedAnnotationToolName
@@ -3899,6 +4524,7 @@ function sessionEnvelope(session) {
3899
4524
  transport_observed: TRANSPORT_LIBRARY,
3900
4525
  principal: session.principal,
3901
4526
  organization: session.organization,
4527
+ labels: wireLabels(session.labels),
3902
4528
  client_observed: session.clientObserved,
3903
4529
  runtime_meta: session.runtimeMeta
3904
4530
  };
@@ -4097,8 +4723,6 @@ function paramsOf(args) {
4097
4723
  }
4098
4724
  var Core = class {
4099
4725
  closed = false;
4100
- pending = /* @__PURE__ */ new Set();
4101
- closedWarned = false;
4102
4726
  // A snapshot describes the server, so it takes no block's session,
4103
4727
  // principal or client: SPEC §11.5.1's join must not count it.
4104
4728
  surfaceSessionId = uuid7();
@@ -4111,7 +4735,7 @@ var Core = class {
4111
4735
  scrubber;
4112
4736
  disabled;
4113
4737
  constructor(resolved) {
4114
- this.sink = resolved.sink;
4738
+ this.sink = offTheCall(resolved.sink);
4115
4739
  this.vendorId = resolved.vendorId;
4116
4740
  this.tenantId = resolved.tenantId;
4117
4741
  this.consentToken = resolved.consentToken;
@@ -4135,25 +4759,15 @@ var Core = class {
4135
4759
  live() {
4136
4760
  if (this.disabled) return false;
4137
4761
  if (!this.closed) return true;
4138
- PROCESS_DROPS.add("after_close");
4139
- if (!this.closedWarned) {
4140
- this.closedWarned = true;
4141
- process.stderr.write("baton: Client is closed; further events are dropped.\n");
4142
- }
4762
+ droppedAfterClose(this.sink);
4143
4763
  return false;
4144
4764
  }
4145
- /** Never rejects. Tracked so `flush()` can wait for it. */
4765
+ /** Never rejects. */
4146
4766
  emit(build) {
4147
- return this.track(emit(this.sink, build));
4148
- }
4149
- track(work) {
4150
- const tracked = work.finally(() => this.pending.delete(tracked));
4151
- this.pending.add(tracked);
4152
- return tracked;
4767
+ return emit(this.sink, build);
4153
4768
  }
4154
- /** Sends `surface` unless this client already has. Never rejects; a failed
4155
- * write unmarks it, so the next `listTools` tries again. A surface that does
4156
- * not fit the schema stays marked: it would fail the same way every time. */
4769
+ /** Sends `surface` unless this client already has. Never rejects. The
4770
+ * write only queues, so a surface counts as sent once queued. */
4157
4771
  sendSurface(surface) {
4158
4772
  if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
4159
4773
  this.sentSurfaces.mark(surface.digest);
@@ -4175,32 +4789,7 @@ var Core = class {
4175
4789
  `);
4176
4790
  return Promise.resolve();
4177
4791
  }
4178
- return this.track(
4179
- (async () => {
4180
- try {
4181
- await this.sink.write(event);
4182
- } catch (err) {
4183
- if (isSinkClosed(err)) return droppedAfterClose(this.sink);
4184
- process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
4185
- `);
4186
- this.sentSurfaces.unmark(surface.digest);
4187
- }
4188
- })()
4189
- );
4190
- }
4191
- /** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
4192
- * also for ones emitted while it waits. A write still pending when time runs
4193
- * out is not waited on again, so one stuck write costs one wait. */
4194
- async settleWithin(ms, untilEmpty) {
4195
- const deadline = performance.now() + ms;
4196
- do {
4197
- const waiting = [...this.pending];
4198
- if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
4199
- const left = waiting.filter((write) => this.pending.delete(write));
4200
- if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
4201
- return;
4202
- }
4203
- } while (untilEmpty && this.pending.size > 0);
4792
+ return safeWrite(this.sink, event);
4204
4793
  }
4205
4794
  scrub(value, field) {
4206
4795
  return scrubOrNull(this.scrubber, value, field);
@@ -4471,93 +5060,81 @@ var Client = class {
4471
5060
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
4472
5061
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
4473
5062
  async flush() {
4474
- await this.#settleThen("flush");
5063
+ await boundedSinkCall(this.#core.sink, "flush");
4475
5064
  }
4476
5065
  /** Flush, then close the sink. Later events are dropped. */
4477
5066
  aclose() {
4478
- this.#closing ??= this.#settleThen("aclose");
4479
- return this.#closing;
4480
- }
4481
- /** One budget: events in flight get until its end to reach the sink, then
4482
- * the sink gets the time left. */
4483
- async #settleThen(method) {
4484
- await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
4485
- const deadline = performance.now() + budgetMs;
4486
- await this.#core.settleWithin(budgetMs, method === "aclose");
4487
- if (method === "aclose") this.#core.closed = true;
4488
- await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
5067
+ this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5068
+ this.#core.closed = true;
4489
5069
  });
5070
+ return this.#closing;
4490
5071
  }
4491
5072
  };
5073
+
5074
+ // src/library/reportTool.ts
5075
+ function inputSchema() {
5076
+ const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5077
+ delete schema.$schema;
5078
+ return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5079
+ }
5080
+ var nonEmptyText = (value) => typeof value === "string" && value !== "";
5081
+ var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5082
+ function annotateArgs(args) {
5083
+ const whatHappened = args.what_happened;
5084
+ if (!isReport(whatHappened)) return null;
5085
+ const options = { whatHappened };
5086
+ const toolName = args[TOOL_NAME_PARAM_NAME];
5087
+ if (typeof toolName === "string") options.toolName = toolName;
5088
+ const intent = args[USER_GOAL_PARAM_NAME];
5089
+ if (nonEmptyText(intent)) options.intent = intent;
5090
+ if (nonEmptyText(args.suggested_improvement)) {
5091
+ options.suggestedImprovement = args.suggested_improvement;
5092
+ }
5093
+ if (nonEmptyObject(args.context)) options.context = args.context;
5094
+ return options;
5095
+ }
5096
+ function reportTool(options) {
5097
+ const { vendorDisplayName } = options;
5098
+ const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5099
+ if (derived === void 0) {
5100
+ throw new Error(
5101
+ `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for the instructions. Pass name.`
5102
+ );
5103
+ }
5104
+ const name = validateAnnotationToolName(derived);
5105
+ if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {
5106
+ throw new Error(
5107
+ `vendorDisplayName and name ${JSON.stringify(name)} are too long together for the instructions. Shorten one of them.`
5108
+ );
5109
+ }
5110
+ return {
5111
+ name,
5112
+ description: buildAnnotationToolDescription({ vendorDisplayName }),
5113
+ inputSchema: inputSchema(),
5114
+ instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5115
+ refusal: buildRefusalText({ annotationToolName: name }),
5116
+ annotateArgs
5117
+ };
5118
+ }
4492
5119
  export {
4493
- AnnotationEventSchema,
4494
- AnnotationPayloadSchema,
4495
5120
  BatonHandle,
4496
5121
  Client,
4497
- ClientReportEventSchema,
4498
- ClientReportPayloadSchema,
4499
- DEFAULT_CONSENT_TOKEN,
4500
- DEPTH_LIMIT,
4501
- DEPTH_MARKER,
4502
5122
  EventSchema,
4503
- EventTypeSchema,
4504
5123
  FileSink,
4505
5124
  HttpSink,
4506
5125
  INTENT_INSTRUCTIONS,
4507
5126
  INTENT_PARAMS,
4508
5127
  MultiSink,
4509
- PRINCIPAL_FORM_HASHED,
4510
- PRINCIPAL_FORM_RAW,
4511
- PRINCIPAL_SOURCE_ASSERTED,
4512
- PrincipalWireSchema,
4513
- PromptGetEndEventSchema,
4514
- PromptGetEndPayloadSchema,
4515
- PromptGetErrorEventSchema,
4516
- PromptGetErrorPayloadSchema,
4517
- PromptGetStartEventSchema,
4518
- PromptGetStartPayloadSchema,
4519
- PromptListEndEventSchema,
4520
- PromptListEndPayloadSchema,
4521
- PromptListErrorEventSchema,
4522
- PromptListErrorPayloadSchema,
4523
- PromptListStartEventSchema,
4524
- PromptListStartPayloadSchema,
4525
- ResourceListEndEventSchema,
4526
- ResourceListEndPayloadSchema,
4527
- ResourceListErrorEventSchema,
4528
- ResourceListErrorPayloadSchema,
4529
- ResourceListStartEventSchema,
4530
- ResourceListStartPayloadSchema,
4531
- ResourceReadEndEventSchema,
4532
- ResourceReadEndPayloadSchema,
4533
- ResourceReadErrorEventSchema,
4534
- ResourceReadErrorPayloadSchema,
4535
- ResourceReadStartEventSchema,
4536
- ResourceReadStartPayloadSchema,
4537
5128
  SDK_VERSION,
4538
5129
  Scrubber,
4539
5130
  SinkClosedError,
4540
5131
  StdoutSink,
4541
- SurfaceSnapshotEventSchema,
4542
- SurfaceSnapshotPayloadSchema,
4543
- ToolCallEndEventSchema,
4544
- ToolCallEndPayloadSchema,
4545
- ToolCallErrorEventSchema,
4546
- ToolCallErrorPayloadSchema,
4547
- ToolCallStartEventSchema,
4548
- ToolCallStartPayloadSchema,
4549
- ToolListEndEventSchema,
4550
- ToolListEndPayloadSchema,
4551
- ToolListErrorEventSchema,
4552
- ToolListErrorPayloadSchema,
4553
- ToolListStartEventSchema,
4554
- ToolListStartPayloadSchema,
4555
5132
  Trace,
4556
5133
  createBaton,
4557
5134
  identityScrub,
4558
5135
  principalFromOAuthEmail,
4559
5136
  principalFromOAuthSub,
4560
- safeWrite,
5137
+ reportTool,
4561
5138
  withBaton
4562
5139
  };
4563
5140
  //# sourceMappingURL=index.js.map