@goodtiming/baton-sdk 0.6.7 → 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.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.7";
56
+ var SDK_VERSION = "ts-1.0.0";
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,35 @@ 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 identity = caller.principal ?? caller.organization;
2183
+ const callSettings = settings.forCaller({
2184
+ labels: caller.labels,
2185
+ clientName: client?.info?.name ?? null,
2186
+ shareKey: identity?.id ?? null
2187
+ });
2188
+ return callSettings === void 0 ? caller : { ...caller, settings: callSettings };
2189
+ } catch {
2190
+ if (!settingsWarned) {
2191
+ settingsWarned = true;
2192
+ warn("baton: applying capture settings failed; this request uses the config's values");
2193
+ }
2194
+ return caller;
2195
+ }
2196
+ }
2197
+ async function resolveIdentity(hook, call) {
1956
2198
  if (hook === void 0) return NO_CALLER;
1957
2199
  try {
1958
2200
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
@@ -2102,6 +2344,15 @@ function sessionIdFromHeader(extra) {
2102
2344
 
2103
2345
  // src/integrations/mcp/annotation.ts
2104
2346
  var TOOL_NAME_PARAM_NAME = "tool_name";
2347
+ var ANNOTATION_INPUT_SHAPE = {
2348
+ user_goal: import_zod2.z.string(),
2349
+ what_happened: import_zod2.z.string().optional(),
2350
+ // Nullable so a report whose agent sends an explicit null is taken,
2351
+ // not rejected by validation.
2352
+ tool_name: import_zod2.z.string().nullable().optional(),
2353
+ suggested_improvement: import_zod2.z.string().optional(),
2354
+ context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
2355
+ };
2105
2356
  function isReport(whatHappened) {
2106
2357
  return typeof whatHappened === "string" && !isBlank(whatHappened);
2107
2358
  }
@@ -2110,19 +2361,12 @@ function registerAnnotationTool(server, options) {
2110
2361
  const description = buildAnnotationToolDescription({
2111
2362
  vendorDisplayName: options.vendorDisplayName
2112
2363
  });
2364
+ const refusal = buildRefusalText({ annotationToolName: name });
2113
2365
  server.registerTool(
2114
2366
  name,
2115
2367
  {
2116
2368
  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
- }
2369
+ inputSchema: ANNOTATION_INPUT_SHAPE
2126
2370
  },
2127
2371
  async (args, extra) => {
2128
2372
  const whatHappened = args.what_happened;
@@ -2133,7 +2377,7 @@ function registerAnnotationTool(server, options) {
2133
2377
  type: "text",
2134
2378
  text: JSON.stringify({
2135
2379
  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.`
2380
+ error: refusal
2137
2381
  })
2138
2382
  }
2139
2383
  ]
@@ -2147,9 +2391,12 @@ function registerAnnotationTool(server, options) {
2147
2391
  "_meta"
2148
2392
  );
2149
2393
  const session = await resolveSessionId(options.fallbackSessionId, extra);
2394
+ const client = observeClient(extra, { server, scrubber: options.scrubber });
2150
2395
  const caller = await resolveCaller(
2151
2396
  options.resolvePrincipal,
2152
- { extra, toolName: name, arguments: args }
2397
+ { extra, toolName: name, arguments: args },
2398
+ options.captureSettings,
2399
+ client
2153
2400
  );
2154
2401
  await emit(
2155
2402
  options.sink,
@@ -2160,11 +2407,10 @@ function registerAnnotationTool(server, options) {
2160
2407
  sequence_number: options.counter.nextFor(session),
2161
2408
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2162
2409
  consent_token: options.consentToken,
2163
- principal: caller.principal,
2164
- organization: caller.organization,
2410
+ ...callerEnvelope(caller),
2165
2411
  transport_observed: observeTransport(extra),
2166
2412
  session_id_origin: session.origin,
2167
- client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
2413
+ client_observed: client,
2168
2414
  runtime_meta: scrubbedMeta,
2169
2415
  payload: {
2170
2416
  // The agent-facing `user_goal` is stored as the wire key `intent`.
@@ -2457,10 +2703,195 @@ function scrubbedErrorBody(scrubber, text) {
2457
2703
  return capCodePoints(String(scrubber(text)), ERROR_BODY_MAX_CODE_POINTS);
2458
2704
  }
2459
2705
 
2460
- // src/integrations/mcp/config.ts
2706
+ // src/integrations/mcp/captureSettings.ts
2707
+ var import_node_crypto2 = require("crypto");
2708
+ var SETTINGS_PATH = "/v0/settings";
2709
+ var TENANT_HEADER = "X-Baton-Tenant-Id";
2710
+ var SETTINGS_MODES = ["local", "console"];
2711
+ var DEFAULT_SETTINGS_REFRESH_MS = 6e4;
2712
+ var MIN_SETTINGS_REFRESH_MS = 15e3;
2713
+ var REQUEST_TIMEOUT_MS = 1e4;
2714
+ var MATCH_KEYS = /* @__PURE__ */ new Set(["label", "client", "share"]);
2461
2715
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required"]);
2462
2716
  var REPORT_MODES = /* @__PURE__ */ new Set(["on", "off"]);
2463
2717
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
2718
+ function shareBucket(vendorId2, key) {
2719
+ const digest = (0, import_node_crypto2.createHash)("sha256").update(`${vendorId2}
2720
+ ${key}`, "utf-8").digest();
2721
+ return Number(digest.readBigUInt64BE(0) % 10000n);
2722
+ }
2723
+ function matchesEveryone(audience) {
2724
+ return audience.labels === null && audience.clients === null && audience.shareThreshold === null;
2725
+ }
2726
+ function matches(audience, caller, bucket) {
2727
+ if (audience.labels !== null && !caller.labels.some((label) => audience.labels.has(label))) return false;
2728
+ if (audience.clients !== null && (caller.clientName === null || !audience.clients.has(caller.clientName))) {
2729
+ return false;
2730
+ }
2731
+ if (audience.shareThreshold !== null && (bucket === null || bucket >= audience.shareThreshold)) return false;
2732
+ return true;
2733
+ }
2734
+ var SettingsDocument = class {
2735
+ constructor(version, audiences) {
2736
+ this.version = version;
2737
+ this.audiences = audiences;
2738
+ this.usesShare = audiences.some((a) => a.shareThreshold !== null);
2739
+ this.unmatched = { capture: { settings_version: version } };
2740
+ this.reportsOnForAnyone = audiences.some((a) => a.settings.reportMode !== "off") || !audiences.some(matchesEveryone);
2741
+ }
2742
+ version;
2743
+ audiences;
2744
+ usesShare;
2745
+ unmatched;
2746
+ /** Whether some caller can get reports, so the instructions point to the
2747
+ * tool. Read only where the code's value is "on": no tool exists otherwise. */
2748
+ reportsOnForAnyone;
2749
+ settingsFor(caller, vendorId2) {
2750
+ const bucket = caller.shareKey !== null && this.usesShare ? shareBucket(vendorId2, caller.shareKey) : null;
2751
+ return this.audiences.find((audience) => matches(audience, caller, bucket))?.settings ?? this.unmatched;
2752
+ }
2753
+ };
2754
+ function stringSet(value) {
2755
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) return null;
2756
+ return new Set(value);
2757
+ }
2758
+ function readAudience(version, id, match, capture) {
2759
+ if (!Object.keys(match).every((key) => MATCH_KEYS.has(key))) return null;
2760
+ let labels = null;
2761
+ let clients = null;
2762
+ let shareThreshold = null;
2763
+ if (Object.hasOwn(match, "label") && (labels = stringSet(match.label)) === null) return null;
2764
+ if (Object.hasOwn(match, "client") && (clients = stringSet(match.client)) === null) return null;
2765
+ if (Object.hasOwn(match, "share")) {
2766
+ const share = match.share;
2767
+ if (typeof share !== "number" || !(share > 0 && share <= 1)) return null;
2768
+ shareThreshold = Math.floor(share * 1e4 + 0.5);
2769
+ }
2770
+ const settings = { capture: { settings_version: version, audience: id } };
2771
+ const { results, goal, reports } = capture;
2772
+ if (typeof results === "string" && RESULT_CAPTURE_MODE_SET.has(results)) {
2773
+ settings.resultCaptureMode = results;
2774
+ }
2775
+ if (typeof goal === "string" && INTENT_PARAM_MODES.has(goal)) settings.intentParamMode = goal;
2776
+ if (typeof reports === "string" && REPORT_MODES.has(reports)) settings.reportMode = reports;
2777
+ return { settings, labels, clients, shareThreshold };
2778
+ }
2779
+ function parseDocument(body) {
2780
+ let data;
2781
+ try {
2782
+ data = JSON.parse(body);
2783
+ } catch {
2784
+ return null;
2785
+ }
2786
+ if (!isRecord(data)) return null;
2787
+ const { version, audiences } = data;
2788
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) return null;
2789
+ if (!Array.isArray(audiences) || audiences.length === 0) return null;
2790
+ const parsed = [];
2791
+ for (const audience of audiences) {
2792
+ if (!isRecord(audience)) return null;
2793
+ const { id, match, capture } = audience;
2794
+ if (typeof id !== "string" || !isRecord(match) || !isRecord(capture)) return null;
2795
+ const readable = readAudience(version, id, match, capture);
2796
+ if (readable !== null) parsed.push(readable);
2797
+ }
2798
+ return new SettingsDocument(version, parsed);
2799
+ }
2800
+ var SettingsFetcher = class {
2801
+ url;
2802
+ // `#`, not `private`, so logging a config shows no key: "logging the config shows no key".
2803
+ #headers;
2804
+ refreshMs;
2805
+ fetchImpl;
2806
+ etag = null;
2807
+ held = null;
2808
+ timer = null;
2809
+ reading = null;
2810
+ warned = false;
2811
+ constructor(options) {
2812
+ this.url = `${options.origin}${SETTINGS_PATH}?${new URLSearchParams({ server: options.vendorId }).toString()}`;
2813
+ this.#headers = { Authorization: `Bearer ${options.apiKey}`, [TENANT_HEADER]: options.tenantId };
2814
+ this.refreshMs = options.refreshMs;
2815
+ this.fetchImpl = options.fetchImpl ?? fetch;
2816
+ }
2817
+ get document() {
2818
+ return this.held;
2819
+ }
2820
+ start() {
2821
+ if (this.timer !== null) return;
2822
+ this.timer = setInterval(() => void this.readOnce(), this.refreshMs);
2823
+ this.timer.unref?.();
2824
+ void this.readOnce();
2825
+ }
2826
+ stop() {
2827
+ if (this.timer !== null) clearInterval(this.timer);
2828
+ this.timer = null;
2829
+ this.reading?.abort();
2830
+ this.reading = null;
2831
+ }
2832
+ /** One request. Never rejects: a failure keeps what is held. */
2833
+ async readOnce() {
2834
+ if (this.reading !== null) return;
2835
+ const reading = new AbortController();
2836
+ this.reading = reading;
2837
+ const timeout = setTimeout(() => reading.abort(), REQUEST_TIMEOUT_MS);
2838
+ timeout.unref?.();
2839
+ try {
2840
+ await this.read(reading.signal);
2841
+ } catch {
2842
+ } finally {
2843
+ clearTimeout(timeout);
2844
+ if (this.reading === reading) this.reading = null;
2845
+ }
2846
+ }
2847
+ async read(signal) {
2848
+ const headers = this.etag === null ? this.#headers : { ...this.#headers, "If-None-Match": this.etag };
2849
+ const response = await this.fetchImpl(this.url, { method: "GET", headers, redirect: "manual", signal });
2850
+ if (response.status !== 200) {
2851
+ void response.body?.cancel().catch(() => void 0);
2852
+ }
2853
+ if (signal.aborted) return;
2854
+ if (response.status === 204) {
2855
+ this.held = null;
2856
+ this.etag = null;
2857
+ } else if (response.status === 200) {
2858
+ const document = parseDocument(await response.text());
2859
+ if (signal.aborted) return;
2860
+ if (document === null) {
2861
+ if (!this.warned) {
2862
+ this.warned = true;
2863
+ warn("baton: the collector sent capture settings this SDK cannot read");
2864
+ }
2865
+ return;
2866
+ }
2867
+ this.held = document;
2868
+ this.etag = response.headers.get("etag");
2869
+ }
2870
+ }
2871
+ };
2872
+ var CaptureSettings = class {
2873
+ constructor(vendorId2, source) {
2874
+ this.vendorId = vendorId2;
2875
+ this.source = source;
2876
+ }
2877
+ vendorId;
2878
+ source;
2879
+ start() {
2880
+ this.source.start();
2881
+ }
2882
+ stop() {
2883
+ this.source.stop();
2884
+ }
2885
+ get document() {
2886
+ return this.source.document;
2887
+ }
2888
+ /** `undefined` while no document is held, and the config's values apply. */
2889
+ forCaller(caller) {
2890
+ return this.document?.settingsFor(caller, this.vendorId);
2891
+ }
2892
+ };
2893
+
2894
+ // src/integrations/mcp/config.ts
2464
2895
  function resolveTenantId(explicit, vendorId2) {
2465
2896
  if (explicit) return explicit;
2466
2897
  const fromEnv2 = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
@@ -2498,6 +2929,11 @@ function resolveBatonConfig(config) {
2498
2929
  consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
2499
2930
  };
2500
2931
  validateBatonConfig(defaulted);
2932
+ if (defaulted.settings === "console") {
2933
+ throw new Error(
2934
+ `BatonConfig.settings: "console" reads the Capture page with the dsn's key, so it needs a dsn.`
2935
+ );
2936
+ }
2501
2937
  return defaulted;
2502
2938
  }
2503
2939
  const dsn = parseDsn(dsnString);
@@ -2519,14 +2955,27 @@ function resolveBatonConfig(config) {
2519
2955
  // `??`, not `||`: an explicit empty string must survive to the validation
2520
2956
  // below and be REFUSED there, rather than be quietly replaced by the
2521
2957
  // default it was deliberately not left as.
2522
- consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
2958
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN,
2959
+ ...config.reportMode === void 0 && config.settings === "console" ? { reportMode: "on" } : {}
2523
2960
  };
2524
2961
  validateBatonConfig(identity);
2525
2962
  return {
2526
2963
  ...identity,
2527
2964
  // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2528
2965
  // itself, exactly as it does for an explicitly-constructed sink.
2529
- sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2966
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key }),
2967
+ ...identity.settings === "console" ? {
2968
+ captureSettings: new CaptureSettings(
2969
+ dsn.vendorId,
2970
+ new SettingsFetcher({
2971
+ origin: dsn.origin,
2972
+ apiKey: dsn.key,
2973
+ tenantId: dsn.tenantId,
2974
+ vendorId: dsn.vendorId,
2975
+ refreshMs: identity.settingsRefreshMs ?? DEFAULT_SETTINGS_REFRESH_MS
2976
+ })
2977
+ )
2978
+ } : {}
2530
2979
  };
2531
2980
  }
2532
2981
  function withServerDisplayName(resolved, supplied, serverName) {
@@ -2591,6 +3040,17 @@ function validateBatonConfig(config) {
2591
3040
  `BatonConfig.resultCaptureMode ${JSON.stringify(config.resultCaptureMode)} must be one of ${JSON.stringify([...RESULT_CAPTURE_MODES].sort())}.`
2592
3041
  );
2593
3042
  }
3043
+ if (config.settings !== void 0 && !SETTINGS_MODES.includes(config.settings)) {
3044
+ throw new Error(
3045
+ `BatonConfig.settings ${JSON.stringify(config.settings)} must be one of ${JSON.stringify(SETTINGS_MODES)}.`
3046
+ );
3047
+ }
3048
+ const refresh = config.settingsRefreshMs;
3049
+ if (refresh !== void 0 && (typeof refresh !== "number" || !(refresh >= MIN_SETTINGS_REFRESH_MS && refresh <= MAX_TIMER_MS))) {
3050
+ throw new Error(
3051
+ `BatonConfig.settingsRefreshMs must be a number of milliseconds from ${String(MIN_SETTINGS_REFRESH_MS)} to ${String(MAX_TIMER_MS)}.`
3052
+ );
3053
+ }
2594
3054
  if (config.scrubber !== void 0 && typeof config.scrubber !== "function") {
2595
3055
  throw new Error("BatonConfig.scrubber must be a function.");
2596
3056
  }
@@ -2652,7 +3112,9 @@ function resumesPausedCall(extra) {
2652
3112
 
2653
3113
  // src/integrations/mcp/handle.ts
2654
3114
  var BatonHandle = class {
3115
+ /** The sink the vendor passed, or the default one. */
2655
3116
  sink;
3117
+ #queue;
2656
3118
  vendorId;
2657
3119
  /** The install's own session id: what stdio and in-memory calls, and the
2658
3120
  * surface snapshot, carry when no session id resolves. A call over HTTP
@@ -2664,6 +3126,7 @@ var BatonHandle = class {
2664
3126
  annotationToolName;
2665
3127
  constructor(options) {
2666
3128
  this.sink = options.sink;
3129
+ this.#queue = options.queue ?? options.sink;
2667
3130
  this.vendorId = options.vendorId;
2668
3131
  this.sessionId = options.sessionId;
2669
3132
  this.annotationToolName = options.annotationToolName;
@@ -2671,14 +3134,83 @@ var BatonHandle = class {
2671
3134
  /** Flush any pending events held by the sink. Never rejects; returns within
2672
3135
  * the shutdown budget (SPEC §11.2 rule 7). */
2673
3136
  async flush() {
2674
- await boundedSinkCall(this.sink, "flush");
3137
+ await boundedSinkCall(this.#queue, "flush");
2675
3138
  }
2676
3139
  /** Flush and release sink resources, on the same terms as `flush()`. */
2677
3140
  async aclose() {
2678
- await boundedSinkCall(this.sink, "aclose");
3141
+ await boundedSinkCall(this.#queue, "aclose");
2679
3142
  }
2680
3143
  };
2681
3144
 
3145
+ // src/integrations/mcp/perCaller.ts
3146
+ var PerCallerSurface = class {
3147
+ constructor(options) {
3148
+ this.options = options;
3149
+ }
3150
+ options;
3151
+ pointerOn = true;
3152
+ /** Called at install and on every request; writes only when the report
3153
+ * pointer should change. */
3154
+ followSettings() {
3155
+ if (this.options.annotationToolName === "") return;
3156
+ try {
3157
+ const document = this.options.settings.document;
3158
+ const pointerOn = document === null || document.reportsOnForAnyone;
3159
+ if (pointerOn === this.pointerOn) return;
3160
+ this.options.writeInstructions(pointerOn ? this.options.instructions : INTENT_INSTRUCTIONS);
3161
+ this.pointerOn = pointerOn;
3162
+ } catch (err) {
3163
+ process.stderr.write(`baton: could not update the server instructions for new settings: ${printable(err)}
3164
+ `);
3165
+ }
3166
+ }
3167
+ /** `result` with the caller's goal and reports settings; as served on any failure. */
3168
+ toolsFor(result, caller) {
3169
+ const settings = caller.settings;
3170
+ if (settings === void 0) return result;
3171
+ const { intentParamMode, annotationToolName, injectsGoal } = this.options;
3172
+ const goal = settings.intentParamMode ?? intentParamMode;
3173
+ const hideReports = annotationToolName !== "" && settings.reportMode === "off";
3174
+ if (goal === intentParamMode && !hideReports) return result;
3175
+ try {
3176
+ const tools = result?.tools;
3177
+ if (!Array.isArray(tools)) return result;
3178
+ const served = [];
3179
+ for (const tool of tools) {
3180
+ const name = tool?.name;
3181
+ if (hideReports && name === annotationToolName) continue;
3182
+ const rewrite = goal !== intentParamMode && typeof name === "string" && injectsGoal(name);
3183
+ served.push(rewrite ? withGoalMode(tool, goal) : tool);
3184
+ }
3185
+ return { ...result, tools: served };
3186
+ } catch (err) {
3187
+ process.stderr.write(`baton: could not apply capture settings to the tool list: ${printable(err)}
3188
+ `);
3189
+ return result;
3190
+ }
3191
+ }
3192
+ };
3193
+ function withGoalMode(tool, goal) {
3194
+ const entry = tool;
3195
+ const schema = entry.inputSchema;
3196
+ const properties = schema?.properties;
3197
+ const param = properties?.[USER_GOAL_PARAM_NAME];
3198
+ if (typeof param !== "object" || param === null) return tool;
3199
+ const others = Array.isArray(schema.required) ? schema.required.filter((name) => name !== USER_GOAL_PARAM_NAME) : [];
3200
+ const required = goal === "required" ? [...others, USER_GOAL_PARAM_NAME] : others;
3201
+ return {
3202
+ ...entry,
3203
+ inputSchema: {
3204
+ ...schema,
3205
+ properties: {
3206
+ ...properties,
3207
+ [USER_GOAL_PARAM_NAME]: { ...param, description: buildUserGoalParamDescription({ intentParamMode: goal }) }
3208
+ },
3209
+ ...required.length > 0 || Array.isArray(schema.required) ? { required } : {}
3210
+ }
3211
+ };
3212
+ }
3213
+
2682
3214
  // src/integrations/mcp/sessionCounter.ts
2683
3215
  var SESSION_CAP = 4096;
2684
3216
  var SessionCounter = class {
@@ -2791,16 +3323,16 @@ var import_zod3 = require("zod");
2791
3323
  var import_v3 = require("zod/v3");
2792
3324
  var DEFAULT_INTENT_PARAM_MODE = "required";
2793
3325
  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: {} };
3326
+ function injectGoalParams(inputSchema2, intentParamMode) {
3327
+ const objSchema = normalizeObjectSchema(inputSchema2);
3328
+ if (!objSchema) return { schema: inputSchema2, dispositions: {} };
2797
3329
  const existingShape = getObjectShape(objSchema) ?? {};
2798
3330
  const values = Object.values(existingShape);
2799
3331
  const useV4 = values.length === 0 || isZ4Schema(values[0]);
2800
3332
  const zodImpl = useV4 ? import_zod3.z : import_v3.z;
2801
3333
  const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl, intentParamMode);
2802
3334
  if (Object.keys(toInject).length === 0)
2803
- return { schema: inputSchema, dispositions };
3335
+ return { schema: inputSchema2, dispositions };
2804
3336
  const mergedShape = { ...existingShape, ...toInject };
2805
3337
  const newSchema = objectFromShape(mergedShape);
2806
3338
  return { schema: newSchema, dispositions };
@@ -2819,15 +3351,15 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
2819
3351
  }
2820
3352
  return { dispositions, toInject };
2821
3353
  }
2822
- function injectGoalParamsV2(inputSchema, intentParamMode) {
2823
- const candidate = inputSchema;
3354
+ function injectGoalParamsV2(inputSchema2, intentParamMode) {
3355
+ const candidate = inputSchema2;
2824
3356
  const shape = candidate?.shape;
2825
3357
  if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
2826
- return { schema: inputSchema, dispositions: {} };
3358
+ return { schema: inputSchema2, dispositions: {} };
2827
3359
  }
2828
3360
  const { dispositions, toInject } = buildIntentFields(shape, import_zod3.z, intentParamMode);
2829
3361
  if (Object.keys(toInject).length === 0)
2830
- return { schema: inputSchema, dispositions };
3362
+ return { schema: inputSchema2, dispositions };
2831
3363
  return { schema: candidate.extend(toInject), dispositions };
2832
3364
  }
2833
3365
  function advertiseIntentParamsRequired(result, names, isInjected) {
@@ -2850,8 +3382,8 @@ function advertiseIntentParamsRequired(result, names, isInjected) {
2850
3382
  });
2851
3383
  return changed ? { ...result, tools: advertised } : result;
2852
3384
  }
2853
- function toolInputJsonSchema(inputSchema) {
2854
- const objSchema = normalizeObjectSchema(inputSchema);
3385
+ function toolInputJsonSchema(inputSchema2) {
3386
+ const objSchema = normalizeObjectSchema(inputSchema2);
2855
3387
  if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
2856
3388
  return toJsonSchemaCompat(objSchema, {
2857
3389
  strictUnions: true,
@@ -2860,10 +3392,10 @@ function toolInputJsonSchema(inputSchema) {
2860
3392
  }
2861
3393
 
2862
3394
  // src/integrations/mcp/surface.ts
2863
- var import_node_crypto2 = require("crypto");
3395
+ var import_node_crypto3 = require("crypto");
2864
3396
  function surfaceHash(surface) {
2865
3397
  const canonical = canonicalJson(surface);
2866
- const digest = (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf-8").digest("hex");
3398
+ const digest = (0, import_node_crypto3.createHash)("sha256").update(canonical, "utf-8").digest("hex");
2867
3399
  return `sha256:${digest}`;
2868
3400
  }
2869
3401
  function canonicalJson(value) {
@@ -2907,9 +3439,6 @@ var SentSurfaces = class {
2907
3439
  this.hashes.delete(this.hashes.values().next().value);
2908
3440
  }
2909
3441
  }
2910
- unmark(digest) {
2911
- this.hashes.delete(digest);
2912
- }
2913
3442
  };
2914
3443
  function buildSeamAugmentations(options) {
2915
3444
  return {
@@ -2999,10 +3528,14 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
2999
3528
  const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
3000
3529
  (name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
3001
3530
  );
3531
+ const client = observeClient(extra, ctx);
3002
3532
  const caller = await resolveCaller(
3003
3533
  ctx.resolvePrincipal,
3004
- { extra, toolName, arguments: params }
3534
+ { extra, toolName, arguments: params },
3535
+ ctx.captureSettings,
3536
+ client
3005
3537
  );
3538
+ const resultCaptureMode = caller.settings?.resultCaptureMode ?? ctx.configResultCaptureMode;
3006
3539
  const common = {
3007
3540
  tenant_id: ctx.tenantId,
3008
3541
  vendor_id: ctx.vendorId,
@@ -3012,15 +3545,14 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3012
3545
  // it. `surface_snapshot` is deliberately not among them: it describes the
3013
3546
  // SERVER and is captured outside any call, so it has no caller, transport
3014
3547
  // or client to name.
3015
- principal: caller.principal,
3016
- organization: caller.organization,
3548
+ ...callerEnvelope(caller),
3017
3549
  transport_observed: observeTransport(extra),
3018
3550
  session_id_origin: session.origin,
3019
- client_observed: observeClient(extra, ctx),
3551
+ client_observed: client,
3020
3552
  runtime_meta: scrubbedMeta,
3021
3553
  call_id: uuid7()
3022
3554
  };
3023
- if (resumesPausedCall(extra)) return { common, session };
3555
+ if (resumesPausedCall(extra)) return { common, session, resultCaptureMode };
3024
3556
  await emit(
3025
3557
  ctx.sink,
3026
3558
  () => ToolCallStartEventSchema.parse({
@@ -3038,7 +3570,7 @@ async function openCall(ctx, toolName, extra, params, stripped, registered = tru
3038
3570
  }
3039
3571
  })
3040
3572
  );
3041
- return { common, session };
3573
+ return { common, session, resultCaptureMode };
3042
3574
  }
3043
3575
  function batonWrap(nameRef, original, ctx) {
3044
3576
  return async (...callArgs) => {
@@ -3049,7 +3581,7 @@ function batonWrap(nameRef, original, ctx) {
3049
3581
  const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
3050
3582
  const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
3051
3583
  if (slot) slot.strippedFor = null;
3052
- const { common, session } = await openCall(ctx, toolName, extra, params, stripped);
3584
+ const { common, session, resultCaptureMode } = await openCall(ctx, toolName, extra, params, stripped);
3053
3585
  const terminate = async (build, replacement) => {
3054
3586
  if (!slot) {
3055
3587
  if (build !== null) await emit(ctx.sink, build);
@@ -3082,7 +3614,7 @@ function batonWrap(nameRef, original, ctx) {
3082
3614
  // SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
3083
3615
  // raised message public, so under "off" every one is withheld.
3084
3616
  ...resultDerivedFields(
3085
- ctx.resultCaptureMode,
3617
+ resultCaptureMode,
3086
3618
  () => messageOf(err),
3087
3619
  null,
3088
3620
  (text) => errorBody(ctx, text),
@@ -3142,7 +3674,7 @@ function batonWrap(nameRef, original, ctx) {
3142
3674
  // nothing on the wire has; the loss is deliberate and worth
3143
3675
  // knowing when debugging one of these.
3144
3676
  ...resultDerivedFields(
3145
- ctx.resultCaptureMode,
3677
+ resultCaptureMode,
3146
3678
  () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
3147
3679
  // ⚠ `null` on the `raised` lane, never `undefined`, and the
3148
3680
  // union is what forces the branch rather than a comment: the
@@ -3181,7 +3713,7 @@ function batonWrap(nameRef, original, ctx) {
3181
3713
  // `ToolCallErrorPayloadSchema` in `events.ts` holds that claim and
3182
3714
  // names the test that enforces it.
3183
3715
  ...returnedErrorFields(
3184
- ctx.resultCaptureMode,
3716
+ resultCaptureMode,
3185
3717
  result,
3186
3718
  (text) => errorBody(ctx, text),
3187
3719
  ctx.scrubber
@@ -3199,7 +3731,7 @@ function batonWrap(nameRef, original, ctx) {
3199
3731
  payload: {
3200
3732
  tool_name: toolName,
3201
3733
  duration_ms: durationMs,
3202
- ...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
3734
+ ...endResultFields(resultCaptureMode, result, ctx.scrubber)
3203
3735
  }
3204
3736
  }),
3205
3737
  (outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
@@ -3262,14 +3794,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
3262
3794
  requiredParamNames: requiredParamNames(ctx.intentParamMode),
3263
3795
  instructionsSuffix: instructionsSuffixServed(ctx.annotationToolName, ctx.servedInstructions())
3264
3796
  });
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
- }
3797
+ await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
3273
3798
  }
3274
3799
  function declaredIntentParams(vendorSchema) {
3275
3800
  const declared2 = {};
@@ -3352,6 +3877,7 @@ var LIFECYCLE_SEAMS = {
3352
3877
  };
3353
3878
  function installLifecycleSeam(lowLevel, ctx, spec) {
3354
3879
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
3880
+ ctx.perCaller?.followSettings();
3355
3881
  const request = args[0];
3356
3882
  const requestParams = request?.params ?? {};
3357
3883
  const extra = args[1];
@@ -3372,8 +3898,9 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3372
3898
  const startedAt = performance.now();
3373
3899
  const elapsed = () => Math.round(performance.now() - startedAt);
3374
3900
  try {
3375
- const result = await handler(...args);
3376
- if (isInputRequired(result)) return result;
3901
+ const served = await handler(...args);
3902
+ if (isInputRequired(served)) return served;
3903
+ const result = opened !== null && spec.rewriteResult !== void 0 ? spec.rewriteResult(ctx, served, opened.caller) : served;
3377
3904
  await fire(spec.schemas.end, {
3378
3905
  ...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
3379
3906
  duration_ms: elapsed()
@@ -3395,24 +3922,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
3395
3922
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
3396
3923
  try {
3397
3924
  const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
3398
- const caller = await resolveCaller(ctx.resolvePrincipal, {
3399
- extra,
3400
- toolName: null,
3401
- arguments: {}
3402
- });
3925
+ const client = observeClient(extra, ctx);
3926
+ const caller = await resolveCaller(
3927
+ ctx.resolvePrincipal,
3928
+ { extra, toolName: null, arguments: {} },
3929
+ ctx.captureSettings,
3930
+ client
3931
+ );
3403
3932
  return {
3404
3933
  session,
3934
+ caller,
3405
3935
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
3406
3936
  common: {
3407
3937
  tenant_id: ctx.tenantId,
3408
3938
  vendor_id: ctx.vendorId,
3409
3939
  session_id: session.sessionId,
3410
3940
  consent_token: ctx.consentToken,
3411
- principal: caller.principal,
3412
- organization: caller.organization,
3941
+ ...callerEnvelope(caller),
3413
3942
  transport_observed: observeTransport(extra),
3414
3943
  session_id_origin: session.origin,
3415
- client_observed: observeClient(extra, ctx),
3944
+ client_observed: client,
3416
3945
  runtime_meta: scrubbedMeta
3417
3946
  }
3418
3947
  };
@@ -3495,7 +4024,8 @@ var LIFECYCLE_SPECS = [
3495
4024
  error: ToolListErrorEventSchema
3496
4025
  },
3497
4026
  countKey: "tools",
3498
- startParams: NO_PARAMS
4027
+ startParams: NO_PARAMS,
4028
+ rewriteResult: (ctx, result, caller) => ctx.perCaller?.toolsFor(result, caller) ?? result
3499
4029
  }
3500
4030
  ];
3501
4031
  function installLifecycleSeams(lowLevel, ctx) {
@@ -3537,6 +4067,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
3537
4067
  TOOLS_CALL_METHOD,
3538
4068
  TOOLS_CALL_SEAM,
3539
4069
  (handler) => async (...args) => {
4070
+ ctx.perCaller?.followSettings();
3540
4071
  const request = args[0];
3541
4072
  const name = request?.params?.name;
3542
4073
  const slot = {
@@ -3604,7 +4135,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3604
4135
  const entry = toolEntry(toolName);
3605
4136
  if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
3606
4137
  const params = { ...request?.params?.arguments ?? {} };
3607
- const { common, session } = await openCall(
4138
+ const { common, session, resultCaptureMode } = await openCall(
3608
4139
  ctx,
3609
4140
  toolName,
3610
4141
  args[1],
@@ -3647,7 +4178,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
3647
4178
  ...failureKind === void 0 ? {} : { failure_kind: failureKind },
3648
4179
  ...requestSideFailureFields(
3649
4180
  failureKind,
3650
- ctx.resultCaptureMode,
4181
+ resultCaptureMode,
3651
4182
  text,
3652
4183
  outcome.raised ? null : outcome.result,
3653
4184
  (value) => errorBody(ctx, value),
@@ -3724,8 +4255,28 @@ function withBaton(server, supplied = {}) {
3724
4255
  const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);
3725
4256
  if (unconfigured) logUnconfigured("withBaton");
3726
4257
  else warnAboutSettings(resolved);
3727
- return handle;
3728
- }
4258
+ const settings = resolved.captureSettings;
4259
+ if (settings === void 0) return handle;
4260
+ settings.start();
4261
+ return new SettingsHandle(handle, settings);
4262
+ }
4263
+ var SettingsHandle = class extends BatonHandle {
4264
+ constructor(inner, settings) {
4265
+ super(inner);
4266
+ this.inner = inner;
4267
+ this.settings = settings;
4268
+ }
4269
+ inner;
4270
+ settings;
4271
+ // The inner handle holds the queue in front of the sink.
4272
+ flush() {
4273
+ return this.inner.flush();
4274
+ }
4275
+ async aclose() {
4276
+ this.settings.stop();
4277
+ await this.inner.aclose();
4278
+ }
4279
+ };
3729
4280
  function createBaton(supplied = {}) {
3730
4281
  const disabledBy = captureDisabled();
3731
4282
  if (disabledBy !== null) {
@@ -3742,19 +4293,23 @@ function createBaton(supplied = {}) {
3742
4293
  if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
3743
4294
  if (unconfigured) logUnconfigured("createBaton");
3744
4295
  else warnAboutSettings(resolved);
3745
- const sink = unconfigured ? new DisabledSink() : resolved.sink ?? new StdoutSink();
4296
+ const sink = unconfigured ? new DisabledSink() : offTheCall(resolved.sink ?? new StdoutSink());
3746
4297
  const config = {
3747
4298
  ...resolved,
3748
4299
  sink,
3749
4300
  tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
3750
4301
  };
3751
4302
  const state = newBatonState(resolved);
4303
+ resolved.captureSettings?.start();
3752
4304
  return {
3753
4305
  wrap: (server) => {
3754
4306
  install(server, supplied, config, state, unconfigured);
3755
4307
  },
3756
4308
  flush: () => boundedSinkCall(sink, "flush"),
3757
- aclose: () => boundedSinkCall(sink, "aclose")
4309
+ aclose: () => {
4310
+ resolved.captureSettings?.stop();
4311
+ return boundedSinkCall(sink, "aclose");
4312
+ }
3758
4313
  };
3759
4314
  }
3760
4315
  function inertHandle(sink, sessionId) {
@@ -3788,7 +4343,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3788
4343
  const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
3789
4344
  const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
3790
4345
  if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
3791
- const sink = config.sink ?? new StdoutSink();
4346
+ const given = config.sink ?? new StdoutSink();
4347
+ const sink = offTheCall(given);
3792
4348
  const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
3793
4349
  const fallbackSessionId = `sdk-${uuid7()}`;
3794
4350
  const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
@@ -3796,29 +4352,26 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3796
4352
  const serverMeta = buildServerMeta(server.server);
3797
4353
  const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
3798
4354
  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
- }
4355
+ await emit(
4356
+ sink,
4357
+ () => SurfaceSnapshotEventSchema.parse({
4358
+ tenant_id: tenantId,
4359
+ vendor_id: config.vendorId,
4360
+ session_id: sessionId,
4361
+ session_id_origin: "minted",
4362
+ consent_token: config.consentToken,
4363
+ sequence_number: counter2.next(sessionId, false),
4364
+ captured_at: (/* @__PURE__ */ new Date()).toISOString(),
4365
+ payload: {
4366
+ surface_hash: digest,
4367
+ server_info: snapshot.server_info,
4368
+ capabilities: snapshot.capabilities,
4369
+ instructions: snapshot.instructions,
4370
+ tools: snapshot.tools,
4371
+ seam_augmentations: snapshot.seam_augmentations
4372
+ }
4373
+ })
4374
+ );
3822
4375
  };
3823
4376
  const bustSchemaMemo = (name) => {
3824
4377
  const memo = internals._toolInputSchemaJson;
@@ -3845,7 +4398,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3845
4398
  );
3846
4399
  };
3847
4400
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
3848
- const vendorToolJsonSchema = (name, inputSchema) => {
4401
+ const vendorToolJsonSchema = (name, inputSchema2) => {
3849
4402
  if (isV2Server) {
3850
4403
  try {
3851
4404
  const json = internals.toolInputSchemaJson(name);
@@ -3853,14 +4406,14 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3853
4406
  } catch {
3854
4407
  }
3855
4408
  try {
3856
- const standard = inputSchema?.["~standard"];
4409
+ const standard = inputSchema2?.["~standard"];
3857
4410
  const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
3858
4411
  if (json) return json;
3859
4412
  } catch {
3860
4413
  }
3861
4414
  }
3862
4415
  try {
3863
- return toolInputJsonSchema(inputSchema);
4416
+ return toolInputJsonSchema(inputSchema2);
3864
4417
  } catch {
3865
4418
  return { type: "object", properties: {} };
3866
4419
  }
@@ -3877,9 +4430,11 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3877
4430
  scrubber,
3878
4431
  annotationToolName,
3879
4432
  intentParamMode,
3880
- resultCaptureMode: config.resultCaptureMode ?? "full",
4433
+ configResultCaptureMode: config.resultCaptureMode ?? "full",
3881
4434
  paramRegistry: /* @__PURE__ */ new Map(),
3882
4435
  resolvePrincipal: config.resolvePrincipal,
4436
+ captureSettings: config.captureSettings,
4437
+ perCaller: void 0,
3883
4438
  vendorToolJsonSchema,
3884
4439
  bustSchemaMemo,
3885
4440
  dropSubagentClause,
@@ -3887,11 +4442,29 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3887
4442
  surfaceState,
3888
4443
  emitSurface
3889
4444
  };
3890
- internals.server._instructions = withVendorInstructions(
3891
- internals.server,
3892
- ours,
3893
- (message) => warnOnce2("instructions-length", message)
3894
- );
4445
+ const writeInstructions = (text) => {
4446
+ internals.server._instructions = withVendorInstructions(
4447
+ internals.server,
4448
+ text,
4449
+ (message) => warnOnce2("instructions-length", message)
4450
+ );
4451
+ };
4452
+ writeInstructions(ours);
4453
+ if (config.captureSettings !== void 0) {
4454
+ ctx.perCaller = new PerCallerSurface({
4455
+ settings: config.captureSettings,
4456
+ intentParamMode,
4457
+ annotationToolName,
4458
+ instructions: ours,
4459
+ writeInstructions: (text) => {
4460
+ writeInstructions(text);
4461
+ const native = [...ctx.paramRegistry].find(([, d]) => d[USER_GOAL_PARAM_NAME] === "native");
4462
+ if (native !== void 0) dropSubagentClause(native[0]);
4463
+ },
4464
+ injectsGoal: (name) => ctx.paramRegistry.get(name)?.[USER_GOAL_PARAM_NAME] === "injected"
4465
+ });
4466
+ ctx.perCaller.followSettings();
4467
+ }
3895
4468
  installToolsListSeam(internals.server, ctx);
3896
4469
  installToolsCallSeam(
3897
4470
  internals.server,
@@ -3917,6 +4490,7 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3917
4490
  vendorDisplayName: reports.vendorDisplayName,
3918
4491
  consentToken: ctx.consentToken,
3919
4492
  resolvePrincipal: ctx.resolvePrincipal,
4493
+ captureSettings: ctx.captureSettings,
3920
4494
  fallbackSessionId: ctx.fallbackSessionId,
3921
4495
  scrubber: ctx.scrubber,
3922
4496
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -3937,7 +4511,8 @@ function install(server, supplied, resolved, { sentSurfaces, warned: warned3, co
3937
4511
  return registered;
3938
4512
  };
3939
4513
  return new BatonHandle({
3940
- sink,
4514
+ sink: given,
4515
+ queue: sink,
3941
4516
  vendorId: config.vendorId,
3942
4517
  sessionId: fallbackSessionId,
3943
4518
  annotationToolName: resolvedAnnotationToolName
@@ -3956,7 +4531,7 @@ function warnAboutSettings(config) {
3956
4531
  }
3957
4532
  if (config.resultCaptureMode === WITHHELD) {
3958
4533
  warn(
3959
- 'baton: resultCaptureMode "off" does not withhold the message of a failed resource or prompt request. resource_list_error, resource_read_error, prompt_list_error and prompt_get_error carry that message, which can quote what your handler fetched. Throw a message that names the resource or prompt, not its contents.'
4534
+ 'baton: resultCaptureMode "off" does not withhold the message of a failed tool list, resource or prompt request. tool_list_error, resource_list_error, resource_read_error, prompt_list_error and prompt_get_error carry that message, which can include text your handler or middleware threw. Throw a message that does not quote what your code fetched.'
3960
4535
  );
3961
4536
  }
3962
4537
  }
@@ -4003,6 +4578,7 @@ function sessionEnvelope(session) {
4003
4578
  transport_observed: TRANSPORT_LIBRARY,
4004
4579
  principal: session.principal,
4005
4580
  organization: session.organization,
4581
+ labels: wireLabels(session.labels),
4006
4582
  client_observed: session.clientObserved,
4007
4583
  runtime_meta: session.runtimeMeta
4008
4584
  };
@@ -4201,8 +4777,6 @@ function paramsOf(args) {
4201
4777
  }
4202
4778
  var Core = class {
4203
4779
  closed = false;
4204
- pending = /* @__PURE__ */ new Set();
4205
- closedWarned = false;
4206
4780
  // A snapshot describes the server, so it takes no block's session,
4207
4781
  // principal or client: SPEC §11.5.1's join must not count it.
4208
4782
  surfaceSessionId = uuid7();
@@ -4215,7 +4789,7 @@ var Core = class {
4215
4789
  scrubber;
4216
4790
  disabled;
4217
4791
  constructor(resolved) {
4218
- this.sink = resolved.sink;
4792
+ this.sink = offTheCall(resolved.sink);
4219
4793
  this.vendorId = resolved.vendorId;
4220
4794
  this.tenantId = resolved.tenantId;
4221
4795
  this.consentToken = resolved.consentToken;
@@ -4239,25 +4813,15 @@ var Core = class {
4239
4813
  live() {
4240
4814
  if (this.disabled) return false;
4241
4815
  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
- }
4816
+ droppedAfterClose(this.sink);
4247
4817
  return false;
4248
4818
  }
4249
- /** Never rejects. Tracked so `flush()` can wait for it. */
4819
+ /** Never rejects. */
4250
4820
  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;
4821
+ return emit(this.sink, build);
4257
4822
  }
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. */
4823
+ /** Sends `surface` unless this client already has. Never rejects. The
4824
+ * write only queues, so a surface counts as sent once queued. */
4261
4825
  sendSurface(surface) {
4262
4826
  if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
4263
4827
  this.sentSurfaces.mark(surface.digest);
@@ -4279,32 +4843,7 @@ var Core = class {
4279
4843
  `);
4280
4844
  return Promise.resolve();
4281
4845
  }
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);
4846
+ return safeWrite(this.sink, event);
4308
4847
  }
4309
4848
  scrub(value, field) {
4310
4849
  return scrubOrNull(this.scrubber, value, field);
@@ -4575,94 +5114,82 @@ var Client = class {
4575
5114
  /** Wait for events so far to reach the sink, then flush it. Never rejects;
4576
5115
  * returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
4577
5116
  async flush() {
4578
- await this.#settleThen("flush");
5117
+ await boundedSinkCall(this.#core.sink, "flush");
4579
5118
  }
4580
5119
  /** Flush, then close the sink. Later events are dropped. */
4581
5120
  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()));
5121
+ this.#closing ??= boundedSinkCall(this.#core.sink, "aclose").then(() => {
5122
+ this.#core.closed = true;
4593
5123
  });
5124
+ return this.#closing;
4594
5125
  }
4595
5126
  };
5127
+
5128
+ // src/library/reportTool.ts
5129
+ function inputSchema() {
5130
+ const schema = toolInputJsonSchema(ANNOTATION_INPUT_SHAPE);
5131
+ delete schema.$schema;
5132
+ return { ...schema, required: [...schema.required, TOOL_NAME_PARAM_NAME] };
5133
+ }
5134
+ var nonEmptyText = (value) => typeof value === "string" && value !== "";
5135
+ var nonEmptyObject = (value) => isRecord(value) && Object.keys(value).length > 0;
5136
+ function annotateArgs(args) {
5137
+ const whatHappened = args.what_happened;
5138
+ if (!isReport(whatHappened)) return null;
5139
+ const options = { whatHappened };
5140
+ const toolName = args[TOOL_NAME_PARAM_NAME];
5141
+ if (typeof toolName === "string") options.toolName = toolName;
5142
+ const intent = args[USER_GOAL_PARAM_NAME];
5143
+ if (nonEmptyText(intent)) options.intent = intent;
5144
+ if (nonEmptyText(args.suggested_improvement)) {
5145
+ options.suggestedImprovement = args.suggested_improvement;
5146
+ }
5147
+ if (nonEmptyObject(args.context)) options.context = args.context;
5148
+ return options;
5149
+ }
5150
+ function reportTool(options) {
5151
+ const { vendorDisplayName } = options;
5152
+ const derived = options.name ?? toolNameForDisplayName(vendorDisplayName);
5153
+ if (derived === void 0) {
5154
+ throw new Error(
5155
+ `vendorDisplayName ${JSON.stringify(vendorDisplayName)} gives no usable tool name, or one too long for the instructions. Pass name.`
5156
+ );
5157
+ }
5158
+ const name = validateAnnotationToolName(derived);
5159
+ if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: name })) {
5160
+ throw new Error(
5161
+ `vendorDisplayName and name ${JSON.stringify(name)} are too long together for the instructions. Shorten one of them.`
5162
+ );
5163
+ }
5164
+ return {
5165
+ name,
5166
+ description: buildAnnotationToolDescription({ vendorDisplayName }),
5167
+ inputSchema: inputSchema(),
5168
+ instructions: buildServerInstructions({ vendorDisplayName, annotationToolName: name }),
5169
+ refusal: buildRefusalText({ annotationToolName: name }),
5170
+ annotateArgs
5171
+ };
5172
+ }
4596
5173
  // Annotate the CommonJS export names for ESM import in node:
4597
5174
  0 && (module.exports = {
4598
- AnnotationEventSchema,
4599
- AnnotationPayloadSchema,
4600
5175
  BatonHandle,
4601
5176
  Client,
4602
- ClientReportEventSchema,
4603
- ClientReportPayloadSchema,
4604
- DEFAULT_CONSENT_TOKEN,
4605
- DEPTH_LIMIT,
4606
- DEPTH_MARKER,
4607
5177
  EventSchema,
4608
- EventTypeSchema,
4609
5178
  FileSink,
4610
5179
  HttpSink,
4611
5180
  INTENT_INSTRUCTIONS,
4612
5181
  INTENT_PARAMS,
4613
5182
  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
5183
  SDK_VERSION,
4643
5184
  Scrubber,
4644
5185
  SinkClosedError,
4645
5186
  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
5187
  Trace,
4661
5188
  createBaton,
4662
5189
  identityScrub,
4663
5190
  principalFromOAuthEmail,
4664
5191
  principalFromOAuthSub,
4665
- safeWrite,
5192
+ reportTool,
4666
5193
  withBaton
4667
5194
  });
4668
5195
  //# sourceMappingURL=index.cjs.map