@goodtiming/baton-sdk 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,34 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.5.2";
2
+ var SDK_VERSION = "ts-0.5.4";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
6
- import { v7 as uuidv7 } from "uuid";
6
+
7
+ // src/uuid7.ts
8
+ import { randomBytes } from "crypto";
9
+ var COUNTER_MAX = 4095;
10
+ var lastMs = -1;
11
+ var counter = 0;
12
+ function uuid7() {
13
+ const bytes = randomBytes(18);
14
+ const seed = (bytes[16] << 8 | bytes[17]) & 2047;
15
+ const now = Date.now();
16
+ if (now > lastMs) {
17
+ lastMs = now;
18
+ counter = seed;
19
+ } else if (++counter > COUNTER_MAX) {
20
+ lastMs += 1;
21
+ counter = seed;
22
+ }
23
+ bytes.writeUIntBE(lastMs, 0, 6);
24
+ bytes[6] = 112 | counter >> 8;
25
+ bytes[7] = counter & 255;
26
+ bytes[8] = 128 | bytes[8] & 63;
27
+ const hex = bytes.toString("hex", 0, 16);
28
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
29
+ }
30
+
31
+ // src/events.ts
7
32
  var ToolCallStartPayloadSchema = z.object({
8
33
  tool_name: z.string(),
9
34
  params: z.record(z.string(), z.unknown()).default({}),
@@ -80,6 +105,7 @@ var ToolCallErrorPayloadSchema = z.object({
80
105
  var AnnotationPayloadSchema = z.object({
81
106
  intent: z.string().nullable().default(null),
82
107
  expected_outcome: z.string().nullable().default(null),
108
+ what_happened: z.string().nullable().default(null),
83
109
  signal_type: z.string().nullable().default(null),
84
110
  workflow: z.string().nullable().default(null),
85
111
  suggested_improvement: z.string().nullable().default(null),
@@ -96,6 +122,10 @@ var SurfaceSnapshotPayloadSchema = z.object({
96
122
  seam_augmentations: z.record(z.string(), z.unknown()).default({})
97
123
  }).strict();
98
124
  var DEFAULT_CONSENT_TOKEN = "customer-consented";
125
+ var ClientObservedSchema = z.object({
126
+ info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),
127
+ headers: z.object({ "user-agent": z.string().optional(), "x-anthropic-client": z.string().optional() }).strict().optional()
128
+ }).strict();
99
129
  var PrincipalWireSchema = z.object({
100
130
  id: z.string(),
101
131
  source: z.string(),
@@ -103,7 +133,7 @@ var PrincipalWireSchema = z.object({
103
133
  display_name: z.string().nullable().optional()
104
134
  }).strict();
105
135
  var envelopeShape = {
106
- event_id: z.uuid().default(() => uuidv7()),
136
+ event_id: z.uuid().default(() => uuid7()),
107
137
  tenant_id: z.string(),
108
138
  vendor_id: z.string(),
109
139
  session_id: z.string(),
@@ -111,9 +141,12 @@ var envelopeShape = {
111
141
  captured_at: z.string(),
112
142
  consent_token: z.string(),
113
143
  sdk_version: z.string().default(SDK_VERSION),
144
+ // Legacy (SPEC §3.4): never set by this SDK, so always the default. The
145
+ // consumer names the client from `client_observed`.
114
146
  agent_runtime: z.string().default("unknown"),
115
147
  principal: PrincipalWireSchema.nullable().default(null),
116
148
  transport_observed: z.string().nullable().default(null),
149
+ client_observed: ClientObservedSchema.nullable().default(null),
117
150
  call_id: z.string().nullable().default(null),
118
151
  runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null)
119
152
  };
@@ -137,7 +170,11 @@ var EventTypeSchema = z.enum([
137
170
  "prompt_list_error",
138
171
  "prompt_get_start",
139
172
  "prompt_get_end",
140
- "prompt_get_error"
173
+ "prompt_get_error",
174
+ // SPEC §11.4.5.
175
+ "tool_list_start",
176
+ "tool_list_end",
177
+ "tool_list_error"
141
178
  ]);
142
179
  var timingShape = { duration_ms: z.number().int().nullable().default(null) };
143
180
  var failureShape = { error_type: z.string(), error_body: z.string(), ...timingShape };
@@ -176,6 +213,14 @@ var PromptListEndPayloadSchema = z.object({
176
213
  var PromptListErrorPayloadSchema = z.object({
177
214
  ...failureShape
178
215
  }).strict();
216
+ var ToolListStartPayloadSchema = z.object({}).strict();
217
+ var ToolListEndPayloadSchema = z.object({
218
+ count: z.number().int(),
219
+ ...timingShape
220
+ }).strict();
221
+ var ToolListErrorPayloadSchema = z.object({
222
+ ...failureShape
223
+ }).strict();
179
224
  var PromptGetStartPayloadSchema = z.object({
180
225
  name: z.string(),
181
226
  /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
@@ -191,18 +236,22 @@ var PromptGetErrorPayloadSchema = z.object({
191
236
  name: z.string(),
192
237
  ...failureShape
193
238
  }).strict();
239
+ var REQUIRED_CALL_ID = z.string().min(1);
194
240
  var ToolCallStartEventSchema = z.object({
195
241
  ...envelopeShape,
242
+ call_id: REQUIRED_CALL_ID,
196
243
  event_type: z.literal("tool_call_start").default("tool_call_start"),
197
244
  payload: ToolCallStartPayloadSchema
198
245
  }).strict();
199
246
  var ToolCallEndEventSchema = z.object({
200
247
  ...envelopeShape,
248
+ call_id: REQUIRED_CALL_ID,
201
249
  event_type: z.literal("tool_call_end").default("tool_call_end"),
202
250
  payload: ToolCallEndPayloadSchema
203
251
  }).strict();
204
252
  var ToolCallErrorEventSchema = z.object({
205
253
  ...envelopeShape,
254
+ call_id: REQUIRED_CALL_ID,
206
255
  event_type: z.literal("tool_call_error").default("tool_call_error"),
207
256
  payload: ToolCallErrorPayloadSchema
208
257
  }).strict();
@@ -276,6 +325,21 @@ var PromptGetErrorEventSchema = z.object({
276
325
  event_type: z.literal("prompt_get_error").default("prompt_get_error"),
277
326
  payload: PromptGetErrorPayloadSchema
278
327
  }).strict();
328
+ var ToolListStartEventSchema = z.object({
329
+ ...envelopeShape,
330
+ event_type: z.literal("tool_list_start").default("tool_list_start"),
331
+ payload: ToolListStartPayloadSchema
332
+ }).strict();
333
+ var ToolListEndEventSchema = z.object({
334
+ ...envelopeShape,
335
+ event_type: z.literal("tool_list_end").default("tool_list_end"),
336
+ payload: ToolListEndPayloadSchema
337
+ }).strict();
338
+ var ToolListErrorEventSchema = z.object({
339
+ ...envelopeShape,
340
+ event_type: z.literal("tool_list_error").default("tool_list_error"),
341
+ payload: ToolListErrorPayloadSchema
342
+ }).strict();
279
343
  var EventSchema = z.discriminatedUnion("event_type", [
280
344
  ToolCallStartEventSchema,
281
345
  ToolCallEndEventSchema,
@@ -293,7 +357,10 @@ var EventSchema = z.discriminatedUnion("event_type", [
293
357
  PromptListErrorEventSchema,
294
358
  PromptGetStartEventSchema,
295
359
  PromptGetEndEventSchema,
296
- PromptGetErrorEventSchema
360
+ PromptGetErrorEventSchema,
361
+ ToolListStartEventSchema,
362
+ ToolListEndEventSchema,
363
+ ToolListErrorEventSchema
297
364
  ]);
298
365
 
299
366
  // src/scrub.ts
@@ -589,7 +656,6 @@ var HttpSink = class _HttpSink {
589
656
 
590
657
  // src/integrations/mcp/withBaton.ts
591
658
  import { AsyncLocalStorage } from "async_hooks";
592
- import { v7 as uuidv72 } from "uuid";
593
659
 
594
660
  // src/integrations/mcp/annotation.ts
595
661
  import { z as z2 } from "zod";
@@ -705,30 +771,21 @@ function principalFor(principal, onUnregisteredForm) {
705
771
  // src/integrations/mcp/llmText.ts
706
772
  var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} usage and friction SDK. Use \`${annotationToolName}\` to report when a ${vendorDisplayName} tool call goes wrong, or when a tool you needed does not exist, so ${vendorDisplayName} can improve their product. See that tool's description for field-level detail.
707
773
 
708
- AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` again with signal_type (REQUIRED) \u2014 one of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other \u2014 and suggested_improvement (REQUIRED whenever you can articulate one).
774
+ AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` with what_happened (REQUIRED, your own words, NOT a category), tool_name (REQUIRED) and suggested_improvement (REQUIRED whenever you can articulate one).
709
775
 
710
- IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` with signal_type='feature_gap' AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
776
+ IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` once per user request, not per call, with what_happened and tool_name (none if no tool) AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
711
777
  var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Report a ${vendorDisplayName} tool call that went wrong \u2014 call this AFTER a call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. Do NOT call it before a tool call or to narrate normal successful work.
712
778
 
713
779
  Fields:
714
780
  - user_goal: one sentence on what the user is trying to accomplish.
781
+ - what_happened: REQUIRED on a report. 1-2 plain sentences in YOUR OWN WORDS: what you asked for, what came back, and why it was unusable. Do NOT pick a category or invent a label \u2014 describe it.
782
+ - tool_name: REQUIRED on a report. The ${vendorDisplayName} tool that went wrong. Write none if no tool exists for the request.
715
783
  - expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
716
784
  - overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.
717
- - signal_type: reactive-only \u2014 omit on a proactive annotation. Set only once a tool call has returned an unhelpful result. One of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other.
718
- - suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
719
- - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. For signal_type='feature_gap' also missing_capability_field and requested_capability.`;
785
+ - suggested_improvement: A concrete sentence about what product change would have helped.
786
+ - context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
720
787
  var CLAUDE_CODE_TRUNCATION_CAP = 2087;
721
788
  var INSTRUCTIONS_LENGTH_CAP = 1500;
722
- var SIGNAL_TYPES = [
723
- "failure",
724
- "retry_loop",
725
- "dead_end",
726
- "parameter_confusion",
727
- "slow_performance",
728
- "abandonment",
729
- "feature_gap",
730
- "other"
731
- ];
732
789
  function renderServerInstructions(options) {
733
790
  return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
734
791
  }
@@ -742,7 +799,7 @@ function buildServerInstructions(options) {
742
799
  `Rendered server instructions are ${rendered.length} chars, which exceeds the ${INSTRUCTIONS_LENGTH_CAP}-char safety cap (Claude Code truncates at ~${CLAUDE_CODE_TRUNCATION_CAP}). Shorten vendorDisplayName or annotationToolName.`
743
800
  );
744
801
  }
745
- return rendered;
802
+ return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
746
803
  }
747
804
  function buildAnnotationToolDescription(options) {
748
805
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -754,16 +811,24 @@ var INTENT_SOURCE_PARAM = "injected_param";
754
811
  var USER_GOAL_PARAM_BODY = "One sentence: what the user is actually trying to accomplish with this call (their goal, not a restatement of the arguments).";
755
812
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
756
813
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
757
- var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
758
- var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. Short stable label for the broader task this call serves (e.g. 'prepare campaign approval'). REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.";
814
+ var EXPECTED_RESULT_PARAM_BODY = "One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
815
+ var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
816
+ var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
817
+ var OVERALL_TASK_PARAM_BODY = "The number of the user's current message in this conversation (1 for the first), a colon, then a short stable label for the broader task this call serves (e.g. '3: prepare campaign approval'). Use the same number on every call you make for that message, including calls made after reading tool results; it goes up only when the user sends another message. REPEAT the exact same label text after the colon on every call serving the same task, across messages; change the label only when the user starts a different task.";
818
+ var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
819
+ var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
820
+ var INSTRUCTIONS_SUBAGENT_CLAUSE = "\n\nWhen you hand work to a subagent that may call this server's tools, tell it the number of the user's current message in this conversation, and that it must start overall_task with that number on every call to this server's tools. This applies only to this server's tools.";
759
821
  function buildUserGoalParamDescription(options = {}) {
760
822
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
761
823
  }
762
- function buildOverallTaskParamDescription() {
763
- return OVERALL_TASK_PARAM_DESCRIPTION;
824
+ function buildOverallTaskParamDescription(options = {}) {
825
+ return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
764
826
  }
765
- function buildExpectedResultParamDescription() {
766
- return EXPECTED_RESULT_PARAM_DESCRIPTION;
827
+ function buildExpectedResultParamDescription(options = {}) {
828
+ return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
829
+ }
830
+ function requiredParamNames(intentParamMode) {
831
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
767
832
  }
768
833
 
769
834
  // src/integrations/mcp/annotationName.ts
@@ -905,6 +970,9 @@ function extraHeaders(extra) {
905
970
  }
906
971
  return null;
907
972
  }
973
+ function isThenable(value) {
974
+ return typeof value?.then === "function";
975
+ }
908
976
 
909
977
  // src/integrations/mcp/principalResolution.ts
910
978
  function buildPrincipalResolutionContext(extra, toolName, args) {
@@ -916,6 +984,26 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
916
984
  authInfo: extraAuthInfo(extra)
917
985
  };
918
986
  }
987
+ var HOOK_TIMEOUT_MS = 5e3;
988
+ var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
989
+ async function withinHookBudget(answer) {
990
+ if (!isThenable(answer)) return answer;
991
+ let timer;
992
+ const deadline = new Promise((resolve) => {
993
+ timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
994
+ timer.unref?.();
995
+ });
996
+ try {
997
+ const first = await Promise.race([answer, deadline]);
998
+ if (first !== TIMED_OUT) return first;
999
+ warn(
1000
+ `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
1001
+ );
1002
+ return null;
1003
+ } finally {
1004
+ clearTimeout(timer);
1005
+ }
1006
+ }
919
1007
  var warnedPreRenameShape = false;
920
1008
  function warnIfPreRenameShape(result) {
921
1009
  const userId = result?.userId;
@@ -929,7 +1017,7 @@ async function resolveCallPrincipal(hook, call) {
929
1017
  if (hook === void 0) return null;
930
1018
  try {
931
1019
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
932
- const result = await hook(context);
1020
+ const result = await withinHookBudget(hook(context));
933
1021
  const principal = normalizePrincipal(result);
934
1022
  if (principal === null) {
935
1023
  warnIfPreRenameShape(result);
@@ -966,56 +1054,67 @@ function scrubOrNull(scrubber, value, field) {
966
1054
  }
967
1055
  }
968
1056
 
969
- // src/integrations/mcp/runtimeAdapter.ts
1057
+ // src/integrations/mcp/clientObserved.ts
970
1058
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
971
- var CLIENT_NAME_MAX_LEN = 128;
972
- var UNKNOWN_AGENT_RUNTIME = "unknown";
973
- function clean(name, scrubber) {
974
- if (typeof name !== "string" || !name) return null;
975
- let cleaned = name;
976
- if (scrubber) {
977
- const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
978
- if (typeof scrubbed !== "string") return null;
979
- cleaned = scrubbed;
980
- }
981
- if (!cleaned) return null;
982
- return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
983
- }
984
- function declaredOnRequest(meta, envelope) {
985
- for (const source of [envelope, meta]) {
986
- if (!source) continue;
987
- const info = source[CLIENT_INFO_META_KEY];
988
- if (info && typeof info === "object") {
989
- const name = info.name;
990
- if (name !== void 0) return name;
991
- }
1059
+ var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
1060
+ var CLIENT_INFO_MAX_LEN = 128;
1061
+ var HEADER_VALUE_MAX_LEN = 256;
1062
+ var hasText = (value) => typeof value === "string" && value !== "";
1063
+ function declared(info) {
1064
+ if (!info || typeof info !== "object") return void 0;
1065
+ const { name, version } = info;
1066
+ return hasText(name) || hasText(version) ? { name, version } : void 0;
1067
+ }
1068
+ function declaredOnRequest(extra) {
1069
+ for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
1070
+ const found = declared(source?.[CLIENT_INFO_META_KEY]);
1071
+ if (found) return found;
992
1072
  }
993
1073
  return void 0;
994
1074
  }
995
- function declaredOnConnection(options) {
1075
+ function declaredOnConnection(server) {
1076
+ if (!server) return void 0;
1077
+ const inner = server.server;
1078
+ const holder = inner ?? server;
1079
+ if (typeof holder.getClientVersion !== "function") return void 0;
1080
+ return declared(holder.getClientVersion());
1081
+ }
1082
+ function observedInfo(extra, options) {
1083
+ const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1084
+ const info = {};
1085
+ const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1086
+ const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
1087
+ if (name !== void 0) info.name = name;
1088
+ if (version !== void 0) info.version = version;
1089
+ return Object.keys(info).length > 0 ? info : void 0;
1090
+ }
1091
+ function observedHeaders(extra, options) {
1092
+ const sent = extraHeaders(extra);
1093
+ const headers = {};
1094
+ for (const header of OBSERVED_HEADERS) {
1095
+ const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1096
+ if (value !== void 0) headers[header] = value;
1097
+ }
1098
+ return Object.keys(headers).length > 0 ? headers : void 0;
1099
+ }
1100
+ function clean(value, scrubber, max) {
1101
+ if (!hasText(value)) return void 0;
1102
+ const scrubbed = scrubOrNull(scrubber, value, "client_observed");
1103
+ if (!hasText(scrubbed)) return void 0;
1104
+ return capCodePoints(scrubbed, max);
1105
+ }
1106
+ function orNothing(read) {
996
1107
  try {
997
- const server = options.server;
998
- if (!server) return void 0;
999
- const inner = server.server;
1000
- const holder = inner ?? server;
1001
- if (typeof holder.getClientVersion !== "function") return void 0;
1002
- return holder.getClientVersion()?.name;
1108
+ return read();
1003
1109
  } catch {
1004
1110
  return void 0;
1005
1111
  }
1006
1112
  }
1007
- function detectAgentRuntime(meta, options = {}) {
1008
- const { envelope, scrubber } = options;
1009
- const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);
1010
- if (onRequest !== null) return onRequest;
1011
- const onConnection = clean(declaredOnConnection(options), scrubber);
1012
- if (onConnection !== null) return onConnection;
1013
- if (meta) {
1014
- for (const key of Object.keys(meta)) {
1015
- if (key.startsWith("claudecode/")) return "claude-code";
1016
- }
1017
- }
1018
- return null;
1113
+ function observeClient(extra, options) {
1114
+ const info = orNothing(() => observedInfo(extra, options));
1115
+ const headers = orNothing(() => observedHeaders(extra, options));
1116
+ if (info === void 0 && headers === void 0) return null;
1117
+ return { ...info && { info }, ...headers && { headers } };
1019
1118
  }
1020
1119
 
1021
1120
  // src/integrations/mcp/sessionResolution.ts
@@ -1025,6 +1124,10 @@ async function resolveSessionId(fallbackSessionId, extra) {
1025
1124
  }
1026
1125
 
1027
1126
  // src/integrations/mcp/annotation.ts
1127
+ var TOOL_NAME_PARAM_NAME = "tool_name";
1128
+ function isReport(whatHappened) {
1129
+ return typeof whatHappened === "string" && whatHappened.trim() !== "";
1130
+ }
1028
1131
  function registerAnnotationTool(server, options) {
1029
1132
  const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
1030
1133
  const description = buildAnnotationToolDescription({
@@ -1037,28 +1140,38 @@ function registerAnnotationTool(server, options) {
1037
1140
  inputSchema: {
1038
1141
  user_goal: z2.string(),
1039
1142
  expected_result: z2.string().optional(),
1040
- signal_type: z2.enum(SIGNAL_TYPES).optional(),
1143
+ what_happened: z2.string().optional(),
1144
+ // Nullable so a report whose agent sends an explicit null is taken,
1145
+ // not rejected by validation.
1146
+ tool_name: z2.string().nullable().optional(),
1041
1147
  overall_task: z2.string().optional(),
1042
1148
  suggested_improvement: z2.string().optional(),
1043
1149
  context: z2.record(z2.string(), z2.unknown()).optional()
1044
1150
  }
1045
1151
  },
1046
1152
  async (args, extra) => {
1153
+ const whatHappened = args.what_happened;
1154
+ if (!isReport(whatHappened)) {
1155
+ return {
1156
+ content: [
1157
+ {
1158
+ type: "text",
1159
+ text: JSON.stringify({
1160
+ ok: false,
1161
+ 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.`
1162
+ })
1163
+ }
1164
+ ]
1165
+ };
1166
+ }
1167
+ const reportedTool = args.tool_name ?? null;
1047
1168
  const meta = extraMeta(extra);
1048
- const runtime = detectAgentRuntime(meta, {
1049
- envelope: extraEnvelope(extra),
1050
- server,
1051
- scrubber: options.scrubber
1052
- }) ?? UNKNOWN_AGENT_RUNTIME;
1053
1169
  const scrubbedMeta = scrubOrNull(
1054
1170
  options.scrubber,
1055
1171
  meta ? roundMetaCoordinates(meta) : null,
1056
1172
  "_meta"
1057
1173
  );
1058
1174
  const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
1059
- if (args.signal_type === void 0) {
1060
- options.tracker?.mark(sessionId);
1061
- }
1062
1175
  const principal = await resolveCallPrincipal(
1063
1176
  options.resolvePrincipal,
1064
1177
  { extra, toolName: name, arguments: args }
@@ -1072,9 +1185,9 @@ function registerAnnotationTool(server, options) {
1072
1185
  sequence_number: options.counter.next(sessionId),
1073
1186
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1074
1187
  consent_token: options.consentToken,
1075
- agent_runtime: runtime,
1076
1188
  principal,
1077
1189
  transport_observed: observeTransport(extra),
1190
+ client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1078
1191
  runtime_meta: scrubbedMeta,
1079
1192
  payload: {
1080
1193
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -1083,15 +1196,10 @@ function registerAnnotationTool(server, options) {
1083
1196
  // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1084
1197
  intent: options.scrubber(args.user_goal),
1085
1198
  expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
1086
- // `signal_type` is a closed enum — nothing to scrub. The task label
1087
- // is agent-authored free text ("processing invoice for
1088
- // bob@example.com" is a realistic value), so it IS scrubbed.
1089
- // Python's annotation.py does NOT scrub this field — a shared
1090
- // gap found 2026-08-11, fixed here and flagged for the sibling
1091
- // rather than mirrored. Not a wire divergence: scrubbing changes
1092
- // content, not shape, and it's deterministic, so the
1093
- // exact-string continuity rung 3b groups on survives.
1094
- signal_type: args.signal_type ?? null,
1199
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1200
+ what_happened: options.scrubber(whatHappened),
1201
+ // eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
1202
+ tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
1095
1203
  // Agent-facing param `overall_task` -> wire key `workflow`, the same
1096
1204
  // split the injected params use (`overall_task` -> `call_workflow`):
1097
1205
  // renaming the param must not move the key the console groups on.
@@ -1381,7 +1489,7 @@ function resolveTenantId(explicit, vendorId) {
1381
1489
  if (fromEnv) return fromEnv;
1382
1490
  return vendorId;
1383
1491
  }
1384
- function resolveBatonConfig(config, serverName) {
1492
+ function resolveBatonConfig(config) {
1385
1493
  const dsnString = selectDsn(
1386
1494
  config.dsn,
1387
1495
  {
@@ -1417,14 +1525,7 @@ function resolveBatonConfig(config, serverName) {
1417
1525
  // in the server instructions and the annotation tool description, which is
1418
1526
  // the whitelabel obligation the validator cites when it refuses the empty
1419
1527
  // one. ⚠ Python uses `or` here and still has the inconsistency.
1420
- //
1421
- // Between the explicit value and the segment sits the server's own name,
1422
- // under the guards in `annotationName.ts`: the segment is an opaque
1423
- // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1424
- vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1425
- vendorId: dsn.vendorId,
1426
- annotationToolName: config.annotationToolName
1427
- }) ?? dsn.vendorId,
1528
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1428
1529
  // `??`, not `||`: an explicit empty string must survive to the validation
1429
1530
  // below and be REFUSED there, rather than be quietly replaced by the
1430
1531
  // default it was deliberately not left as.
@@ -1438,6 +1539,14 @@ function resolveBatonConfig(config, serverName) {
1438
1539
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
1439
1540
  };
1440
1541
  }
1542
+ function withServerDisplayName(resolved, supplied, serverName) {
1543
+ if (supplied.vendorDisplayName !== void 0) return resolved;
1544
+ const fromServer = displayNameFromServer(serverName, {
1545
+ vendorId: resolved.vendorId,
1546
+ annotationToolName: supplied.annotationToolName
1547
+ });
1548
+ return fromServer === void 0 ? resolved : { ...resolved, vendorDisplayName: fromServer };
1549
+ }
1441
1550
  var RENAMED_KEYS = {
1442
1551
  resolveUser: "resolvePrincipal"
1443
1552
  };
@@ -1560,11 +1669,6 @@ var ProactiveTracker = class {
1560
1669
  this.emitted.add(sessionId);
1561
1670
  return true;
1562
1671
  }
1563
- /** Mark the slot claimed without emitting here (the annotation tool's own
1564
- * handler already emitted the annotation event itself). */
1565
- mark(sessionId) {
1566
- this.emitted.add(sessionId);
1567
- }
1568
1672
  };
1569
1673
 
1570
1674
  // src/integrations/mcp/sessionCounter.ts
@@ -1674,13 +1778,8 @@ function injectGoalParams(inputSchema, intentParamMode) {
1674
1778
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1675
1779
  const dispositions = {};
1676
1780
  const toInject = {};
1677
- if (USER_GOAL_PARAM_NAME in existingShape) {
1678
- dispositions[USER_GOAL_PARAM_NAME] = "native";
1679
- } else {
1680
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
1681
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1682
- }
1683
1781
  for (const [name, buildDescription] of [
1782
+ [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1684
1783
  [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1685
1784
  [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1686
1785
  ]) {
@@ -1688,7 +1787,7 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1688
1787
  dispositions[name] = "native";
1689
1788
  } else {
1690
1789
  dispositions[name] = "injected";
1691
- toInject[name] = zodImpl.string().optional().describe(buildDescription());
1790
+ toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1692
1791
  }
1693
1792
  }
1694
1793
  return { dispositions, toInject };
@@ -1704,21 +1803,23 @@ function injectGoalParamsV2(inputSchema, intentParamMode) {
1704
1803
  return { schema: inputSchema, dispositions };
1705
1804
  return { schema: candidate.extend(toInject), dispositions };
1706
1805
  }
1707
- function advertiseUserGoalRequired(result, isInjected) {
1806
+ function advertiseIntentParamsRequired(result, names, isInjected) {
1708
1807
  const tools = result?.tools;
1709
1808
  if (!Array.isArray(tools)) return result;
1710
1809
  let changed = false;
1711
1810
  const advertised = tools.map((tool) => {
1712
1811
  const entry = tool;
1713
- if (typeof entry?.name !== "string" || !isInjected(entry.name)) return tool;
1714
- const schema = entry.inputSchema;
1812
+ const toolName = entry?.name;
1813
+ if (typeof toolName !== "string") return tool;
1814
+ const schema = entry?.inputSchema;
1715
1815
  if (!schema || typeof schema !== "object") return tool;
1716
- const declared = schema.required ?? [];
1717
- if (!Array.isArray(declared)) return tool;
1718
- const required = declared;
1719
- if (required.includes(USER_GOAL_PARAM_NAME)) return tool;
1816
+ const declared2 = schema.required ?? [];
1817
+ if (!Array.isArray(declared2)) return tool;
1818
+ const required = declared2;
1819
+ const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
1820
+ if (missing.length === 0) return tool;
1720
1821
  changed = true;
1721
- return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };
1822
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
1722
1823
  });
1723
1824
  return changed ? { ...result, tools: advertised } : result;
1724
1825
  }
@@ -1767,7 +1868,11 @@ function assembleSurface(serverMeta, tools) {
1767
1868
  function buildSeamAugmentations(options) {
1768
1869
  return {
1769
1870
  injected_tools: [...options.injectedToolNames].sort(),
1770
- intent_param: options.intentParamMode !== "off" ? { names: [...options.intentParamNames].sort(), mode: options.intentParamMode } : null,
1871
+ intent_param: options.intentParamMode !== "off" ? {
1872
+ names: [...options.intentParamNames].sort(),
1873
+ required_names: [...options.requiredParamNames].sort(),
1874
+ mode: options.intentParamMode
1875
+ } : null,
1771
1876
  instructions_suffix: true
1772
1877
  };
1773
1878
  }
@@ -1778,16 +1883,17 @@ var wired = /* @__PURE__ */ new WeakSet();
1778
1883
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1779
1884
  var callSlots = new AsyncLocalStorage();
1780
1885
  var SurfaceState = class {
1781
- constructor(serverMeta) {
1886
+ constructor(serverMeta, emittedHashes) {
1782
1887
  this.serverMeta = serverMeta;
1888
+ this.emittedHashes = emittedHashes;
1783
1889
  }
1784
1890
  serverMeta;
1891
+ emittedHashes;
1785
1892
  /** Every tool this install has seen, keyed by its CURRENT name. `disabled`
1786
1893
  * is tracked alongside rather than pruned, so re-enabling costs nothing and
1787
1894
  * — crucially — never needs a re-capture, which would re-read Baton's own
1788
1895
  * injected schema as if it were vendor-true. */
1789
1896
  rawTools = /* @__PURE__ */ new Map();
1790
- emittedHashes = /* @__PURE__ */ new Set();
1791
1897
  dirty = false;
1792
1898
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
1793
1899
  * which picks the spelling THIS SDK major puts on the wire. */
@@ -1839,23 +1945,13 @@ function messageOf(err) {
1839
1945
  }
1840
1946
  async function resolveEnvelopeParts(ctx, extra) {
1841
1947
  const meta = extraMeta(extra);
1842
- const runtime = detectAgentRuntime(meta, {
1843
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1844
- // `_meta`; 1.x leaves them in. Both are handed over — see
1845
- // `mcpTypes.extraEnvelope`.
1846
- envelope: extraEnvelope(extra),
1847
- // Tier 2's carrier: neither peer puts client identity on the
1848
- // handler context, both expose the cached handshake on the server.
1849
- server: ctx.server,
1850
- scrubber: ctx.scrubber
1851
- }) ?? UNKNOWN_AGENT_RUNTIME;
1852
1948
  const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1853
1949
  const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1854
- return { sessionId, runtime, scrubbedMeta };
1950
+ return { sessionId, scrubbedMeta };
1855
1951
  }
1856
1952
  async function openCall(ctx, toolName, extra, params, registered = true) {
1857
1953
  await maybeEmitSurfaceSnapshot(ctx);
1858
- const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1954
+ const { sessionId, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1859
1955
  const dispositions = ctx.paramRegistry.get(toolName);
1860
1956
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
1861
1957
  const rawExpected = extractGoalParam(
@@ -1869,7 +1965,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
1869
1965
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
1870
1966
  const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
1871
1967
  const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
1872
- const callId = uuidv72();
1968
+ const callId = uuid7();
1873
1969
  const principal = await resolveCallPrincipal(
1874
1970
  ctx.resolvePrincipal,
1875
1971
  { extra, toolName, arguments: params }
@@ -1879,19 +1975,12 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
1879
1975
  vendor_id: ctx.vendorId,
1880
1976
  session_id: sessionId,
1881
1977
  consent_token: ctx.consentToken,
1882
- agent_runtime: runtime,
1883
- // The five `...common` sites below are the tool-call legs — start, end,
1884
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1885
- // annotation, the same five Python stamps (`middleware.py`
1886
- // 503/547/586/644/674; it was four until the returned shape landed
1887
- // there too). `surface_snapshot` is deliberately NOT among them: it
1888
- // describes the SERVER and is captured outside any call, so there is no
1889
- // caller to name (register D5).
1978
+ // Every `...common` site is an event with a caller. `surface_snapshot`
1979
+ // is deliberately not among them: it describes the SERVER and is captured
1980
+ // outside any call, so it has no caller, transport or client to name.
1890
1981
  principal,
1891
- // Same five stamps, same exclusion: a surface_snapshot describes the
1892
- // SERVER and is captured outside any call, so it has no caller's
1893
- // transport to name any more than it has a caller to name.
1894
1982
  transport_observed: observeTransport(extra),
1983
+ client_observed: observeClient(extra, ctx),
1895
1984
  runtime_meta: scrubbedMeta
1896
1985
  };
1897
1986
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -2113,6 +2202,7 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2113
2202
  delete args[paramName];
2114
2203
  return typeof raw === "string" && raw.trim() ? raw : null;
2115
2204
  }
2205
+ var MAX_REMEMBERED_SURFACES = 1024;
2116
2206
  async function maybeEmitSurfaceSnapshot(ctx) {
2117
2207
  if (!ctx.surfaceState.dirty) return;
2118
2208
  ctx.surfaceState.dirty = false;
@@ -2126,21 +2216,24 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2126
2216
  `);
2127
2217
  return;
2128
2218
  }
2129
- if (ctx.surfaceState.emittedHashes.has(digest)) return;
2219
+ const emitted = ctx.surfaceState.emittedHashes;
2220
+ if (emitted.has(digest)) return;
2221
+ if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2222
+ emitted.add(digest);
2130
2223
  const seam = buildSeamAugmentations({
2131
2224
  injectedToolNames: [ctx.annotationToolName],
2132
2225
  intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2133
- intentParamMode: ctx.intentParamMode
2226
+ intentParamMode: ctx.intentParamMode,
2227
+ requiredParamNames: requiredParamNames(ctx.intentParamMode)
2134
2228
  });
2135
2229
  try {
2136
2230
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
2137
2231
  } catch (err) {
2138
2232
  process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
2139
2233
  `);
2234
+ emitted.delete(digest);
2140
2235
  ctx.surfaceState.dirty = true;
2141
- return;
2142
2236
  }
2143
- ctx.surfaceState.emittedHashes.add(digest);
2144
2237
  }
2145
2238
  function captureAndInject(name, entry, ctx) {
2146
2239
  if (!entry || typeof entry !== "object") return;
@@ -2154,6 +2247,7 @@ function captureAndInject(name, entry, ctx) {
2154
2247
  mutable.inputSchema = schema;
2155
2248
  ctx.bustSchemaMemo(name);
2156
2249
  ctx.paramRegistry.set(name, dispositions);
2250
+ if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2157
2251
  } else {
2158
2252
  ctx.paramRegistry.delete(name);
2159
2253
  }
@@ -2174,6 +2268,7 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2174
2268
  const handler = handlers.get(method);
2175
2269
  if (typeof handler !== "function" || handler[seamTag]) return;
2176
2270
  const seamed = wrap(handler);
2271
+ for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];
2177
2272
  seamed[seamTag] = true;
2178
2273
  handlers.set(method, seamed);
2179
2274
  };
@@ -2185,10 +2280,11 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2185
2280
  };
2186
2281
  }
2187
2282
  function installToolsListSeam(lowLevel, ctx) {
2188
- const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
2283
+ const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
2284
+ const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
2189
2285
  const advertise = (result) => {
2190
2286
  try {
2191
- return advertiseUserGoalRequired(result, isInjected);
2287
+ return advertiseIntentParamsRequired(result, names, isInjected);
2192
2288
  } catch (err) {
2193
2289
  process.stderr.write(
2194
2290
  `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
@@ -2206,7 +2302,8 @@ var LIFECYCLE_SEAMS = {
2206
2302
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2207
2303
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2208
2304
  promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2209
- promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2305
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam"),
2306
+ toolList: /* @__PURE__ */ Symbol("batonToolListSeam")
2210
2307
  };
2211
2308
  function installLifecycleSeam(lowLevel, ctx, spec) {
2212
2309
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
@@ -2253,6 +2350,11 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2253
2350
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2254
2351
  try {
2255
2352
  const parts = await resolveEnvelopeParts(ctx, extra);
2353
+ const principal = await resolveCallPrincipal(ctx.resolvePrincipal, {
2354
+ extra,
2355
+ toolName: null,
2356
+ arguments: {}
2357
+ });
2256
2358
  return {
2257
2359
  sessionId: parts.sessionId,
2258
2360
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
@@ -2261,8 +2363,9 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2261
2363
  vendor_id: ctx.vendorId,
2262
2364
  session_id: parts.sessionId,
2263
2365
  consent_token: ctx.consentToken,
2264
- agent_runtime: parts.runtime,
2366
+ principal,
2265
2367
  transport_observed: observeTransport(extra),
2368
+ client_observed: observeClient(extra, ctx),
2266
2369
  runtime_meta: parts.scrubbedMeta
2267
2370
  }
2268
2371
  };
@@ -2335,6 +2438,17 @@ var LIFECYCLE_SPECS = [
2335
2438
  startParams: (params) => ({
2336
2439
  params: paramsBag(params["arguments"])
2337
2440
  })
2441
+ },
2442
+ {
2443
+ method: TOOLS_LIST_METHOD,
2444
+ seamTag: LIFECYCLE_SEAMS.toolList,
2445
+ schemas: {
2446
+ start: ToolListStartEventSchema,
2447
+ end: ToolListEndEventSchema,
2448
+ error: ToolListErrorEventSchema
2449
+ },
2450
+ countKey: "tools",
2451
+ startParams: NO_PARAMS
2338
2452
  }
2339
2453
  ];
2340
2454
  function installLifecycleSeams(lowLevel, ctx) {
@@ -2465,9 +2579,6 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2465
2579
  })
2466
2580
  );
2467
2581
  }
2468
- function isThenable(value) {
2469
- return typeof value?.then === "function";
2470
- }
2471
2582
  function wrapIfNeeded(nameRef, entry, ctx) {
2472
2583
  if (!entry || typeof entry !== "object") return;
2473
2584
  const mutable = entry;
@@ -2543,47 +2654,57 @@ function withBaton(server, supplied = {}) {
2543
2654
  annotationToolName: ""
2544
2655
  });
2545
2656
  }
2657
+ return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
2658
+ }
2659
+ function createBaton(supplied = {}) {
2660
+ const disabledBy = captureDisabled();
2661
+ if (disabledBy !== null) {
2662
+ logDisabled(disabledBy, "createBaton");
2663
+ const unused = supplied.sink ?? new DisabledSink();
2664
+ return { wrap: () => {
2665
+ }, flush: () => unused.flush(), aclose: () => unused.aclose() };
2666
+ }
2667
+ const resolved = resolveBatonConfig(supplied);
2668
+ deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2669
+ const sink = resolved.sink ?? new StdoutSink();
2670
+ const config = {
2671
+ ...resolved,
2672
+ sink,
2673
+ tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2674
+ };
2675
+ const emittedSurfaceHashes = /* @__PURE__ */ new Set();
2676
+ return {
2677
+ wrap: (server) => {
2678
+ install(server, supplied, config, emittedSurfaceHashes);
2679
+ },
2680
+ flush: () => sink.flush(),
2681
+ aclose: () => sink.aclose()
2682
+ };
2683
+ }
2684
+ function install(server, supplied, resolved, emittedSurfaceHashes) {
2546
2685
  const internals = server;
2547
2686
  const serverName = usableServerName(() => ({
2548
2687
  name: internals.server._serverInfo?.name,
2549
2688
  className: internals.constructor.name
2550
2689
  }));
2551
- const config = resolveBatonConfig(supplied, serverName);
2690
+ const config = withServerDisplayName(resolved, supplied, serverName);
2552
2691
  const sink = config.sink ?? new StdoutSink();
2553
2692
  const annotationToolName = resolveAnnotationToolName(serverName, config);
2554
2693
  const intentParamMode = config.intentParamMode ?? "required";
2555
- const counter = new SessionCounter();
2556
- const fallbackSessionId = `sdk-${uuidv72()}`;
2694
+ const counter2 = new SessionCounter();
2695
+ const fallbackSessionId = `sdk-${uuid7()}`;
2557
2696
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
2558
2697
  const scrubber = config.scrubber ?? new Scrubber().scrub;
2559
2698
  const serverMeta = buildServerMeta(server.server);
2560
- const surfaceState = new SurfaceState(serverMeta);
2699
+ const surfaceState = new SurfaceState(serverMeta, emittedSurfaceHashes);
2561
2700
  const emitSurface = async (sessionId, digest, snapshot) => {
2562
2701
  const event = SurfaceSnapshotEventSchema.parse({
2563
2702
  tenant_id: tenantId,
2564
2703
  vendor_id: config.vendorId,
2565
2704
  session_id: sessionId,
2566
2705
  consent_token: config.consentToken,
2567
- sequence_number: counter.next(sessionId),
2706
+ sequence_number: counter2.next(sessionId),
2568
2707
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2569
- // Deliberately the literal, NOT the ladder — and an earlier comment
2570
- // here justified that by saying no call is in scope, which is false:
2571
- // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
2572
- // handshake has happened and tier 2's carrier is live in this closure.
2573
- // The real reason is that the snapshot describes the VENDOR'S SURFACE,
2574
- // which is the same whoever is calling. It is hashed and emitted at
2575
- // most once per process per surface, so the client that happens to
2576
- // trigger it is whichever one called first — attributing the surface to
2577
- // that client would read as a fact about the surface and be an accident
2578
- // of timing. Python hardcodes it from the same in-call position
2579
- // (`_tool_wrap.py`), so this is parity, not a gap.
2580
- //
2581
- // ⚠ Consequence worth knowing: one session emits `surface_snapshot`
2582
- // with `unknown` and everything else with the client's name, so a
2583
- // consumer grouping on `agent_runtime` alone sees two runtimes for one
2584
- // client. Intended; group surfaces on `(tenant_id, vendor_id,
2585
- // surface_hash)`, which is what the Console's table is keyed on.
2586
- agent_runtime: UNKNOWN_AGENT_RUNTIME,
2587
2708
  payload: {
2588
2709
  surface_hash: digest,
2589
2710
  server_info: snapshot.server_info,
@@ -2599,6 +2720,15 @@ function withBaton(server, supplied = {}) {
2599
2720
  const memo = internals._toolInputSchemaJson;
2600
2721
  if (memo && typeof memo === "object") delete memo[name];
2601
2722
  };
2723
+ const dropSubagentClause = (name) => {
2724
+ const current = internals.server._instructions;
2725
+ if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2726
+ internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2727
+ process.stderr.write(
2728
+ `baton: tool ${JSON.stringify(name)} declares its own overall_task, so the subagent sentence was removed from the server instructions; a session that already started keeps it
2729
+ `
2730
+ );
2731
+ };
2602
2732
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
2603
2733
  const vendorToolJsonSchema = (name, inputSchema) => {
2604
2734
  if (isV2Server) {
@@ -2623,7 +2753,7 @@ function withBaton(server, supplied = {}) {
2623
2753
  const tracker = new ProactiveTracker();
2624
2754
  const ctx = {
2625
2755
  sink,
2626
- counter,
2756
+ counter: counter2,
2627
2757
  tenantId,
2628
2758
  vendorId: config.vendorId,
2629
2759
  consentToken: config.consentToken,
@@ -2637,16 +2767,18 @@ function withBaton(server, supplied = {}) {
2637
2767
  resolvePrincipal: config.resolvePrincipal,
2638
2768
  vendorToolJsonSchema,
2639
2769
  bustSchemaMemo,
2770
+ dropSubagentClause,
2640
2771
  tracker,
2641
2772
  surfaceState,
2642
2773
  emitSurface
2643
2774
  };
2644
2775
  const instructions = buildServerInstructions({
2645
2776
  vendorDisplayName: config.vendorDisplayName,
2646
- annotationToolName
2777
+ annotationToolName,
2778
+ intentParamMode
2647
2779
  });
2648
2780
  internals.server._instructions = instructions;
2649
- if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
2781
+ installToolsListSeam(internals.server, ctx);
2650
2782
  installToolsCallSeam(
2651
2783
  internals.server,
2652
2784
  // ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
@@ -2676,8 +2808,7 @@ function withBaton(server, supplied = {}) {
2676
2808
  // The RESOLVED name, never `config.annotationToolName`: handing over the
2677
2809
  // raw override and letting the registration re-derive would register
2678
2810
  // `srv-..._annotate` while the instructions name the server-derived one.
2679
- annotationToolName,
2680
- tracker
2811
+ annotationToolName
2681
2812
  });
2682
2813
  const existing = internals._registeredTools;
2683
2814
  if (existing) {
@@ -2777,6 +2908,13 @@ export {
2777
2908
  ToolCallErrorPayloadSchema,
2778
2909
  ToolCallStartEventSchema,
2779
2910
  ToolCallStartPayloadSchema,
2911
+ ToolListEndEventSchema,
2912
+ ToolListEndPayloadSchema,
2913
+ ToolListErrorEventSchema,
2914
+ ToolListErrorPayloadSchema,
2915
+ ToolListStartEventSchema,
2916
+ ToolListStartPayloadSchema,
2917
+ createBaton,
2780
2918
  identityScrub,
2781
2919
  principalFromOAuthEmail,
2782
2920
  principalFromOAuthSub,