@goodtiming/baton-sdk 0.5.1 → 0.5.3

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
@@ -77,7 +77,13 @@ __export(index_exports, {
77
77
  ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
78
78
  ToolCallStartEventSchema: () => ToolCallStartEventSchema,
79
79
  ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
80
- hashPrincipalId: () => hashPrincipalId,
80
+ ToolListEndEventSchema: () => ToolListEndEventSchema,
81
+ ToolListEndPayloadSchema: () => ToolListEndPayloadSchema,
82
+ ToolListErrorEventSchema: () => ToolListErrorEventSchema,
83
+ ToolListErrorPayloadSchema: () => ToolListErrorPayloadSchema,
84
+ ToolListStartEventSchema: () => ToolListStartEventSchema,
85
+ ToolListStartPayloadSchema: () => ToolListStartPayloadSchema,
86
+ createBaton: () => createBaton,
81
87
  identityScrub: () => identityScrub,
82
88
  principalFromOAuthEmail: () => principalFromOAuthEmail,
83
89
  principalFromOAuthSub: () => principalFromOAuthSub,
@@ -87,11 +93,36 @@ __export(index_exports, {
87
93
  module.exports = __toCommonJS(index_exports);
88
94
 
89
95
  // src/version.ts
90
- var SDK_VERSION = "ts-0.5.1";
96
+ var SDK_VERSION = "ts-0.5.3";
91
97
 
92
98
  // src/events.ts
93
99
  var import_zod = require("zod");
94
- var import_uuid = require("uuid");
100
+
101
+ // src/uuid7.ts
102
+ var import_node_crypto = require("crypto");
103
+ var COUNTER_MAX = 4095;
104
+ var lastMs = -1;
105
+ var counter = 0;
106
+ function uuid7() {
107
+ const bytes = (0, import_node_crypto.randomBytes)(18);
108
+ const seed = (bytes[16] << 8 | bytes[17]) & 2047;
109
+ const now = Date.now();
110
+ if (now > lastMs) {
111
+ lastMs = now;
112
+ counter = seed;
113
+ } else if (++counter > COUNTER_MAX) {
114
+ lastMs += 1;
115
+ counter = seed;
116
+ }
117
+ bytes.writeUIntBE(lastMs, 0, 6);
118
+ bytes[6] = 112 | counter >> 8;
119
+ bytes[7] = counter & 255;
120
+ bytes[8] = 128 | bytes[8] & 63;
121
+ const hex = bytes.toString("hex", 0, 16);
122
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
123
+ }
124
+
125
+ // src/events.ts
95
126
  var ToolCallStartPayloadSchema = import_zod.z.object({
96
127
  tool_name: import_zod.z.string(),
97
128
  params: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({}),
@@ -184,6 +215,10 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
184
215
  seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
185
216
  }).strict();
186
217
  var DEFAULT_CONSENT_TOKEN = "customer-consented";
218
+ var ClientObservedSchema = import_zod.z.object({
219
+ info: import_zod.z.object({ name: import_zod.z.string().optional(), version: import_zod.z.string().optional() }).strict().optional(),
220
+ headers: import_zod.z.object({ "user-agent": import_zod.z.string().optional(), "x-anthropic-client": import_zod.z.string().optional() }).strict().optional()
221
+ }).strict();
187
222
  var PrincipalWireSchema = import_zod.z.object({
188
223
  id: import_zod.z.string(),
189
224
  source: import_zod.z.string(),
@@ -191,7 +226,7 @@ var PrincipalWireSchema = import_zod.z.object({
191
226
  display_name: import_zod.z.string().nullable().optional()
192
227
  }).strict();
193
228
  var envelopeShape = {
194
- event_id: import_zod.z.uuid().default(() => (0, import_uuid.v7)()),
229
+ event_id: import_zod.z.uuid().default(() => uuid7()),
195
230
  tenant_id: import_zod.z.string(),
196
231
  vendor_id: import_zod.z.string(),
197
232
  session_id: import_zod.z.string(),
@@ -199,9 +234,12 @@ var envelopeShape = {
199
234
  captured_at: import_zod.z.string(),
200
235
  consent_token: import_zod.z.string(),
201
236
  sdk_version: import_zod.z.string().default(SDK_VERSION),
237
+ // Legacy (SPEC §3.4): never set by this SDK, so always the default. The
238
+ // consumer names the client from `client_observed`.
202
239
  agent_runtime: import_zod.z.string().default("unknown"),
203
240
  principal: PrincipalWireSchema.nullable().default(null),
204
241
  transport_observed: import_zod.z.string().nullable().default(null),
242
+ client_observed: ClientObservedSchema.nullable().default(null),
205
243
  call_id: import_zod.z.string().nullable().default(null),
206
244
  runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
207
245
  };
@@ -225,7 +263,11 @@ var EventTypeSchema = import_zod.z.enum([
225
263
  "prompt_list_error",
226
264
  "prompt_get_start",
227
265
  "prompt_get_end",
228
- "prompt_get_error"
266
+ "prompt_get_error",
267
+ // SPEC §11.4.5.
268
+ "tool_list_start",
269
+ "tool_list_end",
270
+ "tool_list_error"
229
271
  ]);
230
272
  var timingShape = { duration_ms: import_zod.z.number().int().nullable().default(null) };
231
273
  var failureShape = { error_type: import_zod.z.string(), error_body: import_zod.z.string(), ...timingShape };
@@ -264,6 +306,14 @@ var PromptListEndPayloadSchema = import_zod.z.object({
264
306
  var PromptListErrorPayloadSchema = import_zod.z.object({
265
307
  ...failureShape
266
308
  }).strict();
309
+ var ToolListStartPayloadSchema = import_zod.z.object({}).strict();
310
+ var ToolListEndPayloadSchema = import_zod.z.object({
311
+ count: import_zod.z.number().int(),
312
+ ...timingShape
313
+ }).strict();
314
+ var ToolListErrorPayloadSchema = import_zod.z.object({
315
+ ...failureShape
316
+ }).strict();
267
317
  var PromptGetStartPayloadSchema = import_zod.z.object({
268
318
  name: import_zod.z.string(),
269
319
  /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
@@ -279,18 +329,22 @@ var PromptGetErrorPayloadSchema = import_zod.z.object({
279
329
  name: import_zod.z.string(),
280
330
  ...failureShape
281
331
  }).strict();
332
+ var REQUIRED_CALL_ID = import_zod.z.string().min(1);
282
333
  var ToolCallStartEventSchema = import_zod.z.object({
283
334
  ...envelopeShape,
335
+ call_id: REQUIRED_CALL_ID,
284
336
  event_type: import_zod.z.literal("tool_call_start").default("tool_call_start"),
285
337
  payload: ToolCallStartPayloadSchema
286
338
  }).strict();
287
339
  var ToolCallEndEventSchema = import_zod.z.object({
288
340
  ...envelopeShape,
341
+ call_id: REQUIRED_CALL_ID,
289
342
  event_type: import_zod.z.literal("tool_call_end").default("tool_call_end"),
290
343
  payload: ToolCallEndPayloadSchema
291
344
  }).strict();
292
345
  var ToolCallErrorEventSchema = import_zod.z.object({
293
346
  ...envelopeShape,
347
+ call_id: REQUIRED_CALL_ID,
294
348
  event_type: import_zod.z.literal("tool_call_error").default("tool_call_error"),
295
349
  payload: ToolCallErrorPayloadSchema
296
350
  }).strict();
@@ -364,6 +418,21 @@ var PromptGetErrorEventSchema = import_zod.z.object({
364
418
  event_type: import_zod.z.literal("prompt_get_error").default("prompt_get_error"),
365
419
  payload: PromptGetErrorPayloadSchema
366
420
  }).strict();
421
+ var ToolListStartEventSchema = import_zod.z.object({
422
+ ...envelopeShape,
423
+ event_type: import_zod.z.literal("tool_list_start").default("tool_list_start"),
424
+ payload: ToolListStartPayloadSchema
425
+ }).strict();
426
+ var ToolListEndEventSchema = import_zod.z.object({
427
+ ...envelopeShape,
428
+ event_type: import_zod.z.literal("tool_list_end").default("tool_list_end"),
429
+ payload: ToolListEndPayloadSchema
430
+ }).strict();
431
+ var ToolListErrorEventSchema = import_zod.z.object({
432
+ ...envelopeShape,
433
+ event_type: import_zod.z.literal("tool_list_error").default("tool_list_error"),
434
+ payload: ToolListErrorPayloadSchema
435
+ }).strict();
367
436
  var EventSchema = import_zod.z.discriminatedUnion("event_type", [
368
437
  ToolCallStartEventSchema,
369
438
  ToolCallEndEventSchema,
@@ -381,7 +450,10 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
381
450
  PromptListErrorEventSchema,
382
451
  PromptGetStartEventSchema,
383
452
  PromptGetEndEventSchema,
384
- PromptGetErrorEventSchema
453
+ PromptGetErrorEventSchema,
454
+ ToolListStartEventSchema,
455
+ ToolListEndEventSchema,
456
+ ToolListErrorEventSchema
385
457
  ]);
386
458
 
387
459
  // src/scrub.ts
@@ -677,7 +749,6 @@ var HttpSink = class _HttpSink {
677
749
 
678
750
  // src/integrations/mcp/withBaton.ts
679
751
  var import_node_async_hooks = require("async_hooks");
680
- var import_uuid2 = require("uuid");
681
752
 
682
753
  // src/integrations/mcp/annotation.ts
683
754
  var import_zod2 = require("zod");
@@ -727,9 +798,6 @@ function roundMetaCoordinates(meta) {
727
798
  return walk(meta, 0);
728
799
  }
729
800
 
730
- // src/identity.ts
731
- var import_node_crypto = require("crypto");
732
-
733
801
  // src/_text.ts
734
802
  function exceedsCodePoints(value, max) {
735
803
  if (value.length <= max) return false;
@@ -745,7 +813,7 @@ function capCodePoints(value, max) {
745
813
  var PRINCIPAL_SOURCE_ASSERTED = "asserted";
746
814
  var PRINCIPAL_FORM_HASHED = "hashed";
747
815
  var PRINCIPAL_FORM_RAW = "raw";
748
- var RAW_PRINCIPAL_ID_MAX_LEN = 128;
816
+ var PRINCIPAL_ID_MAX_LEN = 128;
749
817
  var DISPLAY_NAME_MAX_LEN = 128;
750
818
  var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
751
819
  function wireDisplayName(value) {
@@ -753,59 +821,40 @@ function wireDisplayName(value) {
753
821
  if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
754
822
  return value;
755
823
  }
756
- var PRINCIPAL_ID_MODE_HASHED = "hashed";
757
- var PRINCIPAL_ID_MODE_RAW = "raw";
758
- var FORM_BY_MODE = {
759
- [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,
760
- [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW
761
- };
762
- var PRINCIPAL_ID_MODES = Object.keys(
763
- FORM_BY_MODE
764
- );
824
+ var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
765
825
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
766
826
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
767
827
  var LONE_SURROGATE = /\p{Surrogate}/u;
768
- function canonicalize(rawPrincipal) {
769
- return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
770
- }
771
828
  function pythonStrip(value) {
772
829
  return value.replace(PYTHON_STRIP, "");
773
830
  }
774
- function hashPrincipalId(rawPrincipal, options) {
775
- const { tenantId, key, issuer = null } = options;
776
- let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
777
- if (issuer !== null) {
778
- message += `\0${canonicalize(issuer)}`;
779
- }
780
- const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
781
- return (0, import_node_crypto.createHmac)("sha256", keyBytes).update(message, "utf8").digest("hex");
782
- }
783
831
  function normalizePrincipal(result) {
784
832
  if (result === null || typeof result !== "object") return null;
785
833
  const candidate = result;
786
834
  if (typeof candidate.principalId !== "string") return null;
787
835
  if (LONE_SURROGATE.test(candidate.principalId)) return null;
788
- if (canonicalize(candidate.principalId) === "") return null;
789
- const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
790
- const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
791
- return typeof candidate.displayName === "string" ? { principalId: candidate.principalId, issuer, displayName: candidate.displayName } : { principalId: candidate.principalId, issuer };
792
- }
793
- function principalFor(principal, options) {
794
- let id;
795
- if (options.mode === PRINCIPAL_ID_MODE_RAW) {
796
- id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
797
- } else {
798
- if (options.key === null || options.key === void 0) return null;
799
- id = hashPrincipalId(principal.principalId, {
800
- tenantId: options.tenantId,
801
- key: options.key,
802
- issuer: principal.issuer ?? null
803
- });
836
+ if (candidate.principalId.includes("\0")) return null;
837
+ if (pythonStrip(candidate.principalId) === "") return null;
838
+ const principal = { principalId: candidate.principalId };
839
+ if (candidate.form !== void 0) principal.form = candidate.form;
840
+ if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
841
+ return principal;
842
+ }
843
+ function principalFor(principal, onUnregisteredForm) {
844
+ let form = PRINCIPAL_FORM_RAW;
845
+ if (principal.form !== void 0) {
846
+ if (PRINCIPAL_FORMS.has(principal.form)) {
847
+ form = principal.form;
848
+ } else {
849
+ onUnregisteredForm?.(principal.form);
850
+ }
804
851
  }
805
852
  const wire = {
806
- id,
853
+ // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
854
+ // an astral id cut at the boundary would ship a lone surrogate.
855
+ id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
807
856
  source: PRINCIPAL_SOURCE_ASSERTED,
808
- form: FORM_BY_MODE[options.mode]
857
+ form
809
858
  };
810
859
  const displayName = wireDisplayName(principal.displayName);
811
860
  if (displayName !== null) wire.display_name = displayName;
@@ -852,7 +901,7 @@ function buildServerInstructions(options) {
852
901
  `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.`
853
902
  );
854
903
  }
855
- return rendered;
904
+ return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
856
905
  }
857
906
  function buildAnnotationToolDescription(options) {
858
907
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -864,16 +913,24 @@ var INTENT_SOURCE_PARAM = "injected_param";
864
913
  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).";
865
914
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
866
915
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
867
- 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.";
868
- 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.";
916
+ 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.";
917
+ var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
918
+ var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
919
+ 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.";
920
+ var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
921
+ var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
922
+ 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.";
869
923
  function buildUserGoalParamDescription(options = {}) {
870
924
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
871
925
  }
872
- function buildOverallTaskParamDescription() {
873
- return OVERALL_TASK_PARAM_DESCRIPTION;
926
+ function buildOverallTaskParamDescription(options = {}) {
927
+ return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
928
+ }
929
+ function buildExpectedResultParamDescription(options = {}) {
930
+ return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
874
931
  }
875
- function buildExpectedResultParamDescription() {
876
- return EXPECTED_RESULT_PARAM_DESCRIPTION;
932
+ function requiredParamNames(intentParamMode) {
933
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
877
934
  }
878
935
 
879
936
  // src/integrations/mcp/annotationName.ts
@@ -915,12 +972,18 @@ function slugServerName(serverName) {
915
972
  const collapsed = mapped.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
916
973
  return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, "") || void 0;
917
974
  }
975
+ function toolNameCandidate(serverName) {
976
+ const slug = slugServerName(serverName);
977
+ if (slug === void 0) return void 0;
978
+ const candidate = `${slug}${SUFFIX}`;
979
+ return TOOL_NAME_PATTERN.test(candidate) ? candidate : void 0;
980
+ }
918
981
  function displayNameFromServer(serverName, tool) {
919
982
  if (serverName === void 0) return void 0;
920
- const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;
921
- if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {
983
+ const proposed = tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;
984
+ if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
922
985
  warn(
923
- `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name; keeping the DSN's server segment. Pass vendorDisplayName to choose a shorter one.`
986
+ `baton: the server name (${serverName.length} chars) does not fit the server-instructions budget as the display name beside the annotation tool ${JSON.stringify(proposed)}; keeping the DSN's server segment. Pass vendorDisplayName to name the server in fewer characters.`
924
987
  );
925
988
  return void 0;
926
989
  }
@@ -928,10 +991,8 @@ function displayNameFromServer(serverName, tool) {
928
991
  }
929
992
  function annotationToolNameFromServer(serverName, vendorDisplayName) {
930
993
  if (serverName === void 0) return void 0;
931
- const slug = slugServerName(serverName);
932
- if (slug === void 0) return void 0;
933
- const candidate = `${slug}${SUFFIX}`;
934
- if (!TOOL_NAME_PATTERN.test(candidate)) return void 0;
994
+ const candidate = toolNameCandidate(serverName);
995
+ if (candidate === void 0) return void 0;
935
996
  if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
936
997
  warn(
937
998
  `baton: the server-derived annotation tool name ${JSON.stringify(candidate)} does not fit the server-instructions budget beside the display name (${vendorDisplayName.length} chars); keeping {vendorId}_annotate. A shorter display name gets the readable one.`
@@ -1011,6 +1072,9 @@ function extraHeaders(extra) {
1011
1072
  }
1012
1073
  return null;
1013
1074
  }
1075
+ function isThenable(value) {
1076
+ return typeof value?.then === "function";
1077
+ }
1014
1078
 
1015
1079
  // src/integrations/mcp/principalResolution.ts
1016
1080
  function buildPrincipalResolutionContext(extra, toolName, args) {
@@ -1022,15 +1086,25 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
1022
1086
  authInfo: extraAuthInfo(extra)
1023
1087
  };
1024
1088
  }
1025
- function warnIfIdentityCannotResolve(config) {
1026
- if (config.resolvePrincipal === void 0) return;
1027
- if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;
1028
- if (config.principalIdHmacKey !== void 0) return;
1029
- if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
1030
- const renamed = process.env?.BATON_USER_ID_HMAC_KEY ? "BATON_USER_ID_HMAC_KEY is set, but it was renamed to BATON_PRINCIPAL_ID_HMAC_KEY in 0.3.5 and is no longer read. " : "";
1031
- process.emitWarning(
1032
- `baton: resolvePrincipal is configured but no principal HMAC key is set, so the principal is dropped from every event (events still emit). ${renamed}Set BATON_PRINCIPAL_ID_HMAC_KEY or BatonConfig.principalIdHmacKey, or pass principalIdMode: "raw" if you intend to emit the subject verbatim.`
1033
- );
1089
+ var HOOK_TIMEOUT_MS = 5e3;
1090
+ var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
1091
+ async function withinHookBudget(answer) {
1092
+ if (!isThenable(answer)) return answer;
1093
+ let timer;
1094
+ const deadline = new Promise((resolve) => {
1095
+ timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
1096
+ timer.unref?.();
1097
+ });
1098
+ try {
1099
+ const first = await Promise.race([answer, deadline]);
1100
+ if (first !== TIMED_OUT) return first;
1101
+ warn(
1102
+ `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
1103
+ );
1104
+ return null;
1105
+ } finally {
1106
+ clearTimeout(timer);
1107
+ }
1034
1108
  }
1035
1109
  var warnedPreRenameShape = false;
1036
1110
  function warnIfPreRenameShape(result) {
@@ -1041,30 +1115,28 @@ function warnIfPreRenameShape(result) {
1041
1115
  "baton: resolvePrincipal returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until the hook returns the new key."
1042
1116
  );
1043
1117
  }
1044
- async function resolveCallPrincipal(hook, call, options) {
1118
+ async function resolveCallPrincipal(hook, call) {
1045
1119
  if (hook === void 0) return null;
1046
- let result;
1047
1120
  try {
1048
1121
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
1049
- result = await hook(context);
1050
- } catch {
1051
- return null;
1052
- }
1053
- const principal = normalizePrincipal(result);
1054
- if (principal === null) {
1055
- warnIfPreRenameShape(result);
1056
- return null;
1057
- }
1058
- try {
1059
- return principalFor(principal, {
1060
- mode: options.mode,
1061
- tenantId: options.tenantId,
1062
- key: options.key
1122
+ const result = await withinHookBudget(hook(context));
1123
+ const principal = normalizePrincipal(result);
1124
+ if (principal === null) {
1125
+ warnIfPreRenameShape(result);
1126
+ return null;
1127
+ }
1128
+ return principalFor(principal, (form) => {
1129
+ warn(
1130
+ `baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
1131
+ );
1063
1132
  });
1064
1133
  } catch {
1065
1134
  return null;
1066
1135
  }
1067
1136
  }
1137
+ function describeForm(form) {
1138
+ return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
1139
+ }
1068
1140
 
1069
1141
  // src/integrations/mcp/safeScrub.ts
1070
1142
  var warned = /* @__PURE__ */ new Set();
@@ -1084,56 +1156,67 @@ function scrubOrNull(scrubber, value, field) {
1084
1156
  }
1085
1157
  }
1086
1158
 
1087
- // src/integrations/mcp/runtimeAdapter.ts
1159
+ // src/integrations/mcp/clientObserved.ts
1088
1160
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
1089
- var CLIENT_NAME_MAX_LEN = 128;
1090
- var UNKNOWN_AGENT_RUNTIME = "unknown";
1091
- function clean(name, scrubber) {
1092
- if (typeof name !== "string" || !name) return null;
1093
- let cleaned = name;
1094
- if (scrubber) {
1095
- const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
1096
- if (typeof scrubbed !== "string") return null;
1097
- cleaned = scrubbed;
1098
- }
1099
- if (!cleaned) return null;
1100
- return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
1101
- }
1102
- function declaredOnRequest(meta, envelope) {
1103
- for (const source of [envelope, meta]) {
1104
- if (!source) continue;
1105
- const info = source[CLIENT_INFO_META_KEY];
1106
- if (info && typeof info === "object") {
1107
- const name = info.name;
1108
- if (name !== void 0) return name;
1109
- }
1161
+ var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
1162
+ var CLIENT_INFO_MAX_LEN = 128;
1163
+ var HEADER_VALUE_MAX_LEN = 256;
1164
+ var hasText = (value) => typeof value === "string" && value !== "";
1165
+ function declared(info) {
1166
+ if (!info || typeof info !== "object") return void 0;
1167
+ const { name, version } = info;
1168
+ return hasText(name) || hasText(version) ? { name, version } : void 0;
1169
+ }
1170
+ function declaredOnRequest(extra) {
1171
+ for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
1172
+ const found = declared(source?.[CLIENT_INFO_META_KEY]);
1173
+ if (found) return found;
1110
1174
  }
1111
1175
  return void 0;
1112
1176
  }
1113
- function declaredOnConnection(options) {
1177
+ function declaredOnConnection(server) {
1178
+ if (!server) return void 0;
1179
+ const inner = server.server;
1180
+ const holder = inner ?? server;
1181
+ if (typeof holder.getClientVersion !== "function") return void 0;
1182
+ return declared(holder.getClientVersion());
1183
+ }
1184
+ function observedInfo(extra, options) {
1185
+ const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1186
+ const info = {};
1187
+ const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1188
+ const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
1189
+ if (name !== void 0) info.name = name;
1190
+ if (version !== void 0) info.version = version;
1191
+ return Object.keys(info).length > 0 ? info : void 0;
1192
+ }
1193
+ function observedHeaders(extra, options) {
1194
+ const sent = extraHeaders(extra);
1195
+ const headers = {};
1196
+ for (const header of OBSERVED_HEADERS) {
1197
+ const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1198
+ if (value !== void 0) headers[header] = value;
1199
+ }
1200
+ return Object.keys(headers).length > 0 ? headers : void 0;
1201
+ }
1202
+ function clean(value, scrubber, max) {
1203
+ if (!hasText(value)) return void 0;
1204
+ const scrubbed = scrubOrNull(scrubber, value, "client_observed");
1205
+ if (!hasText(scrubbed)) return void 0;
1206
+ return capCodePoints(scrubbed, max);
1207
+ }
1208
+ function orNothing(read) {
1114
1209
  try {
1115
- const server = options.server;
1116
- if (!server) return void 0;
1117
- const inner = server.server;
1118
- const holder = inner ?? server;
1119
- if (typeof holder.getClientVersion !== "function") return void 0;
1120
- return holder.getClientVersion()?.name;
1210
+ return read();
1121
1211
  } catch {
1122
1212
  return void 0;
1123
1213
  }
1124
1214
  }
1125
- function detectAgentRuntime(meta, options = {}) {
1126
- const { envelope, scrubber } = options;
1127
- const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);
1128
- if (onRequest !== null) return onRequest;
1129
- const onConnection = clean(declaredOnConnection(options), scrubber);
1130
- if (onConnection !== null) return onConnection;
1131
- if (meta) {
1132
- for (const key of Object.keys(meta)) {
1133
- if (key.startsWith("claudecode/")) return "claude-code";
1134
- }
1135
- }
1136
- return null;
1215
+ function observeClient(extra, options) {
1216
+ const info = orNothing(() => observedInfo(extra, options));
1217
+ const headers = orNothing(() => observedHeaders(extra, options));
1218
+ if (info === void 0 && headers === void 0) return null;
1219
+ return { ...info && { info }, ...headers && { headers } };
1137
1220
  }
1138
1221
 
1139
1222
  // src/integrations/mcp/sessionResolution.ts
@@ -1163,11 +1246,6 @@ function registerAnnotationTool(server, options) {
1163
1246
  },
1164
1247
  async (args, extra) => {
1165
1248
  const meta = extraMeta(extra);
1166
- const runtime = detectAgentRuntime(meta, {
1167
- envelope: extraEnvelope(extra),
1168
- server,
1169
- scrubber: options.scrubber
1170
- }) ?? UNKNOWN_AGENT_RUNTIME;
1171
1249
  const scrubbedMeta = scrubOrNull(
1172
1250
  options.scrubber,
1173
1251
  meta ? roundMetaCoordinates(meta) : null,
@@ -1179,12 +1257,7 @@ function registerAnnotationTool(server, options) {
1179
1257
  }
1180
1258
  const principal = await resolveCallPrincipal(
1181
1259
  options.resolvePrincipal,
1182
- { extra, toolName: name, arguments: args },
1183
- {
1184
- mode: options.principalIdMode,
1185
- tenantId: options.tenantId,
1186
- key: options.principalIdHmacKey
1187
- }
1260
+ { extra, toolName: name, arguments: args }
1188
1261
  );
1189
1262
  await emit(
1190
1263
  options.sink,
@@ -1195,9 +1268,9 @@ function registerAnnotationTool(server, options) {
1195
1268
  sequence_number: options.counter.next(sessionId),
1196
1269
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1197
1270
  consent_token: options.consentToken,
1198
- agent_runtime: runtime,
1199
1271
  principal,
1200
1272
  transport_observed: observeTransport(extra),
1273
+ client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1201
1274
  runtime_meta: scrubbedMeta,
1202
1275
  payload: {
1203
1276
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -1498,19 +1571,13 @@ function requestSideErrorFields(text, errorBody2) {
1498
1571
  // src/integrations/mcp/config.ts
1499
1572
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1500
1573
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1501
- var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1502
1574
  function resolveTenantId(explicit, vendorId) {
1503
1575
  if (explicit) return explicit;
1504
1576
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1505
1577
  if (fromEnv) return fromEnv;
1506
1578
  return vendorId;
1507
1579
  }
1508
- function resolvePrincipalIdHmacKey(explicit) {
1509
- if (explicit !== void 0) return explicit;
1510
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : void 0;
1511
- return fromEnv ? fromEnv : void 0;
1512
- }
1513
- function resolveBatonConfig(config, serverName) {
1580
+ function resolveBatonConfig(config) {
1514
1581
  const dsnString = selectDsn(
1515
1582
  config.dsn,
1516
1583
  {
@@ -1546,14 +1613,7 @@ function resolveBatonConfig(config, serverName) {
1546
1613
  // in the server instructions and the annotation tool description, which is
1547
1614
  // the whitelabel obligation the validator cites when it refuses the empty
1548
1615
  // one. ⚠ Python uses `or` here and still has the inconsistency.
1549
- //
1550
- // Between the explicit value and the segment sits the server's own name,
1551
- // under the guards in `annotationName.ts`: the segment is an opaque
1552
- // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1553
- vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1554
- vendorId: dsn.vendorId,
1555
- annotationToolName: config.annotationToolName
1556
- }) ?? dsn.vendorId,
1616
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1557
1617
  // `??`, not `||`: an explicit empty string must survive to the validation
1558
1618
  // below and be REFUSED there, rather than be quietly replaced by the
1559
1619
  // default it was deliberately not left as.
@@ -1567,10 +1627,16 @@ function resolveBatonConfig(config, serverName) {
1567
1627
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
1568
1628
  };
1569
1629
  }
1630
+ function withServerDisplayName(resolved, supplied, serverName) {
1631
+ if (supplied.vendorDisplayName !== void 0) return resolved;
1632
+ const fromServer = displayNameFromServer(serverName, {
1633
+ vendorId: resolved.vendorId,
1634
+ annotationToolName: supplied.annotationToolName
1635
+ });
1636
+ return fromServer === void 0 ? resolved : { ...resolved, vendorDisplayName: fromServer };
1637
+ }
1570
1638
  var RENAMED_KEYS = {
1571
- resolveUser: "resolvePrincipal",
1572
- userIdMode: "principalIdMode",
1573
- userIdHmacKey: "principalIdHmacKey"
1639
+ resolveUser: "resolvePrincipal"
1574
1640
  };
1575
1641
  function validateBatonConfig(config) {
1576
1642
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
@@ -1619,14 +1685,6 @@ function validateBatonConfig(config) {
1619
1685
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1620
1686
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1621
1687
  }
1622
- if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1623
- throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1624
- }
1625
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1626
- throw new Error(
1627
- `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODE_SET].sort())}.`
1628
- );
1629
- }
1630
1688
  }
1631
1689
 
1632
1690
  // src/optout.ts
@@ -1813,13 +1871,8 @@ function injectGoalParams(inputSchema, intentParamMode) {
1813
1871
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1814
1872
  const dispositions = {};
1815
1873
  const toInject = {};
1816
- if (USER_GOAL_PARAM_NAME in existingShape) {
1817
- dispositions[USER_GOAL_PARAM_NAME] = "native";
1818
- } else {
1819
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
1820
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1821
- }
1822
1874
  for (const [name, buildDescription] of [
1875
+ [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1823
1876
  [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1824
1877
  [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1825
1878
  ]) {
@@ -1827,7 +1880,7 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1827
1880
  dispositions[name] = "native";
1828
1881
  } else {
1829
1882
  dispositions[name] = "injected";
1830
- toInject[name] = zodImpl.string().optional().describe(buildDescription());
1883
+ toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1831
1884
  }
1832
1885
  }
1833
1886
  return { dispositions, toInject };
@@ -1843,21 +1896,23 @@ function injectGoalParamsV2(inputSchema, intentParamMode) {
1843
1896
  return { schema: inputSchema, dispositions };
1844
1897
  return { schema: candidate.extend(toInject), dispositions };
1845
1898
  }
1846
- function advertiseUserGoalRequired(result, isInjected) {
1899
+ function advertiseIntentParamsRequired(result, names, isInjected) {
1847
1900
  const tools = result?.tools;
1848
1901
  if (!Array.isArray(tools)) return result;
1849
1902
  let changed = false;
1850
1903
  const advertised = tools.map((tool) => {
1851
1904
  const entry = tool;
1852
- if (typeof entry?.name !== "string" || !isInjected(entry.name)) return tool;
1853
- const schema = entry.inputSchema;
1905
+ const toolName = entry?.name;
1906
+ if (typeof toolName !== "string") return tool;
1907
+ const schema = entry?.inputSchema;
1854
1908
  if (!schema || typeof schema !== "object") return tool;
1855
- const declared = schema.required ?? [];
1856
- if (!Array.isArray(declared)) return tool;
1857
- const required = declared;
1858
- if (required.includes(USER_GOAL_PARAM_NAME)) return tool;
1909
+ const declared2 = schema.required ?? [];
1910
+ if (!Array.isArray(declared2)) return tool;
1911
+ const required = declared2;
1912
+ const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
1913
+ if (missing.length === 0) return tool;
1859
1914
  changed = true;
1860
- return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };
1915
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
1861
1916
  });
1862
1917
  return changed ? { ...result, tools: advertised } : result;
1863
1918
  }
@@ -1906,7 +1961,11 @@ function assembleSurface(serverMeta, tools) {
1906
1961
  function buildSeamAugmentations(options) {
1907
1962
  return {
1908
1963
  injected_tools: [...options.injectedToolNames].sort(),
1909
- intent_param: options.intentParamMode !== "off" ? { names: [...options.intentParamNames].sort(), mode: options.intentParamMode } : null,
1964
+ intent_param: options.intentParamMode !== "off" ? {
1965
+ names: [...options.intentParamNames].sort(),
1966
+ required_names: [...options.requiredParamNames].sort(),
1967
+ mode: options.intentParamMode
1968
+ } : null,
1910
1969
  instructions_suffix: true
1911
1970
  };
1912
1971
  }
@@ -1917,16 +1976,17 @@ var wired = /* @__PURE__ */ new WeakSet();
1917
1976
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1918
1977
  var callSlots = new import_node_async_hooks.AsyncLocalStorage();
1919
1978
  var SurfaceState = class {
1920
- constructor(serverMeta) {
1979
+ constructor(serverMeta, emittedHashes) {
1921
1980
  this.serverMeta = serverMeta;
1981
+ this.emittedHashes = emittedHashes;
1922
1982
  }
1923
1983
  serverMeta;
1984
+ emittedHashes;
1924
1985
  /** Every tool this install has seen, keyed by its CURRENT name. `disabled`
1925
1986
  * is tracked alongside rather than pruned, so re-enabling costs nothing and
1926
1987
  * — crucially — never needs a re-capture, which would re-read Baton's own
1927
1988
  * injected schema as if it were vendor-true. */
1928
1989
  rawTools = /* @__PURE__ */ new Map();
1929
- emittedHashes = /* @__PURE__ */ new Set();
1930
1990
  dirty = false;
1931
1991
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
1932
1992
  * which picks the spelling THIS SDK major puts on the wire. */
@@ -1978,23 +2038,13 @@ function messageOf(err) {
1978
2038
  }
1979
2039
  async function resolveEnvelopeParts(ctx, extra) {
1980
2040
  const meta = extraMeta(extra);
1981
- const runtime = detectAgentRuntime(meta, {
1982
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1983
- // `_meta`; 1.x leaves them in. Both are handed over — see
1984
- // `mcpTypes.extraEnvelope`.
1985
- envelope: extraEnvelope(extra),
1986
- // Tier 2's carrier: neither peer puts client identity on the
1987
- // handler context, both expose the cached handshake on the server.
1988
- server: ctx.server,
1989
- scrubber: ctx.scrubber
1990
- }) ?? UNKNOWN_AGENT_RUNTIME;
1991
2041
  const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1992
2042
  const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1993
- return { sessionId, runtime, scrubbedMeta };
2043
+ return { sessionId, scrubbedMeta };
1994
2044
  }
1995
2045
  async function openCall(ctx, toolName, extra, params, registered = true) {
1996
2046
  await maybeEmitSurfaceSnapshot(ctx);
1997
- const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
2047
+ const { sessionId, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1998
2048
  const dispositions = ctx.paramRegistry.get(toolName);
1999
2049
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
2000
2050
  const rawExpected = extractGoalParam(
@@ -2008,30 +2058,22 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
2008
2058
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
2009
2059
  const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
2010
2060
  const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
2011
- const callId = (0, import_uuid2.v7)();
2061
+ const callId = uuid7();
2012
2062
  const principal = await resolveCallPrincipal(
2013
2063
  ctx.resolvePrincipal,
2014
- { extra, toolName, arguments: params },
2015
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
2064
+ { extra, toolName, arguments: params }
2016
2065
  );
2017
2066
  const common = {
2018
2067
  tenant_id: ctx.tenantId,
2019
2068
  vendor_id: ctx.vendorId,
2020
2069
  session_id: sessionId,
2021
2070
  consent_token: ctx.consentToken,
2022
- agent_runtime: runtime,
2023
- // The five `...common` sites below are the tool-call legs — start, end,
2024
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
2025
- // annotation, the same five Python stamps (`middleware.py`
2026
- // 503/547/586/644/674; it was four until the returned shape landed
2027
- // there too). `surface_snapshot` is deliberately NOT among them: it
2028
- // describes the SERVER and is captured outside any call, so there is no
2029
- // caller to name (register D5).
2071
+ // Every `...common` site is an event with a caller. `surface_snapshot`
2072
+ // is deliberately not among them: it describes the SERVER and is captured
2073
+ // outside any call, so it has no caller, transport or client to name.
2030
2074
  principal,
2031
- // Same five stamps, same exclusion: a surface_snapshot describes the
2032
- // SERVER and is captured outside any call, so it has no caller's
2033
- // transport to name any more than it has a caller to name.
2034
2075
  transport_observed: observeTransport(extra),
2076
+ client_observed: observeClient(extra, ctx),
2035
2077
  runtime_meta: scrubbedMeta
2036
2078
  };
2037
2079
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -2253,6 +2295,7 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2253
2295
  delete args[paramName];
2254
2296
  return typeof raw === "string" && raw.trim() ? raw : null;
2255
2297
  }
2298
+ var MAX_REMEMBERED_SURFACES = 1024;
2256
2299
  async function maybeEmitSurfaceSnapshot(ctx) {
2257
2300
  if (!ctx.surfaceState.dirty) return;
2258
2301
  ctx.surfaceState.dirty = false;
@@ -2266,21 +2309,24 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2266
2309
  `);
2267
2310
  return;
2268
2311
  }
2269
- if (ctx.surfaceState.emittedHashes.has(digest)) return;
2312
+ const emitted = ctx.surfaceState.emittedHashes;
2313
+ if (emitted.has(digest)) return;
2314
+ if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2315
+ emitted.add(digest);
2270
2316
  const seam = buildSeamAugmentations({
2271
2317
  injectedToolNames: [ctx.annotationToolName],
2272
2318
  intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2273
- intentParamMode: ctx.intentParamMode
2319
+ intentParamMode: ctx.intentParamMode,
2320
+ requiredParamNames: requiredParamNames(ctx.intentParamMode)
2274
2321
  });
2275
2322
  try {
2276
2323
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
2277
2324
  } catch (err) {
2278
2325
  process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
2279
2326
  `);
2327
+ emitted.delete(digest);
2280
2328
  ctx.surfaceState.dirty = true;
2281
- return;
2282
2329
  }
2283
- ctx.surfaceState.emittedHashes.add(digest);
2284
2330
  }
2285
2331
  function captureAndInject(name, entry, ctx) {
2286
2332
  if (!entry || typeof entry !== "object") return;
@@ -2294,6 +2340,7 @@ function captureAndInject(name, entry, ctx) {
2294
2340
  mutable.inputSchema = schema;
2295
2341
  ctx.bustSchemaMemo(name);
2296
2342
  ctx.paramRegistry.set(name, dispositions);
2343
+ if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2297
2344
  } else {
2298
2345
  ctx.paramRegistry.delete(name);
2299
2346
  }
@@ -2314,6 +2361,7 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2314
2361
  const handler = handlers.get(method);
2315
2362
  if (typeof handler !== "function" || handler[seamTag]) return;
2316
2363
  const seamed = wrap(handler);
2364
+ for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];
2317
2365
  seamed[seamTag] = true;
2318
2366
  handlers.set(method, seamed);
2319
2367
  };
@@ -2325,10 +2373,11 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2325
2373
  };
2326
2374
  }
2327
2375
  function installToolsListSeam(lowLevel, ctx) {
2328
- const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
2376
+ const names = requiredParamNames(ctx.intentParamMode);
2377
+ const isInjected = (toolName, paramName) => ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
2329
2378
  const advertise = (result) => {
2330
2379
  try {
2331
- return advertiseUserGoalRequired(result, isInjected);
2380
+ return advertiseIntentParamsRequired(result, names, isInjected);
2332
2381
  } catch (err) {
2333
2382
  process.stderr.write(
2334
2383
  `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
@@ -2346,7 +2395,8 @@ var LIFECYCLE_SEAMS = {
2346
2395
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2347
2396
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2348
2397
  promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2349
- promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2398
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam"),
2399
+ toolList: /* @__PURE__ */ Symbol("batonToolListSeam")
2350
2400
  };
2351
2401
  function installLifecycleSeam(lowLevel, ctx, spec) {
2352
2402
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
@@ -2393,6 +2443,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2393
2443
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2394
2444
  try {
2395
2445
  const parts = await resolveEnvelopeParts(ctx, extra);
2446
+ const principal = spec.resolvesPrincipal ? await resolveCallPrincipal(ctx.resolvePrincipal, { extra, toolName: null, arguments: {} }) : null;
2396
2447
  return {
2397
2448
  sessionId: parts.sessionId,
2398
2449
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
@@ -2401,8 +2452,9 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2401
2452
  vendor_id: ctx.vendorId,
2402
2453
  session_id: parts.sessionId,
2403
2454
  consent_token: ctx.consentToken,
2404
- agent_runtime: parts.runtime,
2455
+ principal,
2405
2456
  transport_observed: observeTransport(extra),
2457
+ client_observed: observeClient(extra, ctx),
2406
2458
  runtime_meta: parts.scrubbedMeta
2407
2459
  }
2408
2460
  };
@@ -2475,6 +2527,18 @@ var LIFECYCLE_SPECS = [
2475
2527
  startParams: (params) => ({
2476
2528
  params: paramsBag(params["arguments"])
2477
2529
  })
2530
+ },
2531
+ {
2532
+ method: TOOLS_LIST_METHOD,
2533
+ seamTag: LIFECYCLE_SEAMS.toolList,
2534
+ schemas: {
2535
+ start: ToolListStartEventSchema,
2536
+ end: ToolListEndEventSchema,
2537
+ error: ToolListErrorEventSchema
2538
+ },
2539
+ countKey: "tools",
2540
+ startParams: NO_PARAMS,
2541
+ resolvesPrincipal: true
2478
2542
  }
2479
2543
  ];
2480
2544
  function installLifecycleSeams(lowLevel, ctx) {
@@ -2605,9 +2669,6 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2605
2669
  })
2606
2670
  );
2607
2671
  }
2608
- function isThenable(value) {
2609
- return typeof value?.then === "function";
2610
- }
2611
2672
  function wrapIfNeeded(nameRef, entry, ctx) {
2612
2673
  if (!entry || typeof entry !== "object") return;
2613
2674
  const mutable = entry;
@@ -2683,47 +2744,57 @@ function withBaton(server, supplied = {}) {
2683
2744
  annotationToolName: ""
2684
2745
  });
2685
2746
  }
2747
+ return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
2748
+ }
2749
+ function createBaton(supplied = {}) {
2750
+ const disabledBy = captureDisabled();
2751
+ if (disabledBy !== null) {
2752
+ logDisabled(disabledBy, "createBaton");
2753
+ const unused = supplied.sink ?? new DisabledSink();
2754
+ return { wrap: () => {
2755
+ }, flush: () => unused.flush(), aclose: () => unused.aclose() };
2756
+ }
2757
+ const resolved = resolveBatonConfig(supplied);
2758
+ deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2759
+ const sink = resolved.sink ?? new StdoutSink();
2760
+ const config = {
2761
+ ...resolved,
2762
+ sink,
2763
+ tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2764
+ };
2765
+ const emittedSurfaceHashes = /* @__PURE__ */ new Set();
2766
+ return {
2767
+ wrap: (server) => {
2768
+ install(server, supplied, config, emittedSurfaceHashes);
2769
+ },
2770
+ flush: () => sink.flush(),
2771
+ aclose: () => sink.aclose()
2772
+ };
2773
+ }
2774
+ function install(server, supplied, resolved, emittedSurfaceHashes) {
2686
2775
  const internals = server;
2687
2776
  const serverName = usableServerName(() => ({
2688
2777
  name: internals.server._serverInfo?.name,
2689
2778
  className: internals.constructor.name
2690
2779
  }));
2691
- const config = resolveBatonConfig(supplied, serverName);
2780
+ const config = withServerDisplayName(resolved, supplied, serverName);
2692
2781
  const sink = config.sink ?? new StdoutSink();
2693
2782
  const annotationToolName = resolveAnnotationToolName(serverName, config);
2694
2783
  const intentParamMode = config.intentParamMode ?? "required";
2695
- const counter = new SessionCounter();
2696
- const fallbackSessionId = `sdk-${(0, import_uuid2.v7)()}`;
2784
+ const counter2 = new SessionCounter();
2785
+ const fallbackSessionId = `sdk-${uuid7()}`;
2697
2786
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
2698
2787
  const scrubber = config.scrubber ?? new Scrubber().scrub;
2699
2788
  const serverMeta = buildServerMeta(server.server);
2700
- const surfaceState = new SurfaceState(serverMeta);
2789
+ const surfaceState = new SurfaceState(serverMeta, emittedSurfaceHashes);
2701
2790
  const emitSurface = async (sessionId, digest, snapshot) => {
2702
2791
  const event = SurfaceSnapshotEventSchema.parse({
2703
2792
  tenant_id: tenantId,
2704
2793
  vendor_id: config.vendorId,
2705
2794
  session_id: sessionId,
2706
2795
  consent_token: config.consentToken,
2707
- sequence_number: counter.next(sessionId),
2796
+ sequence_number: counter2.next(sessionId),
2708
2797
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2709
- // Deliberately the literal, NOT the ladder — and an earlier comment
2710
- // here justified that by saying no call is in scope, which is false:
2711
- // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
2712
- // handshake has happened and tier 2's carrier is live in this closure.
2713
- // The real reason is that the snapshot describes the VENDOR'S SURFACE,
2714
- // which is the same whoever is calling. It is hashed and emitted at
2715
- // most once per process per surface, so the client that happens to
2716
- // trigger it is whichever one called first — attributing the surface to
2717
- // that client would read as a fact about the surface and be an accident
2718
- // of timing. Python hardcodes it from the same in-call position
2719
- // (`_tool_wrap.py`), so this is parity, not a gap.
2720
- //
2721
- // ⚠ Consequence worth knowing: one session emits `surface_snapshot`
2722
- // with `unknown` and everything else with the client's name, so a
2723
- // consumer grouping on `agent_runtime` alone sees two runtimes for one
2724
- // client. Intended; group surfaces on `(tenant_id, vendor_id,
2725
- // surface_hash)`, which is what the Console's table is keyed on.
2726
- agent_runtime: UNKNOWN_AGENT_RUNTIME,
2727
2798
  payload: {
2728
2799
  surface_hash: digest,
2729
2800
  server_info: snapshot.server_info,
@@ -2739,6 +2810,15 @@ function withBaton(server, supplied = {}) {
2739
2810
  const memo = internals._toolInputSchemaJson;
2740
2811
  if (memo && typeof memo === "object") delete memo[name];
2741
2812
  };
2813
+ const dropSubagentClause = (name) => {
2814
+ const current = internals.server._instructions;
2815
+ if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2816
+ internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2817
+ process.stderr.write(
2818
+ `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
2819
+ `
2820
+ );
2821
+ };
2742
2822
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
2743
2823
  const vendorToolJsonSchema = (name, inputSchema) => {
2744
2824
  if (isV2Server) {
@@ -2763,7 +2843,7 @@ function withBaton(server, supplied = {}) {
2763
2843
  const tracker = new ProactiveTracker();
2764
2844
  const ctx = {
2765
2845
  sink,
2766
- counter,
2846
+ counter: counter2,
2767
2847
  tenantId,
2768
2848
  vendorId: config.vendorId,
2769
2849
  consentToken: config.consentToken,
@@ -2775,18 +2855,17 @@ function withBaton(server, supplied = {}) {
2775
2855
  resultCaptureMode: config.resultCaptureMode ?? "full",
2776
2856
  paramRegistry: /* @__PURE__ */ new Map(),
2777
2857
  resolvePrincipal: config.resolvePrincipal,
2778
- principalIdMode: config.principalIdMode ?? "hashed",
2779
- principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),
2780
2858
  vendorToolJsonSchema,
2781
2859
  bustSchemaMemo,
2860
+ dropSubagentClause,
2782
2861
  tracker,
2783
2862
  surfaceState,
2784
2863
  emitSurface
2785
2864
  };
2786
- warnIfIdentityCannotResolve(ctx);
2787
2865
  const instructions = buildServerInstructions({
2788
2866
  vendorDisplayName: config.vendorDisplayName,
2789
- annotationToolName
2867
+ annotationToolName,
2868
+ intentParamMode
2790
2869
  });
2791
2870
  internals.server._instructions = instructions;
2792
2871
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
@@ -2813,15 +2892,7 @@ function withBaton(server, supplied = {}) {
2813
2892
  vendorId: ctx.vendorId,
2814
2893
  vendorDisplayName: config.vendorDisplayName,
2815
2894
  consentToken: ctx.consentToken,
2816
- // Read off `ctx`, never re-resolved from `config`: the two paths must
2817
- // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a
2818
- // default and an env fallback that a second resolution could take
2819
- // differently. Required (not optional) on the options type ON PURPOSE —
2820
- // the compiler then refuses a registration that forgets them, which is
2821
- // the mechanical version of "wiring two of four call sites".
2822
2895
  resolvePrincipal: ctx.resolvePrincipal,
2823
- principalIdMode: ctx.principalIdMode,
2824
- principalIdHmacKey: ctx.principalIdHmacKey,
2825
2896
  fallbackSessionId: ctx.fallbackSessionId,
2826
2897
  scrubber: ctx.scrubber,
2827
2898
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -2867,8 +2938,7 @@ function principalFromOAuthSub(context) {
2867
2938
  const claims = claimsOf(context);
2868
2939
  if (claims === null) return null;
2869
2940
  const sub = stringClaim(claims, "sub");
2870
- const iss = claims.iss;
2871
- return sub === null ? null : { principalId: sub, issuer: typeof iss === "string" && iss !== "" ? iss : null };
2941
+ return sub === null ? null : { principalId: sub };
2872
2942
  }
2873
2943
  function principalFromOAuthEmail(context) {
2874
2944
  const claims = claimsOf(context);
@@ -2930,7 +3000,13 @@ function principalFromOAuthEmail(context) {
2930
3000
  ToolCallErrorPayloadSchema,
2931
3001
  ToolCallStartEventSchema,
2932
3002
  ToolCallStartPayloadSchema,
2933
- hashPrincipalId,
3003
+ ToolListEndEventSchema,
3004
+ ToolListEndPayloadSchema,
3005
+ ToolListErrorEventSchema,
3006
+ ToolListErrorPayloadSchema,
3007
+ ToolListStartEventSchema,
3008
+ ToolListStartPayloadSchema,
3009
+ createBaton,
2934
3010
  identityScrub,
2935
3011
  principalFromOAuthEmail,
2936
3012
  principalFromOAuthSub,