@goodtiming/baton-sdk 0.6.8 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -30,80 +30,30 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- AnnotationEventSchema: () => AnnotationEventSchema,
34
- AnnotationPayloadSchema: () => AnnotationPayloadSchema,
35
33
  BatonHandle: () => BatonHandle,
36
34
  Client: () => Client,
37
- ClientReportEventSchema: () => ClientReportEventSchema,
38
- ClientReportPayloadSchema: () => ClientReportPayloadSchema,
39
- DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
40
- DEPTH_LIMIT: () => DEPTH_LIMIT,
41
- DEPTH_MARKER: () => DEPTH_MARKER,
42
35
  EventSchema: () => EventSchema,
43
- EventTypeSchema: () => EventTypeSchema,
44
36
  FileSink: () => FileSink,
45
37
  HttpSink: () => HttpSink,
46
38
  INTENT_INSTRUCTIONS: () => INTENT_INSTRUCTIONS,
47
39
  INTENT_PARAMS: () => INTENT_PARAMS,
48
40
  MultiSink: () => MultiSink,
49
- PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
50
- PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
51
- PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
52
- PrincipalWireSchema: () => PrincipalWireSchema,
53
- PromptGetEndEventSchema: () => PromptGetEndEventSchema,
54
- PromptGetEndPayloadSchema: () => PromptGetEndPayloadSchema,
55
- PromptGetErrorEventSchema: () => PromptGetErrorEventSchema,
56
- PromptGetErrorPayloadSchema: () => PromptGetErrorPayloadSchema,
57
- PromptGetStartEventSchema: () => PromptGetStartEventSchema,
58
- PromptGetStartPayloadSchema: () => PromptGetStartPayloadSchema,
59
- PromptListEndEventSchema: () => PromptListEndEventSchema,
60
- PromptListEndPayloadSchema: () => PromptListEndPayloadSchema,
61
- PromptListErrorEventSchema: () => PromptListErrorEventSchema,
62
- PromptListErrorPayloadSchema: () => PromptListErrorPayloadSchema,
63
- PromptListStartEventSchema: () => PromptListStartEventSchema,
64
- PromptListStartPayloadSchema: () => PromptListStartPayloadSchema,
65
- ResourceListEndEventSchema: () => ResourceListEndEventSchema,
66
- ResourceListEndPayloadSchema: () => ResourceListEndPayloadSchema,
67
- ResourceListErrorEventSchema: () => ResourceListErrorEventSchema,
68
- ResourceListErrorPayloadSchema: () => ResourceListErrorPayloadSchema,
69
- ResourceListStartEventSchema: () => ResourceListStartEventSchema,
70
- ResourceListStartPayloadSchema: () => ResourceListStartPayloadSchema,
71
- ResourceReadEndEventSchema: () => ResourceReadEndEventSchema,
72
- ResourceReadEndPayloadSchema: () => ResourceReadEndPayloadSchema,
73
- ResourceReadErrorEventSchema: () => ResourceReadErrorEventSchema,
74
- ResourceReadErrorPayloadSchema: () => ResourceReadErrorPayloadSchema,
75
- ResourceReadStartEventSchema: () => ResourceReadStartEventSchema,
76
- ResourceReadStartPayloadSchema: () => ResourceReadStartPayloadSchema,
77
41
  SDK_VERSION: () => SDK_VERSION,
78
42
  Scrubber: () => Scrubber,
79
43
  SinkClosedError: () => SinkClosedError,
80
44
  StdoutSink: () => StdoutSink,
81
- SurfaceSnapshotEventSchema: () => SurfaceSnapshotEventSchema,
82
- SurfaceSnapshotPayloadSchema: () => SurfaceSnapshotPayloadSchema,
83
- ToolCallEndEventSchema: () => ToolCallEndEventSchema,
84
- ToolCallEndPayloadSchema: () => ToolCallEndPayloadSchema,
85
- ToolCallErrorEventSchema: () => ToolCallErrorEventSchema,
86
- ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
87
- ToolCallStartEventSchema: () => ToolCallStartEventSchema,
88
- ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
89
- ToolListEndEventSchema: () => ToolListEndEventSchema,
90
- ToolListEndPayloadSchema: () => ToolListEndPayloadSchema,
91
- ToolListErrorEventSchema: () => ToolListErrorEventSchema,
92
- ToolListErrorPayloadSchema: () => ToolListErrorPayloadSchema,
93
- ToolListStartEventSchema: () => ToolListStartEventSchema,
94
- ToolListStartPayloadSchema: () => ToolListStartPayloadSchema,
95
45
  Trace: () => Trace,
96
46
  createBaton: () => createBaton,
97
47
  identityScrub: () => identityScrub,
98
48
  principalFromOAuthEmail: () => principalFromOAuthEmail,
99
49
  principalFromOAuthSub: () => principalFromOAuthSub,
100
- safeWrite: () => safeWrite,
50
+ reportTool: () => reportTool,
101
51
  withBaton: () => withBaton
102
52
  });
103
53
  module.exports = __toCommonJS(index_exports);
104
54
 
105
55
  // src/version.ts
106
- var SDK_VERSION = "ts-0.6.8";
56
+ var SDK_VERSION = "ts-1.0.1";
107
57
 
108
58
  // src/events.ts
109
59
  var import_zod = require("zod");
@@ -233,6 +183,11 @@ var ClientObservedSchema = import_zod.z.object({
233
183
  info: import_zod.z.object({ name: import_zod.z.string().optional(), version: import_zod.z.string().optional() }).strict().optional(),
234
184
  headers: import_zod.z.object({ "user-agent": import_zod.z.string().optional(), "x-anthropic-client": import_zod.z.string().optional() }).strict().optional()
235
185
  }).strict();
186
+ var CaptureObservedSchema = import_zod.z.object({
187
+ settings_version: import_zod.z.number().int().min(1).optional(),
188
+ audience: import_zod.z.string().optional(),
189
+ overlay: import_zod.z.string().optional()
190
+ }).strict();
236
191
  var PrincipalWireSchema = import_zod.z.object({
237
192
  id: import_zod.z.string(),
238
193
  source: import_zod.z.string(),
@@ -253,6 +208,10 @@ var envelopeShape = {
253
208
  agent_runtime: import_zod.z.string().default("unknown"),
254
209
  principal: PrincipalWireSchema.nullable().default(null),
255
210
  organization: PrincipalWireSchema.nullable().default(null),
211
+ // No length rules here: zod counts UTF-16 units, SPEC §11.4 code points.
212
+ // `cleanLabels` applies them.
213
+ labels: import_zod.z.array(import_zod.z.string()).nullable().default(null),
214
+ capture: CaptureObservedSchema.nullable().default(null),
256
215
  transport_observed: import_zod.z.string().nullable().default(null),
257
216
  session_id_origin: import_zod.z.string().nullable().default(null),
258
217
  client_observed: ClientObservedSchema.nullable().default(null),
@@ -613,6 +572,7 @@ function identityScrub(value) {
613
572
 
614
573
  // src/sinks.ts
615
574
  var import_node_fs = require("fs");
575
+ var import_promises = require("fs/promises");
616
576
 
617
577
  // src/_text.ts
618
578
  var WHITE_SPACE = /^\p{White_Space}$/u;
@@ -752,6 +712,7 @@ function timerMsOption(given, name, fallback) {
752
712
  function shutdownBudgetMs(sink) {
753
713
  try {
754
714
  if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
715
+ if (sink instanceof QueuedSink) return shutdownBudgetMs(sink.inner);
755
716
  const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
756
717
  if (isTimerMs(budget)) return budget;
757
718
  } catch {
@@ -796,22 +757,32 @@ var FileSink = class {
796
757
  this.path = path;
797
758
  }
798
759
  path;
799
- fd = null;
760
+ file = null;
761
+ closeOnce;
762
+ /** Writes run one after another: two at once on one file can interleave. */
763
+ last = Promise.resolve();
800
764
  closed = false;
801
765
  async write(event) {
802
766
  if (this.closed) throw new SinkClosedError("FileSink is closed");
803
- this.fd ??= (0, import_node_fs.openSync)(this.path, "a");
804
- (0, import_node_fs.writeSync)(this.fd, JSON.stringify(event) + "\n");
767
+ const line = JSON.stringify(event) + "\n";
768
+ const written = this.last.then(async () => {
769
+ this.file ??= await (0, import_promises.open)(this.path, "a");
770
+ await this.file.appendFile(line);
771
+ });
772
+ this.last = written.catch(() => void 0);
773
+ await written;
805
774
  }
806
775
  async flush() {
776
+ await this.last;
807
777
  }
808
- async aclose() {
809
- if (this.closed) return;
778
+ /** A second call waits for the first (SPEC §11.2 rule 7). */
779
+ aclose() {
810
780
  this.closed = true;
811
- if (this.fd !== null) {
812
- (0, import_node_fs.closeSync)(this.fd);
813
- this.fd = null;
814
- }
781
+ this.closeOnce ??= this.last.then(async () => {
782
+ await this.file?.close();
783
+ this.file = null;
784
+ });
785
+ return this.closeOnce;
815
786
  }
816
787
  };
817
788
  var MultiSink = class {
@@ -844,6 +815,194 @@ var MultiSink = class {
844
815
  throw new AggregateError(errors, "MultiSink fan-out failures");
845
816
  }
846
817
  };
818
+ var QUEUE_BOUND = 1e3;
819
+ var WRITES_PER_TURN = 100;
820
+ var CLOSE_GRACE_MS = 250;
821
+ var later = (run) => {
822
+ if (typeof setImmediate === "function") setImmediate(run);
823
+ else setTimeout(run, 0);
824
+ };
825
+ var withUnwrittenEvents = /* @__PURE__ */ new Set();
826
+ var exitHooked = false;
827
+ function hookExit() {
828
+ if (exitHooked) return;
829
+ exitHooked = true;
830
+ try {
831
+ process.on("exit", () => {
832
+ try {
833
+ let unsure = 0;
834
+ for (const sink of withUnwrittenEvents) unsure += sink.handOffAtExit();
835
+ if (unsure > 0) stderrLine(`baton: process exiting; ${unsure} event(s) may not have been written.`);
836
+ } catch {
837
+ }
838
+ });
839
+ } catch {
840
+ }
841
+ }
842
+ function writeNow(sink, events) {
843
+ const lines = events.map((event) => JSON.stringify(event) + "\n").join("");
844
+ if (sink instanceof StdoutSink) {
845
+ const stream = sink["stream"];
846
+ if (stream !== process.stdout && stream !== process.stderr) return false;
847
+ if (!sink["closed"]) stream.write(lines);
848
+ } else if (sink instanceof FileSink) {
849
+ if (!sink["closed"]) (0, import_node_fs.appendFileSync)(sink["path"], lines);
850
+ } else return false;
851
+ return true;
852
+ }
853
+ var QueuedSink = class {
854
+ constructor(inner) {
855
+ this.inner = inner;
856
+ }
857
+ inner;
858
+ queue = [];
859
+ closed = false;
860
+ draining = false;
861
+ /** Set when close ran out of time or the process is exiting: what was left is already handled. */
862
+ abandoned = false;
863
+ inFlight = 0;
864
+ /** A flush waits until `settled`, the events written or lost, reaches `taken` as it was. */
865
+ taken = 0;
866
+ settled = 0;
867
+ /** Writes that returned, so a dropped event does not look like progress. */
868
+ ended = 0;
869
+ /** `ended` when a flush waited its whole budget: until a write ends, later flushes return at once. */
870
+ stuckAt = null;
871
+ waiters = [];
872
+ overflowWarned = false;
873
+ failWarned = false;
874
+ copyWarned = false;
875
+ closeOnce;
876
+ get unwritten() {
877
+ return this.queue.length + this.inFlight;
878
+ }
879
+ /** Writes what waits to a `StdoutSink` or `FileSink` at once; answers how
880
+ * many events may not be written. */
881
+ handOffAtExit() {
882
+ this.abandoned = true;
883
+ const waiting = this.queue.splice(0);
884
+ let written = false;
885
+ try {
886
+ written = waiting.length === 0 || writeNow(this.inner, waiting);
887
+ } catch {
888
+ }
889
+ return this.inFlight + (written ? 0 : waiting.length);
890
+ }
891
+ async write(event) {
892
+ if (this.closed) throw new SinkClosedError("the sink is closed");
893
+ let copy;
894
+ try {
895
+ copy = JSON.parse(JSON.stringify(event));
896
+ } catch (err) {
897
+ PROCESS_DROPS.add("encode_failed");
898
+ if (!this.copyWarned) {
899
+ this.copyWarned = true;
900
+ warn(`baton: an event could not be copied and was dropped (${err?.name ?? "Error"}). Later ones are not logged.`);
901
+ }
902
+ return;
903
+ }
904
+ this.queue.push(copy);
905
+ this.taken++;
906
+ if (this.queue.length > QUEUE_BOUND) {
907
+ this.queue.shift();
908
+ this.settle();
909
+ PROCESS_DROPS.add("buffer_full");
910
+ if (!this.overflowWarned) {
911
+ this.overflowWarned = true;
912
+ warn(`baton: the sink's queue is full (${QUEUE_BOUND}); oldest events dropped. Further overflows will be silent.`);
913
+ }
914
+ }
915
+ withUnwrittenEvents.add(this);
916
+ hookExit();
917
+ if (!this.draining) {
918
+ this.draining = true;
919
+ later(() => void this.drain());
920
+ }
921
+ }
922
+ /** Waits for the events written before it, not for later ones (SPEC §11.2 rule 7). */
923
+ async flush() {
924
+ if (this.closed || this.stuckAt === this.ended) return;
925
+ const budget = shutdownBudgetMs(this.inner);
926
+ const start = performance.now();
927
+ if (await raceDeadline(this.settledUpTo(this.taken), budget) === TIMED_OUT) this.stuckAt = this.ended;
928
+ await callWithin(this.inner, "flush", Math.max(0, budget - (performance.now() - start)));
929
+ }
930
+ /** A second call waits for the first (SPEC §11.2 rule 7). */
931
+ aclose() {
932
+ this.closeOnce ??= this.close(shutdownBudgetMs(this.inner));
933
+ return this.closeOnce;
934
+ }
935
+ /** Takes events until the queue is empty, as `HttpSink` does, so an event
936
+ * recorded while close runs is not refused. */
937
+ async close(ms) {
938
+ const start = performance.now();
939
+ const deadline = start + ms - Math.min(CLOSE_GRACE_MS, ms / 2);
940
+ let timedOut = false;
941
+ while (this.settled < this.taken && !timedOut) {
942
+ timedOut = await raceDeadline(this.settledUpTo(this.taken), deadline - performance.now()) === TIMED_OUT;
943
+ }
944
+ this.closed = true;
945
+ if (timedOut) {
946
+ const unwritten = this.unwritten;
947
+ this.abandoned = true;
948
+ this.queue.length = 0;
949
+ withUnwrittenEvents.delete(this);
950
+ PROCESS_DROPS.add("unsent_at_close", unwritten);
951
+ warn(`baton: closed with ${unwritten} event(s) not yet written to the sink.`);
952
+ }
953
+ await callWithin(this.inner, "aclose", Math.max(0, ms - (performance.now() - start)));
954
+ }
955
+ async drain() {
956
+ try {
957
+ let event;
958
+ let written = 0;
959
+ while (!this.abandoned && (event = this.queue.shift()) !== void 0) {
960
+ this.inFlight = 1;
961
+ try {
962
+ await this.inner.write(event);
963
+ } catch (err) {
964
+ if (!this.abandoned) this.lose(err);
965
+ } finally {
966
+ this.inFlight = 0;
967
+ this.ended++;
968
+ this.settle();
969
+ }
970
+ if (++written % WRITES_PER_TURN === 0) await new Promise((resolve) => later(resolve));
971
+ }
972
+ } catch {
973
+ } finally {
974
+ this.draining = false;
975
+ if (this.queue.length === 0) withUnwrittenEvents.delete(this);
976
+ else if (!this.abandoned) {
977
+ this.draining = true;
978
+ later(() => void this.drain());
979
+ }
980
+ }
981
+ }
982
+ lose(err) {
983
+ if (isSinkClosed(err)) return droppedAfterClose(this);
984
+ PROCESS_DROPS.add("write_failed");
985
+ if (this.failWarned) return;
986
+ this.failWarned = true;
987
+ warn(`baton: the sink failed to write an event; it was dropped. Later failures are not logged: ${printable(err)}`);
988
+ }
989
+ settle() {
990
+ this.settled++;
991
+ this.waiters = this.waiters.filter((w) => {
992
+ if (w.upTo > this.settled) return true;
993
+ w.resolve();
994
+ return false;
995
+ });
996
+ }
997
+ settledUpTo(upTo) {
998
+ if (this.settled >= upTo) return Promise.resolve();
999
+ return new Promise((resolve) => this.waiters.push({ upTo, resolve }));
1000
+ }
1001
+ };
1002
+ function offTheCall(sink) {
1003
+ if (sink instanceof QueuedSink || sink instanceof HttpSink && sink.write === HttpSink.prototype.write) return sink;
1004
+ return new QueuedSink(sink);
1005
+ }
847
1006
  var BATCH_OPEN = '{"events":[';
848
1007
  var BATCH_CLOSE = "]}";
849
1008
  var BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;
@@ -1613,6 +1772,9 @@ function buildServerInstructions(options) {
1613
1772
  function buildAnnotationToolDescription(options) {
1614
1773
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
1615
1774
  }
1775
+ function buildRefusalText(options) {
1776
+ 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.`;
1777
+ }
1616
1778
  var USER_GOAL_PARAM_NAME = "user_goal";
1617
1779
  var EXPECTED_RESULT_PARAM_NAME = "expected_result";
1618
1780
  var OVERALL_TASK_PARAM_NAME = "overall_task";
@@ -1690,9 +1852,12 @@ var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
1690
1852
  function pythonStrip(value) {
1691
1853
  return stripEdges(value, PYTHON_SPACE);
1692
1854
  }
1855
+ function isPlaceholderLiteral(name) {
1856
+ return PLACEHOLDER_LITERALS.has(pythonStrip(name).toLowerCase());
1857
+ }
1693
1858
  function isLibraryPlaceholder(serverName, className) {
1859
+ if (isPlaceholderLiteral(serverName)) return true;
1694
1860
  const stripped = pythonStrip(serverName);
1695
- if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
1696
1861
  const stem = stripped.replace(RANDOM_SUFFIX, "");
1697
1862
  return stem !== stripped && stem === className;
1698
1863
  }
@@ -1747,8 +1912,15 @@ function annotationToolNameFromServer(serverName, vendorDisplayName) {
1747
1912
  }
1748
1913
  return candidate;
1749
1914
  }
1915
+ function toolNameForDisplayName(vendorDisplayName) {
1916
+ if (isPlaceholderLiteral(vendorDisplayName)) return void 0;
1917
+ const candidate = toolNameCandidate(vendorDisplayName);
1918
+ return candidate !== void 0 && fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate }) ? candidate : void 0;
1919
+ }
1750
1920
  function deriveAnnotationToolName(vendorId2, override) {
1751
- const name = override || `${vendorId2}${SUFFIX}`;
1921
+ return validateAnnotationToolName(override || `${vendorId2}${SUFFIX}`);
1922
+ }
1923
+ function validateAnnotationToolName(name) {
1752
1924
  if (!TOOL_NAME_PATTERN.test(name)) {
1753
1925
  throw new Error(
1754
1926
  `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).`
@@ -1784,9 +1956,27 @@ var PRINCIPAL_FORM_RAW = "raw";
1784
1956
  var PRINCIPAL_ID_MAX_LEN = 128;
1785
1957
  var DISPLAY_NAME_MAX_LEN = 128;
1786
1958
  function wireDisplayName(value) {
1787
- if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
1788
- if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
1789
- return value;
1959
+ return usableText(value, DISPLAY_NAME_MAX_LEN) ? value : null;
1960
+ }
1961
+ function usableText(value, maxCodePoints) {
1962
+ if (typeof value !== "string" || exceedsCodePoints(value, maxCodePoints)) return false;
1963
+ return !LONE_SURROGATE.test(value) && !value.includes("\0") && !isBlank(value);
1964
+ }
1965
+ var LABELS_MAX = 20;
1966
+ var LABEL_MAX_LEN = 64;
1967
+ var LABELS_READ_MAX = 1e3;
1968
+ function wireLabels(labels) {
1969
+ return labels.length > 0 ? labels : null;
1970
+ }
1971
+ function cleanLabels(values) {
1972
+ const kept = /* @__PURE__ */ new Set();
1973
+ for (const value of values) {
1974
+ if (usableText(value, LABEL_MAX_LEN)) {
1975
+ kept.add(value);
1976
+ if (kept.size === LABELS_MAX) break;
1977
+ }
1978
+ }
1979
+ return [...kept];
1790
1980
  }
1791
1981
  var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
1792
1982
  var LONE_SURROGATE = /\p{Surrogate}/u;
@@ -1804,7 +1994,7 @@ function readIdentity(result, idKey) {
1804
1994
  const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
1805
1995
  return { id, form: candidate.form, displayName };
1806
1996
  }
1807
- var NO_CALLER = Object.freeze({ principal: null, organization: null });
1997
+ var NO_CALLER = Object.freeze({ principal: null, organization: null, labels: [] });
1808
1998
  function callerFor(result, warn3) {
1809
1999
  try {
1810
2000
  return readCaller(result, warn3);
@@ -1821,7 +2011,11 @@ function readCaller(result, warn3) {
1821
2011
  }
1822
2012
  if (!("principalId" in result) && !("organization" in result)) {
1823
2013
  if ("organizationId" in result) {
1824
- return { principal: null, organization: identityFor(result, "organization", warn3) };
2014
+ return {
2015
+ principal: null,
2016
+ organization: identityFor(result, "organization", warn3),
2017
+ labels: labelsOf([result], warn3)
2018
+ };
1825
2019
  }
1826
2020
  if (typeof result.userId === "string") {
1827
2021
  warn3(
@@ -1839,9 +2033,29 @@ function readCaller(result, warn3) {
1839
2033
  const nested = result.organization;
1840
2034
  return {
1841
2035
  principal: identityFor(result, "principal", warn3),
1842
- organization: nested == null ? null : identityFor(nested, "organization", warn3)
2036
+ organization: nested == null ? null : identityFor(nested, "organization", warn3),
2037
+ labels: labelsOf([result, nested], warn3)
1843
2038
  };
1844
2039
  }
2040
+ function labelsOf(sources, warn3) {
2041
+ const labels = [];
2042
+ for (const source of sources) {
2043
+ try {
2044
+ const given = source?.labels;
2045
+ if (typeof given === "string" || typeof given?.[Symbol.iterator] !== "function") {
2046
+ continue;
2047
+ }
2048
+ let read = 0;
2049
+ for (const label of given) {
2050
+ labels.push(label);
2051
+ if (++read === LABELS_READ_MAX) break;
2052
+ }
2053
+ } catch {
2054
+ warn3("labels", "labels could not be read \u2014 sending the ones read before the failure.");
2055
+ }
2056
+ }
2057
+ return cleanLabels(labels);
2058
+ }
1845
2059
  function identityFor(value, member, warn3) {
1846
2060
  const idKey = member === "principal" ? "principalId" : "organizationId";
1847
2061
  const identity = readIdentity(value, idKey);
@@ -1952,7 +2166,34 @@ function warnOnce(key, message) {
1952
2166
  warned.add(key);
1953
2167
  warn(`baton: resolvePrincipal ${message}`);
1954
2168
  }
1955
- async function resolveCaller(hook, call) {
2169
+ function callerEnvelope(caller) {
2170
+ return {
2171
+ principal: caller.principal,
2172
+ organization: caller.organization,
2173
+ labels: wireLabels(caller.labels),
2174
+ capture: caller.settings?.capture ?? null
2175
+ };
2176
+ }
2177
+ var settingsWarned = false;
2178
+ async function resolveCaller(hook, call, settings, client = null) {
2179
+ const caller = await resolveIdentity(hook, call);
2180
+ if (settings === void 0) return caller;
2181
+ try {
2182
+ const callSettings = settings.forCaller({
2183
+ labels: caller.labels,
2184
+ clientName: client?.info?.name ?? null,
2185
+ shareKey: caller.principal?.id ?? null
2186
+ });
2187
+ return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2188
+ } catch {
2189
+ if (!settingsWarned) {
2190
+ settingsWarned = true;
2191
+ warn("baton: applying capture settings failed; this request uses the config's values");
2192
+ }
2193
+ return caller;
2194
+ }
2195
+ }
2196
+ async function resolveIdentity(hook, call) {
1956
2197
  if (hook === void 0) return NO_CALLER;
1957
2198
  try {
1958
2199
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
@@ -2102,6 +2343,15 @@ function sessionIdFromHeader(extra) {
2102
2343
 
2103
2344
  // src/integrations/mcp/annotation.ts
2104
2345
  var TOOL_NAME_PARAM_NAME = "tool_name";
2346
+ var ANNOTATION_INPUT_SHAPE = {
2347
+ user_goal: import_zod2.z.string(),
2348
+ what_happened: import_zod2.z.string().optional(),
2349
+ // Nullable so a report whose agent sends an explicit null is taken,
2350
+ // not rejected by validation.
2351
+ tool_name: import_zod2.z.string().nullable().optional(),
2352
+ suggested_improvement: import_zod2.z.string().optional(),
2353
+ context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
2354
+ };
2105
2355
  function isReport(whatHappened) {
2106
2356
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2107
2357
  }
@@ -2110,19 +2360,12 @@ function registerAnnotationTool(server, options) {
2110
2360
  const description = buildAnnotationToolDescription({
2111
2361
  vendorDisplayName: options.vendorDisplayName
2112
2362
  });
2363
+ const refusal = buildRefusalText({ annotationToolName: name });
2113
2364
  server.registerTool(
2114
2365
  name,
2115
2366
  {
2116
2367
  description,
2117
- inputSchema: {
2118
- user_goal: import_zod2.z.string(),
2119
- what_happened: import_zod2.z.string().optional(),
2120
- // Nullable so a report whose agent sends an explicit null is taken,
2121
- // not rejected by validation.
2122
- tool_name: import_zod2.z.string().nullable().optional(),
2123
- suggested_improvement: import_zod2.z.string().optional(),
2124
- context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
2125
- }
2368
+ inputSchema: ANNOTATION_INPUT_SHAPE
2126
2369
  },
2127
2370
  async (args, extra) => {
2128
2371
  const whatHappened = args.what_happened;
@@ -2133,7 +2376,7 @@ function registerAnnotationTool(server, options) {
2133
2376
  type: "text",
2134
2377
  text: JSON.stringify({
2135
2378
  ok: false,
2136
- 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.`
2379
+ error: refusal
2137
2380
  })
2138
2381
  }
2139
2382
  ]
@@ -2147,9 +2390,12 @@ function registerAnnotationTool(server, options) {
2147
2390
  "_meta"
2148
2391
  );
2149
2392
  const session = await resolveSessionId(options.fallbackSessionId, extra);
2393
+ const client = observeClient(extra, { server, scrubber: options.scrubber });
2150
2394
  const caller = await resolveCaller(
2151
2395
  options.resolvePrincipal,
2152
- { extra, toolName: name, arguments: args }
2396
+ { extra, toolName: name, arguments: args },
2397
+ options.captureSettings,
2398
+ client
2153
2399
  );
2154
2400
  await emit(
2155
2401
  options.sink,
@@ -2160,11 +2406,10 @@ function registerAnnotationTool(server, options) {
2160
2406
  sequence_number: options.counter.nextFor(session),
2161
2407
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2162
2408
  consent_token: options.consentToken,
2163
- principal: caller.principal,
2164
- organization: caller.organization,
2409
+ ...callerEnvelope(caller),
2165
2410
  transport_observed: observeTransport(extra),
2166
2411
  session_id_origin: session.origin,
2167
- client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
2412
+ client_observed: client,
2168
2413
  runtime_meta: scrubbedMeta,
2169
2414
  payload: {
2170
2415
  // The agent-facing `user_goal` is stored as the wire key `intent`.
@@ -2457,10 +2702,195 @@ function scrubbedErrorBody(scrubber, text) {
2457
2702
  return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2458
2703
  }
2459
2704
 
2460
- // src/integrations/mcp/config.ts
2705
+ // src/integrations/mcp/captureSettings.ts
2706
+ var import_node_crypto2 = require("crypto");
2707
+ var SETTINGS_PATH = "/v0/settings";
2708
+ var TENANT_HEADER = "X-Baton-Tenant-Id";
2709
+ var SETTINGS_MODES = ["local", "console"];
2710
+ var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
2711
+ var MIN_SETTINGS_REFRESH_MS = 15e3;
2712
+ var REQUEST_TIMEOUT_MS = 1e4;
2713
+ var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
2461
2714
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2462
2715
  var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2463
2716
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2717
+ function shareBucket(vendorId2, key) {
2718
+ const digest = (0, import_node_crypto2.createHash)("sha256").update(`${vendorId2}
2719
+ ${key}`, "utf-8").digest();
2720
+ return Number(digest.readBigUInt64BE(0) % 10000n);
2721
+ }
2722
+ function matchesEveryone(audience) {
2723
+ return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
2724
+ }
2725
+ function matches(audience, caller, bucket) {
2726
+ if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
2727
+ if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
2728
+ return false;
2729
+ }
2730
+ if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
2731
+ return true;
2732
+ }
2733
+ var SettingsDocument = class {
2734
+ constructor(version, audiences) {
2735
+ this.version = version;
2736
+ this.audiences = audiences;
2737
+ this.usesShare = audiences.some((a) => a.shareThreshold !== null);
2738
+ this.unmatched = { capture: { settings_version: version } };
2739
+ this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
2740
+ }
2741
+ version;
2742
+ audiences;
2743
+ usesShare;
2744
+ unmatched;
2745
+ /** Whether some caller can get reports, so the instructions point to the
2746
+ * tool. Read only where the code's value is "on": no tool exists otherwise. */
2747
+ reportsOnForAnyone;
2748
+ settingsFor(caller, vendorId2) {
2749
+ const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
2750
+ return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
2751
+ }
2752
+ };
2753
+ function stringSet(value) {
2754
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
2755
+ return new Set(value);
2756
+ }
2757
+ function readAudience(version, id, match, capture) {
2758
+ if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
2759
+ let labels = null;
2760
+ let clients = null;
2761
+ let shareThreshold = null;
2762
+ if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
2763
+ if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
2764
+ if (Object.hasOwn(match, "share")) {
2765
+ const share = match.share;
2766
+ if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
2767
+ shareThreshold = Math.floor(share * 1e4 + 0.5);
2768
+ }
2769
+ const settings = { capture: { settings_version: version, audience: id } };
2770
+ const { results, goal, reports } = capture;
2771
+ if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
2772
+ settings.resultCaptureMode = results;
2773
+ }
2774
+ if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
2775
+ if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
2776
+ return { settings, labels, clients, shareThreshold };
2777
+ }
2778
+ function parseDocument(body) {
2779
+ let data;
2780
+ try {
2781
+ data = JSON.parse(body);
2782
+ } catch {
2783
+ return null;
2784
+ }
2785
+ if (!isRecord(data)) return null;
2786
+ const { version, audiences } = data;
2787
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
2788
+ if (!Array.isArray(audiences) || audiences.length === 0) return null;
2789
+ const parsed = [];
2790
+ for (const audience of audiences) {
2791
+ if (!isRecord(audience)) return null;
2792
+ const { id, match, capture } = audience;
2793
+ if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
2794
+ const readable = readAudience(version, id, match, capture);
2795
+ if (readable !== null) parsed.push(readable);
2796
+ }
2797
+ return new SettingsDocument(version, parsed);
2798
+ }
2799
+ var SettingsFetcher = class {
2800
+ url;
2801
+ // `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
2802
+ #headers;
2803
+ refreshMs;
2804
+ fetchImpl;
2805
+ etag = null;
2806
+ held = null;
2807
+ timer = null;
2808
+ reading = null;
2809
+ warned = false;
2810
+ constructor(options) {
2811
+ this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2812
+ this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2813
+ this.refreshMs = options.refreshMs;
2814
+ this.fetchImpl = options.fetchImpl ?? fetch;
2815
+ }
2816
+ get document() {
2817
+ return this.held;
2818
+ }
2819
+ start() {
2820
+ if (this.timer !== null) return;
2821
+ this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
2822
+ this.timer.unref?.();
2823
+ void this.readOnce();
2824
+ }
2825
+ stop() {
2826
+ if (this.timer !== null) clearInterval(this.timer);
2827
+ this.timer = null;
2828
+ this.reading?.abort();
2829
+ this.reading = null;
2830
+ }
2831
+ /** One request. Never rejects: a failure keeps what is held. */
2832
+ async readOnce() {
2833
+ if (this.reading !== null) return;
2834
+ const reading = new AbortController();
2835
+ this.reading = reading;
2836
+ const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
2837
+ timeout.unref?.();
2838
+ try {
2839
+ await this.read(reading.signal);
2840
+ } catch {
2841
+ } finally {
2842
+ clearTimeout(timeout);
2843
+ if (this.reading === reading) this.reading = null;
2844
+ }
2845
+ }
2846
+ async read(signal) {
2847
+ const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
2848
+ const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
2849
+ if (response.status !== 200) {
2850
+ void response.body?.cancel().catch(() => void 0);
2851
+ }
2852
+ if (signal.aborted) return;
2853
+ if (response.status === 204) {
2854
+ this.held = null;
2855
+ this.etag = null;
2856
+ } else if (response.status === 200) {
2857
+ const document = parseDocument(await response.text());
2858
+ if (signal.aborted) return;
2859
+ if (document === null) {
2860
+ if (!this.warned) {
2861
+ this.warned = true;
2862
+ warn("baton: the collector sent capture settings this SDK cannot read");
2863
+ }
2864
+ return;
2865
+ }
2866
+ this.held = document;
2867
+ this.etag = response.headers.get("etag");
2868
+ }
2869
+ }
2870
+ };
2871
+ var CaptureSettings = class {
2872
+ constructor(vendorId2, source) {
2873
+ this.vendorId = vendorId2;
2874
+ this.source = source;
2875
+ }
2876
+ vendorId;
2877
+ source;
2878
+ start() {
2879
+ this.source.start();
2880
+ }
2881
+ stop() {
2882
+ this.source.stop();
2883
+ }
2884
+ get document() {
2885
+ return this.source.document;
2886
+ }
2887
+ /** `undefined` while no document is held, and the config's values apply. */
2888
+ forCaller(caller) {
2889
+ return this.document?.settingsFor(caller, this.vendorId);
2890
+ }
2891
+ };
2892
+
2893
+ // src/integrations/mcp/config.ts
2464
2894
  function resolveTenantId(explicit, vendorId2) {
2465
2895
  if (explicit) return explicit;
2466
2896
  const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
@@ -2498,6 +2928,11 @@ function resolveBatonConfig(config) {
2498
2928
  consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
2499
2929
  };
2500
2930
  validateBatonConfig(defaulted);
2931
+ if (defaulted.settings === "console") {
2932
+ throw new Error(
2933
+ `BatonConfig.settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`
2934
+ );
2935
+ }
2501
2936
  return defaulted;
2502
2937
  }
2503
2938
  const dsn = parseDsn(dsnString);
@@ -2519,14 +2954,27 @@ function resolveBatonConfig(config) {
2519
2954
  // `??`, not `||`: an explicit empty string must survive to the validation
2520
2955
  // below and be REFUSED there, rather than be quietly replaced by the
2521
2956
  // default it was deliberately not left as.
2522
- consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
2957
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,
2958
+ ...config.reportMode === void 0 && config.settings === "console" ? { reportMode: "on" } : {}
2523
2959
  };
2524
2960
  validateBatonConfig(identity);
2525
2961
  return {
2526
2962
  ...identity,
2527
2963
  // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2528
2964
  // itself, exactly as it does for an explicitly-constructed sink.
2529
- sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2965
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
2966
+ ...identity.settings === "console" ? {
2967
+ captureSettings: new CaptureSettings(
2968
+ dsn.vendorId,
2969
+ new SettingsFetcher({
2970
+ origin: dsn.origin,
2971
+ apiKey: dsn.key,
2972
+ tenantId: dsn.tenantId,
2973
+ vendorId: dsn.vendorId,
2974
+ refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
2975
+ })
2976
+ )
2977
+ } : {}
2530
2978
  };
2531
2979
  }
2532
2980
  function withServerDisplayName(resolved, supplied, serverName) {
@@ -2591,6 +3039,17 @@ function validateBatonConfig(config) {
2591
3039
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
2592
3040
  );
2593
3041
  }
3042
+ if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3043
+ throw new Error(
3044
+ `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3045
+ );
3046
+ }
3047
+ const refresh = config.settingsRefreshMs;
3048
+ if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3049
+ throw new Error(
3050
+ `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3051
+ );
3052
+ }
2594
3053
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
2595
3054
  throw new Error("BatonConfig.scrubber must be a function.");
2596
3055
  }
@@ -2652,7 +3111,9 @@ function resumesPausedCall(extra) {
2652
3111
 
2653
3112
  // src/integrations/mcp/handle.ts
2654
3113
  var BatonHandle = class {
3114
+ /** The sink the vendor passed, or the default one. */
2655
3115
  sink;
3116
+ #queue;
2656
3117
  vendorId;
2657
3118
  /** The install's own session id: what stdio and in-memory calls, and the
2658
3119
  * surface snapshot, carry when no session id resolves. A call over HTTP
@@ -2664,6 +3125,7 @@ var BatonHandle = class {
2664
3125
  annotationToolName;
2665
3126
  constructor(options) {
2666
3127
  this.sink = options.sink;
3128
+ this.#queue = options.queue ?? options.sink;
2667
3129
  this.vendorId = options.vendorId;
2668
3130
  this.sessionId = options.sessionId;
2669
3131
  this.annotationToolName = options.annotationToolName;
@@ -2671,14 +3133,83 @@ var BatonHandle = class {
2671
3133
  /** Flush any pending events held by the sink. Never rejects; returns within
2672
3134
  * the shutdown budget (SPEC §11.2 rule 7). */
2673
3135
  async flush() {
2674
- await boundedSinkCall(this.sink, "flush");
3136
+ await boundedSinkCall(this.#queue, "flush");
2675
3137
  }
2676
3138
  /** Flush and release sink resources, on the same terms as `flush()`. */
2677
3139
  async aclose() {
2678
- await boundedSinkCall(this.sink, "aclose");
3140
+ await boundedSinkCall(this.#queue, "aclose");
2679
3141
  }
2680
3142
  };
2681
3143
 
3144
+ // src/integrations/mcp/perCaller.ts
3145
+ var PerCallerSurface = class {
3146
+ constructor(options) {
3147
+ this.options = options;
3148
+ }
3149
+ options;
3150
+ pointerOn = true;
3151
+ /** Called at install and on every request; writes only when the report
3152
+ * pointer should change. */
3153
+ followSettings() {
3154
+ if (this.options.annotationToolName === "") return;
3155
+ try {
3156
+ const document = this.options.settings.document;
3157
+ const pointerOn = document === null || document.reportsOnForAnyone;
3158
+ if (pointerOn === this.pointerOn) return;
3159
+ this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
3160
+ this.pointerOn = pointerOn;
3161
+ } catch (err) {
3162
+ process.stderr.write(`baton: could not update the server instructions for new settings: ${printable(err)}
3163
+ `);
3164
+ }
3165
+ }
3166
+ /** `result` with the caller's goal and reports settings; as served on any failure. */
3167
+ toolsFor(result, caller) {
3168
+ const settings = caller.settings;
3169
+ if (settings === void 0) return result;
3170
+ const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3171
+ const goal = settings.intentParamMode ?? intentParamMode;
3172
+ const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3173
+ if (goal === intentParamMode && !hideReports) return result;
3174
+ try {
3175
+ const tools = result?.tools;
3176
+ if (!Array.isArray(tools)) return result;
3177
+ const served = [];
3178
+ for (const tool of tools) {
3179
+ const name = tool?.name;
3180
+ if (hideReports && name === annotationToolName) continue;
3181
+ const rewrite = goal !== intentParamMode && typeof name === "string" && injectsGoal(name);
3182
+ served.push(rewrite ? withGoalMode(tool, goal) : tool);
3183
+ }
3184
+ return { ...result, tools: served };
3185
+ } catch (err) {
3186
+ process.stderr.write(`baton: could not apply capture settings to the tool list: ${printable(err)}
3187
+ `);
3188
+ return result;
3189
+ }
3190
+ }
3191
+ };
3192
+ function withGoalMode(tool, goal) {
3193
+ const entry = tool;
3194
+ const schema = entry.inputSchema;
3195
+ const properties = schema?.properties;
3196
+ const param = properties?.[USER_GOAL_PARAM_NAME];
3197
+ if (typeof param !== "object" || param === null) return tool;
3198
+ const others = Array.isArray(schema.required) ? schema.required.filter((name) => name !== USER_GOAL_PARAM_NAME) : [];
3199
+ const required = goal === "required" ? [...others, USER_GOAL_PARAM_NAME] : others;
3200
+ return {
3201
+ ...entry,
3202
+ inputSchema: {
3203
+ ...schema,
3204
+ properties: {
3205
+ ...properties,
3206
+ [USER_GOAL_PARAM_NAME]: { ...param, description: buildUserGoalParamDescription({ intentParamMode: goal }) }
3207
+ },
3208
+ ...required.length > 0 || Array.isArray(schema.required) ? { required } : {}
3209
+ }
3210
+ };
3211
+ }
3212
+
2682
3213
  // src/integrations/mcp/sessionCounter.ts
2683
3214
  var SESSION_CAP = 4096;
2684
3215
  var SessionCounter = class {
@@ -2791,16 +3322,16 @@ var import_zod3 = require("zod");
2791
3322
  var import_v3 = require("zod/v3");
2792
3323
  var DEFAULT_INTENT_PARAM_MODE = "required";
2793
3324
  var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
2794
- function injectGoalParams(inputSchema, intentParamMode) {
2795
- const objSchema = normalizeObjectSchema(inputSchema);
2796
- if (!objSchema) return { schema: inputSchema, dispositions: {} };
3325
+ function injectGoalParams(inputSchema2, intentParamMode) {
3326
+ const objSchema = normalizeObjectSchema(inputSchema2);
3327
+ if (!objSchema) return { schema: inputSchema2, dispositions: {} };
2797
3328
  const existingShape = getObjectShape(objSchema) ?? {};
2798
3329
  const values = Object.values(existingShape);
2799
3330
  const useV4 = values.length === 0 || isZ4Schema(values[0]);
2800
3331
  const zodImpl = useV4 ? import_zod3.z : import_v3.z;
2801
3332
  const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
2802
3333
  if (Object.keys(toInject).length === 0)
2803
- return { schema: inputSchema, dispositions };
3334
+ return { schema: inputSchema2, dispositions };
2804
3335
  const mergedShape = { ...existingShape, ...toInject };
2805
3336
  const newSchema = objectFromShape(mergedShape);
2806
3337
  return { schema: newSchema, dispositions };
@@ -2819,15 +3350,15 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
2819
3350
  }
2820
3351
  return { dispositions, toInject };
2821
3352
  }
2822
- function injectGoalParamsV2(inputSchema, intentParamMode) {
2823
- const candidate = inputSchema;
3353
+ function injectGoalParamsV2(inputSchema2, intentParamMode) {
3354
+ const candidate = inputSchema2;
2824
3355
  const shape = candidate?.shape;
2825
3356
  if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
2826
- return { schema: inputSchema, dispositions: {} };
3357
+ return { schema: inputSchema2, dispositions: {} };
2827
3358
  }
2828
3359
  const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
2829
3360
  if (Object.keys(toInject).length === 0)
2830
- return { schema: inputSchema, dispositions };
3361
+ return { schema: inputSchema2, dispositions };
2831
3362
  return { schema: candidate.extend(toInject), dispositions };
2832
3363
  }
2833
3364
  function advertiseIntentParamsRequired(result, names, isInjected) {
@@ -2850,8 +3381,8 @@ function advertiseIntentParamsRequired(result, names, isInjected) {
2850
3381
  });
2851
3382
  return changed ? { ...result, tools: advertised } : result;
2852
3383
  }
2853
- function toolInputJsonSchema(inputSchema) {
2854
- const objSchema = normalizeObjectSchema(inputSchema);
3384
+ function toolInputJsonSchema(inputSchema2) {
3385
+ const objSchema = normalizeObjectSchema(inputSchema2);
2855
3386
  if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
2856
3387
  return toJsonSchemaCompat(objSchema, {
2857
3388
  strictUnions: true,
@@ -2860,10 +3391,10 @@ function toolInputJsonSchema(inputSchema) {
2860
3391
  }
2861
3392
 
2862
3393
  // src/integrations/mcp/surface.ts
2863
- var import_node_crypto2 = require("crypto");
3394
+ var import_node_crypto3 = require("crypto");
2864
3395
  function surfaceHash(surface) {
2865
3396
  const canonical = canonicalJson(surface);
2866
- const digest = (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf-8").digest("hex");
3397
+ const digest = (0, import_node_crypto3.createHash)("sha256").update(canonical, "utf-8").digest("hex");
2867
3398
  return `sha256:${digest}`;
2868
3399
  }
2869
3400
  function canonicalJson(value) {
@@ -2907,9 +3438,6 @@ var SentSurfaces = class {
2907
3438
  this.hashes.delete(this.hashes.values().next().value);
2908
3439
  }
2909
3440
  }
2910
- unmark(digest) {
2911
- this.hashes.delete(digest);
2912
- }
2913
3441
  };
2914
3442
  function buildSeamAugmentations(options) {
2915
3443
  return {
@@ -2999,10 +3527,14 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
2999
3527
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
3000
3528
  (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3001
3529
  );
3530
+ const client = observeClient(extra, ctx);
3002
3531
  const caller = await resolveCaller(
3003
3532
  ctx.resolvePrincipal,
3004
- { extra, toolName, arguments: params }
3533
+ { extra, toolName, arguments: params },
3534
+ ctx.captureSettings,
3535
+ client
3005
3536
  );
3537
+ const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
3006
3538
  const common = {
3007
3539
  tenant_id: ctx.tenantId,
3008
3540
  vendor_id: ctx.vendorId,
@@ -3012,15 +3544,14 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3012
3544
  // it. `surface_snapshot` is deliberately not among them: it describes the
3013
3545
  // SERVER and is captured outside any call, so it has no caller, transport
3014
3546
  // or client to name.
3015
- principal: caller.principal,
3016
- organization: caller.organization,
3547
+ ...callerEnvelope(caller),
3017
3548
  transport_observed: observeTransport(extra),
3018
3549
  session_id_origin: session.origin,
3019
- client_observed: observeClient(extra, ctx),
3550
+ client_observed: client,
3020
3551
  runtime_meta: scrubbedMeta,
3021
3552
  call_id: uuid7()
3022
3553
  };
3023
- if (resumesPausedCall(extra)) return { common, session };
3554
+ if (resumesPausedCall(extra)) return { common, session, resultCaptureMode };
3024
3555
  await emit(
3025
3556
  ctx.sink,
3026
3557
  () => ToolCallStartEventSchema.parse({
@@ -3038,7 +3569,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3038
3569
  }
3039
3570
  })
3040
3571
  );
3041
- return { common, session };
3572
+ return { common, session, resultCaptureMode };
3042
3573
  }
3043
3574
  function batonWrap(nameRef, original, ctx) {
3044
3575
  return async (...callArgs) => {
@@ -3049,7 +3580,7 @@ function batonWrap(nameRef, original, ctx) {
3049
3580
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3050
3581
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3051
3582
  if (slot) slot.strippedFor = null;
3052
- const { common, session } = await openCall(ctx, toolName, extra, params, stripped);
3583
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
3053
3584
  const terminate = async (build, replacement) => {
3054
3585
  if (!slot) {
3055
3586
  if (build !== null) await emit(ctx.sink, build);
@@ -3082,7 +3613,7 @@ function batonWrap(nameRef, original, ctx) {
3082
3613
  // SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
3083
3614
  // raised message public, so under "off" every one is withheld.
3084
3615
  ...resultDerivedFields(
3085
- ctx.resultCaptureMode,
3616
+ resultCaptureMode,
3086
3617
  () => messageOf(err),
3087
3618
  null,
3088
3619
  (text) => errorBody(ctx, text),
@@ -3142,7 +3673,7 @@ function batonWrap(nameRef, original, ctx) {
3142
3673
  // nothing on the wire has; the loss is deliberate and worth
3143
3674
  // knowing when debugging one of these.
3144
3675
  ...resultDerivedFields(
3145
- ctx.resultCaptureMode,
3676
+ resultCaptureMode,
3146
3677
  () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
3147
3678
  // ⚠ `null` on the `raised` lane, never `undefined`, and the
3148
3679
  // union is what forces the branch rather than a comment: the
@@ -3181,7 +3712,7 @@ function batonWrap(nameRef, original, ctx) {
3181
3712
  // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
3182
3713
  // names the test that enforces it.
3183
3714
  ...returnedErrorFields(
3184
- ctx.resultCaptureMode,
3715
+ resultCaptureMode,
3185
3716
  result,
3186
3717
  (text) => errorBody(ctx, text),
3187
3718
  ctx.scrubber
@@ -3199,7 +3730,7 @@ function batonWrap(nameRef, original, ctx) {
3199
3730
  payload: {
3200
3731
  tool_name: toolName,
3201
3732
  duration_ms: durationMs,
3202
- ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
3733
+ ...endResultFields(resultCaptureMode, result, ctx.scrubber)
3203
3734
  }
3204
3735
  }),
3205
3736
  (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
@@ -3262,14 +3793,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3262
3793
  requiredParamNames: requiredParamNames(ctx.intentParamMode),
3263
3794
  instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
3264
3795
  });
3265
- try {
3266
- await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
3267
- } catch (err) {
3268
- process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
3269
- `);
3270
- sent.unmark(digest);
3271
- ctx.surfaceState.dirty = true;
3272
- }
3796
+ await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
3273
3797
  }
3274
3798
  function declaredIntentParams(vendorSchema) {
3275
3799
  const declared2 = {};
@@ -3352,6 +3876,7 @@ var LIFECYCLE_SEAMS = {
3352
3876
  };
3353
3877
  function installLifecycleSeam(lowLevel, ctx, spec) {
3354
3878
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
3879
+ ctx.perCaller?.followSettings();
3355
3880
  const request = args[0];
3356
3881
  const requestParams = request?.params ?? {};
3357
3882
  const extra = args[1];
@@ -3372,8 +3897,9 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3372
3897
  const startedAt = performance.now();
3373
3898
  const elapsed = () => Math.round(performance.now() - startedAt);
3374
3899
  try {
3375
- const result = await handler(...args);
3376
- if (isInputRequired(result)) return result;
3900
+ const served = await handler(...args);
3901
+ if (isInputRequired(served)) return served;
3902
+ const result = opened !== null && spec.rewriteResult !== void 0 ? spec.rewriteResult(ctx, served, opened.caller) : served;
3377
3903
  await fire(spec.schemas.end, {
3378
3904
  ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
3379
3905
  duration_ms: elapsed()
@@ -3395,24 +3921,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3395
3921
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
3396
3922
  try {
3397
3923
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3398
- const caller = await resolveCaller(ctx.resolvePrincipal, {
3399
- extra,
3400
- toolName: null,
3401
- arguments: {}
3402
- });
3924
+ const client = observeClient(extra, ctx);
3925
+ const caller = await resolveCaller(
3926
+ ctx.resolvePrincipal,
3927
+ { extra, toolName: null, arguments: {} },
3928
+ ctx.captureSettings,
3929
+ client
3930
+ );
3403
3931
  return {
3404
3932
  session,
3933
+ caller,
3405
3934
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
3406
3935
  common: {
3407
3936
  tenant_id: ctx.tenantId,
3408
3937
  vendor_id: ctx.vendorId,
3409
3938
  session_id: session.sessionId,
3410
3939
  consent_token: ctx.consentToken,
3411
- principal: caller.principal,
3412
- organization: caller.organization,
3940
+ ...callerEnvelope(caller),
3413
3941
  transport_observed: observeTransport(extra),
3414
3942
  session_id_origin: session.origin,
3415
- client_observed: observeClient(extra, ctx),
3943
+ client_observed: client,
3416
3944
  runtime_meta: scrubbedMeta
3417
3945
  }
3418
3946
  };
@@ -3495,7 +4023,8 @@ var LIFECYCLE_SPECS = [
3495
4023
  error: ToolListErrorEventSchema
3496
4024
  },
3497
4025
  countKey: "tools",
3498
- startParams: NO_PARAMS
4026
+ startParams: NO_PARAMS,
4027
+ rewriteResult: (ctx, result, caller) => ctx.perCaller?.toolsFor(result, caller) ?? result
3499
4028
  }
3500
4029
  ];
3501
4030
  function installLifecycleSeams(lowLevel, ctx) {
@@ -3537,6 +4066,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
3537
4066
  TOOLS_CALL_METHOD,
3538
4067
  TOOLS_CALL_SEAM,
3539
4068
  (handler) => async (...args) => {
4069
+ ctx.perCaller?.followSettings();
3540
4070
  const request = args[0];
3541
4071
  const name = request?.params?.name;
3542
4072
  const slot = {
@@ -3604,7 +4134,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3604
4134
  const entry = toolEntry(toolName);
3605
4135
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
3606
4136
  const params = { ...request?.params?.arguments ?? {} };
3607
- const { common, session } = await openCall(
4137
+ const { common, session, resultCaptureMode } = await openCall(
3608
4138
  ctx,
3609
4139
  toolName,
3610
4140
  args[1],
@@ -3647,7 +4177,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3647
4177
  ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3648
4178
  ...requestSideFailureFields(
3649
4179
  failureKind,
3650
- ctx.resultCaptureMode,
4180
+ resultCaptureMode,
3651
4181
  text,
3652
4182
  outcome.raised ? null : outcome.result,
3653
4183
  (value) => errorBody(ctx, value),
@@ -3724,8 +4254,28 @@ function withBaton(server, supplied = {}) {
3724
4254
  const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);
3725
4255
  if (unconfigured) logUnconfigured("withBaton");
3726
4256
  else warnAboutSettings(resolved);
3727
- return handle;
3728
- }
4257
+ const settings = resolved.captureSettings;
4258
+ if (settings === void 0) return handle;
4259
+ settings.start();
4260
+ return new SettingsHandle(handle, settings);
4261
+ }
4262
+ var SettingsHandle = class extends BatonHandle {
4263
+ constructor(inner, settings) {
4264
+ super(inner);
4265
+ this.inner = inner;
4266
+ this.settings = settings;
4267
+ }
4268
+ inner;
4269
+ settings;
4270
+ // The inner handle holds the queue in front of the sink.
4271
+ flush() {
4272
+ return this.inner.flush();
4273
+ }
4274
+ async aclose() {
4275
+ this.settings.stop();
4276
+ await this.inner.aclose();
4277
+ }
4278
+ };
3729
4279
  function createBaton(supplied = {}) {
3730
4280
  const disabledBy = captureDisabled();
3731
4281
  if (disabledBy !== null) {
@@ -3742,19 +4292,23 @@ function createBaton(supplied = {}) {
3742
4292
  if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
3743
4293
  if (unconfigured) logUnconfigured("createBaton");
3744
4294
  else warnAboutSettings(resolved);
3745
- const sink = unconfigured ? new DisabledSink() : resolved.sink ?? new StdoutSink();
4295
+ const sink = unconfigured ? new DisabledSink() : offTheCall(resolved.sink ?? new StdoutSink());
3746
4296
  const config = {
3747
4297
  ...resolved,
3748
4298
  sink,
3749
4299
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
3750
4300
  };
3751
4301
  const state = newBatonState(resolved);
4302
+ resolved.captureSettings?.start();
3752
4303
  return {
3753
4304
  wrap: (server) => {
3754
4305
  install(server, supplied, config, state, unconfigured);
3755
4306
  },
3756
4307
  flush: () => boundedSinkCall(sink, "flush"),
3757
- aclose: () => boundedSinkCall(sink, "aclose")
4308
+ aclose: () => {
4309
+ resolved.captureSettings?.stop();
4310
+ return boundedSinkCall(sink, "aclose");
4311
+ }
3758
4312
  };
3759
4313
  }
3760
4314
  function inertHandle(sink, sessionId) {
@@ -3788,7 +4342,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3788
4342
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
3789
4343
  const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3790
4344
  if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
3791
- const sink = config.sink ?? new StdoutSink();
4345
+ const given = config.sink ?? new StdoutSink();
4346
+ const sink = offTheCall(given);
3792
4347
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
3793
4348
  const fallbackSessionId = `sdk-${uuid7()}`;
3794
4349
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
@@ -3796,29 +4351,26 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3796
4351
  const serverMeta = buildServerMeta(server.server);
3797
4352
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
3798
4353
  const emitSurface = async (sessionId, digest, snapshot) => {
3799
- const event = SurfaceSnapshotEventSchema.parse({
3800
- tenant_id: tenantId,
3801
- vendor_id: config.vendorId,
3802
- session_id: sessionId,
3803
- session_id_origin: "minted",
3804
- consent_token: config.consentToken,
3805
- sequence_number: counter2.next(sessionId, false),
3806
- captured_at: (/* @__PURE__ */ new Date()).toISOString(),
3807
- payload: {
3808
- surface_hash: digest,
3809
- server_info: snapshot.server_info,
3810
- capabilities: snapshot.capabilities,
3811
- instructions: snapshot.instructions,
3812
- tools: snapshot.tools,
3813
- seam_augmentations: snapshot.seam_augmentations
3814
- }
3815
- });
3816
- try {
3817
- await sink.write(event);
3818
- } catch (err) {
3819
- if (isSinkClosed(err)) return droppedAfterClose(sink);
3820
- throw err;
3821
- }
4354
+ await emit(
4355
+ sink,
4356
+ () => SurfaceSnapshotEventSchema.parse({
4357
+ tenant_id: tenantId,
4358
+ vendor_id: config.vendorId,
4359
+ session_id: sessionId,
4360
+ session_id_origin: "minted",
4361
+ consent_token: config.consentToken,
4362
+ sequence_number: counter2.next(sessionId, false),
4363
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
4364
+ payload: {
4365
+ surface_hash: digest,
4366
+ server_info: snapshot.server_info,
4367
+ capabilities: snapshot.capabilities,
4368
+ instructions: snapshot.instructions,
4369
+ tools: snapshot.tools,
4370
+ seam_augmentations: snapshot.seam_augmentations
4371
+ }
4372
+ })
4373
+ );
3822
4374
  };
3823
4375
  const bustSchemaMemo = (name) => {
3824
4376
  const memo = internals._toolInputSchemaJson;
@@ -3845,7 +4397,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3845
4397
  );
3846
4398
  };
3847
4399
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
3848
- const vendorToolJsonSchema = (name, inputSchema) => {
4400
+ const vendorToolJsonSchema = (name, inputSchema2) => {
3849
4401
  if (isV2Server) {
3850
4402
  try {
3851
4403
  const json = internals.toolInputSchemaJson(name);
@@ -3853,14 +4405,14 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3853
4405
  } catch {
3854
4406
  }
3855
4407
  try {
3856
- const standard = inputSchema?.["~standard"];
4408
+ const standard = inputSchema2?.["~standard"];
3857
4409
  const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
3858
4410
  if (json) return json;
3859
4411
  } catch {
3860
4412
  }
3861
4413
  }
3862
4414
  try {
3863
- return toolInputJsonSchema(inputSchema);
4415
+ return toolInputJsonSchema(inputSchema2);
3864
4416
  } catch {
3865
4417
  return { type: "object", properties: {} };
3866
4418
  }
@@ -3877,9 +4429,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3877
4429
  scrubber,
3878
4430
  annotationToolName,
3879
4431
  intentParamMode,
3880
- resultCaptureMode: config.resultCaptureMode ?? "full",
4432
+ configResultCaptureMode: config.resultCaptureMode ?? "full",
3881
4433
  paramRegistry: /* @__PURE__ */ new Map(),
3882
4434
  resolvePrincipal: config.resolvePrincipal,
4435
+ captureSettings: config.captureSettings,
4436
+ perCaller: void 0,
3883
4437
  vendorToolJsonSchema,
3884
4438
  bustSchemaMemo,
3885
4439
  dropSubagentClause,
@@ -3887,11 +4441,29 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3887
4441
  surfaceState,
3888
4442
  emitSurface
3889
4443
  };
3890
- internals.server._instructions = withVendorInstructions(
3891
- internals.server,
3892
- ours,
3893
- (message) => warnOnce2("instructions-length", message)
3894
- );
4444
+ const writeInstructions = (text) => {
4445
+ internals.server._instructions = withVendorInstructions(
4446
+ internals.server,
4447
+ text,
4448
+ (message) => warnOnce2("instructions-length", message)
4449
+ );
4450
+ };
4451
+ writeInstructions(ours);
4452
+ if (config.captureSettings !== void 0) {
4453
+ ctx.perCaller = new PerCallerSurface({
4454
+ settings: config.captureSettings,
4455
+ intentParamMode,
4456
+ annotationToolName,
4457
+ instructions: ours,
4458
+ writeInstructions: (text) => {
4459
+ writeInstructions(text);
4460
+ const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4461
+ if (native !== void 0) dropSubagentClause(native[0]);
4462
+ },
4463
+ injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4464
+ });
4465
+ ctx.perCaller.followSettings();
4466
+ }
3895
4467
  installToolsListSeam(internals.server, ctx);
3896
4468
  installToolsCallSeam(
3897
4469
  internals.server,
@@ -3917,6 +4489,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3917
4489
  vendorDisplayName: reports.vendorDisplayName,
3918
4490
  consentToken: ctx.consentToken,
3919
4491
  resolvePrincipal: ctx.resolvePrincipal,
4492
+ captureSettings: ctx.captureSettings,
3920
4493
  fallbackSessionId: ctx.fallbackSessionId,
3921
4494
  scrubber: ctx.scrubber,
3922
4495
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -3937,7 +4510,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3937
4510
  return registered;
3938
4511
  };
3939
4512
  return new BatonHandle({
3940
- sink,
4513
+ sink: given,
4514
+ queue: sink,
3941
4515
  vendorId: config.vendorId,
3942
4516
  sessionId: fallbackSessionId,
3943
4517
  annotationToolName: resolvedAnnotationToolName
@@ -4003,6 +4577,7 @@ function sessionEnvelope(session) {
4003
4577
  transport_observed: TRANSPORT_LIBRARY,
4004
4578
  principal: session.principal,
4005
4579
  organization: session.organization,
4580
+ labels: wireLabels(session.labels),
4006
4581
  client_observed: session.clientObserved,
4007
4582
  runtime_meta: session.runtimeMeta
4008
4583
  };
@@ -4201,10 +4776,8 @@ function paramsOf(args) {
4201
4776
  }
4202
4777
  var Core = class {
4203
4778
  closed = false;
4204
- pending = /* @__PURE__ */ new Set();
4205
- closedWarned = false;
4206
4779
  // A snapshot describes the server, so it takes no block's session,
4207
- // principal or client: SPEC §11.5.1's join must not count it.
4780
+ // principal or client (SPEC §5.6 rule 7).
4208
4781
  surfaceSessionId = uuid7();
4209
4782
  sentSurfaces = new SentSurfaces();
4210
4783
  sink;
@@ -4215,7 +4788,7 @@ var Core = class {
4215
4788
  scrubber;
4216
4789
  disabled;
4217
4790
  constructor(resolved) {
4218
- this.sink = resolved.sink;
4791
+ this.sink = offTheCall(resolved.sink);
4219
4792
  this.vendorId = resolved.vendorId;
4220
4793
  this.tenantId = resolved.tenantId;
4221
4794
  this.consentToken = resolved.consentToken;
@@ -4239,25 +4812,15 @@ var Core = class {
4239
4812
  live() {
4240
4813
  if (this.disabled) return false;
4241
4814
  if (!this.closed) return true;
4242
- PROCESS_DROPS.add("after_close");
4243
- if (!this.closedWarned) {
4244
- this.closedWarned = true;
4245
- process.stderr.write("baton: Client is closed; further events are dropped.\n");
4246
- }
4815
+ droppedAfterClose(this.sink);
4247
4816
  return false;
4248
4817
  }
4249
- /** Never rejects. Tracked so `flush()` can wait for it. */
4818
+ /** Never rejects. */
4250
4819
  emit(build) {
4251
- return this.track(emit(this.sink, build));
4252
- }
4253
- track(work) {
4254
- const tracked = work.finally(() => this.pending.delete(tracked));
4255
- this.pending.add(tracked);
4256
- return tracked;
4820
+ return emit(this.sink, build);
4257
4821
  }
4258
- /** Sends `surface` unless this client already has. Never rejects; a failed
4259
- * write unmarks it, so the next `listTools` tries again. A surface that does
4260
- * not fit the schema stays marked: it would fail the same way every time. */
4822
+ /** Sends `surface` unless this client already has. Never rejects. The
4823
+ * write only queues, so a surface counts as sent once queued. */
4261
4824
  sendSurface(surface) {
4262
4825
  if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
4263
4826
  this.sentSurfaces.mark(surface.digest);
@@ -4279,32 +4842,7 @@ var Core = class {
4279
4842
  `);
4280
4843
  return Promise.resolve();
4281
4844
  }
4282
- return this.track(
4283
- (async () => {
4284
- try {
4285
- await this.sink.write(event);
4286
- } catch (err) {
4287
- if (isSinkClosed(err)) return droppedAfterClose(this.sink);
4288
- process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
4289
- `);
4290
- this.sentSurfaces.unmark(surface.digest);
4291
- }
4292
- })()
4293
- );
4294
- }
4295
- /** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
4296
- * also for ones emitted while it waits. A write still pending when time runs
4297
- * out is not waited on again, so one stuck write costs one wait. */
4298
- async settleWithin(ms, untilEmpty) {
4299
- const deadline = performance.now() + ms;
4300
- do {
4301
- const waiting = [...this.pending];
4302
- if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
4303
- const left = waiting.filter((write) => this.pending.delete(write));
4304
- if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
4305
- return;
4306
- }
4307
- } while (untilEmpty && this.pending.size > 0);
4845
+ return safeWrite(this.sink, event);
4308
4846
  }
4309
4847
  scrub(value, field) {
4310
4848
  return scrubOrNull(this.scrubber, value, field);
@@ -4575,94 +5113,82 @@ var Client = class {
4575
5113
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
4576
5114
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
4577
5115
  async flush() {
4578
- await this.#settleThen("flush");
5116
+ await boundedSinkCall(this.#core.sink, "flush");
4579
5117
  }
4580
5118
  /** Flush, then close the sink. Later events are dropped. */
4581
5119
  aclose() {
4582
- this.#closing ??= this.#settleThen("aclose");
4583
- return this.#closing;
4584
- }
4585
- /** One budget: events in flight get until its end to reach the sink, then
4586
- * the sink gets the time left. */
4587
- async #settleThen(method) {
4588
- await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
4589
- const deadline = performance.now() + budgetMs;
4590
- await this.#core.settleWithin(budgetMs, method === "aclose");
4591
- if (method === "aclose") this.#core.closed = true;
4592
- await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
5120
+ this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5121
+ this.#core.closed = true;
4593
5122
  });
5123
+ return this.#closing;
4594
5124
  }
4595
5125
  };
5126
+
5127
+ // src/library/reportTool.ts
5128
+ function inputSchema() {
5129
+ const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5130
+ delete schema.$schema;
5131
+ return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5132
+ }
5133
+ var nonEmptyText = (value) => typeof value === "string" && value !== "";
5134
+ var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5135
+ function annotateArgs(args) {
5136
+ const whatHappened = args.what_happened;
5137
+ if (!isReport(whatHappened)) return null;
5138
+ const options = { whatHappened };
5139
+ const toolName = args[TOOL_NAME_PARAM_NAME];
5140
+ if (typeof toolName === "string") options.toolName = toolName;
5141
+ const intent = args[USER_GOAL_PARAM_NAME];
5142
+ if (nonEmptyText(intent)) options.intent = intent;
5143
+ if (nonEmptyText(args.suggested_improvement)) {
5144
+ options.suggestedImprovement = args.suggested_improvement;
5145
+ }
5146
+ if (nonEmptyObject(args.context)) options.context = args.context;
5147
+ return options;
5148
+ }
5149
+ function reportTool(options) {
5150
+ const { vendorDisplayName } = options;
5151
+ const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5152
+ if (derived === void 0) {
5153
+ throw new Error(
5154
+ `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for the instructions. Pass name.`
5155
+ );
5156
+ }
5157
+ const name = validateAnnotationToolName(derived);
5158
+ if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {
5159
+ throw new Error(
5160
+ `vendorDisplayName and name ${JSON.stringify(name)} are too long together for the instructions. Shorten one of them.`
5161
+ );
5162
+ }
5163
+ return {
5164
+ name,
5165
+ description: buildAnnotationToolDescription({ vendorDisplayName }),
5166
+ inputSchema: inputSchema(),
5167
+ instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5168
+ refusal: buildRefusalText({ annotationToolName: name }),
5169
+ annotateArgs
5170
+ };
5171
+ }
4596
5172
  // Annotate the CommonJS export names for ESM import in node:
4597
5173
  0 && (module.exports = {
4598
- AnnotationEventSchema,
4599
- AnnotationPayloadSchema,
4600
5174
  BatonHandle,
4601
5175
  Client,
4602
- ClientReportEventSchema,
4603
- ClientReportPayloadSchema,
4604
- DEFAULT_CONSENT_TOKEN,
4605
- DEPTH_LIMIT,
4606
- DEPTH_MARKER,
4607
5176
  EventSchema,
4608
- EventTypeSchema,
4609
5177
  FileSink,
4610
5178
  HttpSink,
4611
5179
  INTENT_INSTRUCTIONS,
4612
5180
  INTENT_PARAMS,
4613
5181
  MultiSink,
4614
- PRINCIPAL_FORM_HASHED,
4615
- PRINCIPAL_FORM_RAW,
4616
- PRINCIPAL_SOURCE_ASSERTED,
4617
- PrincipalWireSchema,
4618
- PromptGetEndEventSchema,
4619
- PromptGetEndPayloadSchema,
4620
- PromptGetErrorEventSchema,
4621
- PromptGetErrorPayloadSchema,
4622
- PromptGetStartEventSchema,
4623
- PromptGetStartPayloadSchema,
4624
- PromptListEndEventSchema,
4625
- PromptListEndPayloadSchema,
4626
- PromptListErrorEventSchema,
4627
- PromptListErrorPayloadSchema,
4628
- PromptListStartEventSchema,
4629
- PromptListStartPayloadSchema,
4630
- ResourceListEndEventSchema,
4631
- ResourceListEndPayloadSchema,
4632
- ResourceListErrorEventSchema,
4633
- ResourceListErrorPayloadSchema,
4634
- ResourceListStartEventSchema,
4635
- ResourceListStartPayloadSchema,
4636
- ResourceReadEndEventSchema,
4637
- ResourceReadEndPayloadSchema,
4638
- ResourceReadErrorEventSchema,
4639
- ResourceReadErrorPayloadSchema,
4640
- ResourceReadStartEventSchema,
4641
- ResourceReadStartPayloadSchema,
4642
5182
  SDK_VERSION,
4643
5183
  Scrubber,
4644
5184
  SinkClosedError,
4645
5185
  StdoutSink,
4646
- SurfaceSnapshotEventSchema,
4647
- SurfaceSnapshotPayloadSchema,
4648
- ToolCallEndEventSchema,
4649
- ToolCallEndPayloadSchema,
4650
- ToolCallErrorEventSchema,
4651
- ToolCallErrorPayloadSchema,
4652
- ToolCallStartEventSchema,
4653
- ToolCallStartPayloadSchema,
4654
- ToolListEndEventSchema,
4655
- ToolListEndPayloadSchema,
4656
- ToolListErrorEventSchema,
4657
- ToolListErrorPayloadSchema,
4658
- ToolListStartEventSchema,
4659
- ToolListStartPayloadSchema,
4660
5186
  Trace,
4661
5187
  createBaton,
4662
5188
  identityScrub,
4663
5189
  principalFromOAuthEmail,
4664
5190
  principalFromOAuthSub,
4665
- safeWrite,
5191
+ reportTool,
4666
5192
  withBaton
4667
5193
  });
4668
5194
  //# sourceMappingURL=index.cjs.map