@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.js CHANGED
@@ -1,9 +1,34 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.5.1";
2
+ var SDK_VERSION = "ts-0.5.3";
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({}),
@@ -96,6 +121,10 @@ var SurfaceSnapshotPayloadSchema = z.object({
96
121
  seam_augmentations: z.record(z.string(), z.unknown()).default({})
97
122
  }).strict();
98
123
  var DEFAULT_CONSENT_TOKEN = "customer-consented";
124
+ var ClientObservedSchema = z.object({
125
+ info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),
126
+ headers: z.object({ "user-agent": z.string().optional(), "x-anthropic-client": z.string().optional() }).strict().optional()
127
+ }).strict();
99
128
  var PrincipalWireSchema = z.object({
100
129
  id: z.string(),
101
130
  source: z.string(),
@@ -103,7 +132,7 @@ var PrincipalWireSchema = z.object({
103
132
  display_name: z.string().nullable().optional()
104
133
  }).strict();
105
134
  var envelopeShape = {
106
- event_id: z.uuid().default(() => uuidv7()),
135
+ event_id: z.uuid().default(() => uuid7()),
107
136
  tenant_id: z.string(),
108
137
  vendor_id: z.string(),
109
138
  session_id: z.string(),
@@ -111,9 +140,12 @@ var envelopeShape = {
111
140
  captured_at: z.string(),
112
141
  consent_token: z.string(),
113
142
  sdk_version: z.string().default(SDK_VERSION),
143
+ // Legacy (SPEC §3.4): never set by this SDK, so always the default. The
144
+ // consumer names the client from `client_observed`.
114
145
  agent_runtime: z.string().default("unknown"),
115
146
  principal: PrincipalWireSchema.nullable().default(null),
116
147
  transport_observed: z.string().nullable().default(null),
148
+ client_observed: ClientObservedSchema.nullable().default(null),
117
149
  call_id: z.string().nullable().default(null),
118
150
  runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null)
119
151
  };
@@ -137,7 +169,11 @@ var EventTypeSchema = z.enum([
137
169
  "prompt_list_error",
138
170
  "prompt_get_start",
139
171
  "prompt_get_end",
140
- "prompt_get_error"
172
+ "prompt_get_error",
173
+ // SPEC §11.4.5.
174
+ "tool_list_start",
175
+ "tool_list_end",
176
+ "tool_list_error"
141
177
  ]);
142
178
  var timingShape = { duration_ms: z.number().int().nullable().default(null) };
143
179
  var failureShape = { error_type: z.string(), error_body: z.string(), ...timingShape };
@@ -176,6 +212,14 @@ var PromptListEndPayloadSchema = z.object({
176
212
  var PromptListErrorPayloadSchema = z.object({
177
213
  ...failureShape
178
214
  }).strict();
215
+ var ToolListStartPayloadSchema = z.object({}).strict();
216
+ var ToolListEndPayloadSchema = z.object({
217
+ count: z.number().int(),
218
+ ...timingShape
219
+ }).strict();
220
+ var ToolListErrorPayloadSchema = z.object({
221
+ ...failureShape
222
+ }).strict();
179
223
  var PromptGetStartPayloadSchema = z.object({
180
224
  name: z.string(),
181
225
  /** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
@@ -191,18 +235,22 @@ var PromptGetErrorPayloadSchema = z.object({
191
235
  name: z.string(),
192
236
  ...failureShape
193
237
  }).strict();
238
+ var REQUIRED_CALL_ID = z.string().min(1);
194
239
  var ToolCallStartEventSchema = z.object({
195
240
  ...envelopeShape,
241
+ call_id: REQUIRED_CALL_ID,
196
242
  event_type: z.literal("tool_call_start").default("tool_call_start"),
197
243
  payload: ToolCallStartPayloadSchema
198
244
  }).strict();
199
245
  var ToolCallEndEventSchema = z.object({
200
246
  ...envelopeShape,
247
+ call_id: REQUIRED_CALL_ID,
201
248
  event_type: z.literal("tool_call_end").default("tool_call_end"),
202
249
  payload: ToolCallEndPayloadSchema
203
250
  }).strict();
204
251
  var ToolCallErrorEventSchema = z.object({
205
252
  ...envelopeShape,
253
+ call_id: REQUIRED_CALL_ID,
206
254
  event_type: z.literal("tool_call_error").default("tool_call_error"),
207
255
  payload: ToolCallErrorPayloadSchema
208
256
  }).strict();
@@ -276,6 +324,21 @@ var PromptGetErrorEventSchema = z.object({
276
324
  event_type: z.literal("prompt_get_error").default("prompt_get_error"),
277
325
  payload: PromptGetErrorPayloadSchema
278
326
  }).strict();
327
+ var ToolListStartEventSchema = z.object({
328
+ ...envelopeShape,
329
+ event_type: z.literal("tool_list_start").default("tool_list_start"),
330
+ payload: ToolListStartPayloadSchema
331
+ }).strict();
332
+ var ToolListEndEventSchema = z.object({
333
+ ...envelopeShape,
334
+ event_type: z.literal("tool_list_end").default("tool_list_end"),
335
+ payload: ToolListEndPayloadSchema
336
+ }).strict();
337
+ var ToolListErrorEventSchema = z.object({
338
+ ...envelopeShape,
339
+ event_type: z.literal("tool_list_error").default("tool_list_error"),
340
+ payload: ToolListErrorPayloadSchema
341
+ }).strict();
279
342
  var EventSchema = z.discriminatedUnion("event_type", [
280
343
  ToolCallStartEventSchema,
281
344
  ToolCallEndEventSchema,
@@ -293,7 +356,10 @@ var EventSchema = z.discriminatedUnion("event_type", [
293
356
  PromptListErrorEventSchema,
294
357
  PromptGetStartEventSchema,
295
358
  PromptGetEndEventSchema,
296
- PromptGetErrorEventSchema
359
+ PromptGetErrorEventSchema,
360
+ ToolListStartEventSchema,
361
+ ToolListEndEventSchema,
362
+ ToolListErrorEventSchema
297
363
  ]);
298
364
 
299
365
  // src/scrub.ts
@@ -589,7 +655,6 @@ var HttpSink = class _HttpSink {
589
655
 
590
656
  // src/integrations/mcp/withBaton.ts
591
657
  import { AsyncLocalStorage } from "async_hooks";
592
- import { v7 as uuidv72 } from "uuid";
593
658
 
594
659
  // src/integrations/mcp/annotation.ts
595
660
  import { z as z2 } from "zod";
@@ -639,9 +704,6 @@ function roundMetaCoordinates(meta) {
639
704
  return walk(meta, 0);
640
705
  }
641
706
 
642
- // src/identity.ts
643
- import { createHmac } from "crypto";
644
-
645
707
  // src/_text.ts
646
708
  function exceedsCodePoints(value, max) {
647
709
  if (value.length <= max) return false;
@@ -657,7 +719,7 @@ function capCodePoints(value, max) {
657
719
  var PRINCIPAL_SOURCE_ASSERTED = "asserted";
658
720
  var PRINCIPAL_FORM_HASHED = "hashed";
659
721
  var PRINCIPAL_FORM_RAW = "raw";
660
- var RAW_PRINCIPAL_ID_MAX_LEN = 128;
722
+ var PRINCIPAL_ID_MAX_LEN = 128;
661
723
  var DISPLAY_NAME_MAX_LEN = 128;
662
724
  var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
663
725
  function wireDisplayName(value) {
@@ -665,59 +727,40 @@ function wireDisplayName(value) {
665
727
  if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
666
728
  return value;
667
729
  }
668
- var PRINCIPAL_ID_MODE_HASHED = "hashed";
669
- var PRINCIPAL_ID_MODE_RAW = "raw";
670
- var FORM_BY_MODE = {
671
- [PRINCIPAL_ID_MODE_HASHED]: PRINCIPAL_FORM_HASHED,
672
- [PRINCIPAL_ID_MODE_RAW]: PRINCIPAL_FORM_RAW
673
- };
674
- var PRINCIPAL_ID_MODES = Object.keys(
675
- FORM_BY_MODE
676
- );
730
+ var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
677
731
  var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
678
732
  var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
679
733
  var LONE_SURROGATE = /\p{Surrogate}/u;
680
- function canonicalize(rawPrincipal) {
681
- return pythonStrip(rawPrincipal.normalize("NFC")).toLowerCase();
682
- }
683
734
  function pythonStrip(value) {
684
735
  return value.replace(PYTHON_STRIP, "");
685
736
  }
686
- function hashPrincipalId(rawPrincipal, options) {
687
- const { tenantId, key, issuer = null } = options;
688
- let message = `${tenantId}\0${canonicalize(rawPrincipal)}`;
689
- if (issuer !== null) {
690
- message += `\0${canonicalize(issuer)}`;
691
- }
692
- const keyBytes = typeof key === "string" ? Buffer.from(key, "utf8") : key;
693
- return createHmac("sha256", keyBytes).update(message, "utf8").digest("hex");
694
- }
695
737
  function normalizePrincipal(result) {
696
738
  if (result === null || typeof result !== "object") return null;
697
739
  const candidate = result;
698
740
  if (typeof candidate.principalId !== "string") return null;
699
741
  if (LONE_SURROGATE.test(candidate.principalId)) return null;
700
- if (canonicalize(candidate.principalId) === "") return null;
701
- const issuerRaw = typeof candidate.issuer === "string" && candidate.issuer ? candidate.issuer : null;
702
- const issuer = issuerRaw !== null && !LONE_SURROGATE.test(issuerRaw) ? issuerRaw : null;
703
- return typeof candidate.displayName === "string" ? { principalId: candidate.principalId, issuer, displayName: candidate.displayName } : { principalId: candidate.principalId, issuer };
704
- }
705
- function principalFor(principal, options) {
706
- let id;
707
- if (options.mode === PRINCIPAL_ID_MODE_RAW) {
708
- id = capCodePoints(principal.principalId, RAW_PRINCIPAL_ID_MAX_LEN);
709
- } else {
710
- if (options.key === null || options.key === void 0) return null;
711
- id = hashPrincipalId(principal.principalId, {
712
- tenantId: options.tenantId,
713
- key: options.key,
714
- issuer: principal.issuer ?? null
715
- });
742
+ if (candidate.principalId.includes("\0")) return null;
743
+ if (pythonStrip(candidate.principalId) === "") return null;
744
+ const principal = { principalId: candidate.principalId };
745
+ if (candidate.form !== void 0) principal.form = candidate.form;
746
+ if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
747
+ return principal;
748
+ }
749
+ function principalFor(principal, onUnregisteredForm) {
750
+ let form = PRINCIPAL_FORM_RAW;
751
+ if (principal.form !== void 0) {
752
+ if (PRINCIPAL_FORMS.has(principal.form)) {
753
+ form = principal.form;
754
+ } else {
755
+ onUnregisteredForm?.(principal.form);
756
+ }
716
757
  }
717
758
  const wire = {
718
- id,
759
+ // `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
760
+ // an astral id cut at the boundary would ship a lone surrogate.
761
+ id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
719
762
  source: PRINCIPAL_SOURCE_ASSERTED,
720
- form: FORM_BY_MODE[options.mode]
763
+ form
721
764
  };
722
765
  const displayName = wireDisplayName(principal.displayName);
723
766
  if (displayName !== null) wire.display_name = displayName;
@@ -764,7 +807,7 @@ function buildServerInstructions(options) {
764
807
  `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.`
765
808
  );
766
809
  }
767
- return rendered;
810
+ return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
768
811
  }
769
812
  function buildAnnotationToolDescription(options) {
770
813
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -776,16 +819,24 @@ var INTENT_SOURCE_PARAM = "injected_param";
776
819
  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).";
777
820
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
778
821
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
779
- 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.";
780
- 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.";
822
+ 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.";
823
+ var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
824
+ var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
825
+ 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.";
826
+ var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
827
+ var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
828
+ 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.";
781
829
  function buildUserGoalParamDescription(options = {}) {
782
830
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
783
831
  }
784
- function buildOverallTaskParamDescription() {
785
- return OVERALL_TASK_PARAM_DESCRIPTION;
832
+ function buildOverallTaskParamDescription(options = {}) {
833
+ return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
834
+ }
835
+ function buildExpectedResultParamDescription(options = {}) {
836
+ return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
786
837
  }
787
- function buildExpectedResultParamDescription() {
788
- return EXPECTED_RESULT_PARAM_DESCRIPTION;
838
+ function requiredParamNames(intentParamMode) {
839
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
789
840
  }
790
841
 
791
842
  // src/integrations/mcp/annotationName.ts
@@ -827,12 +878,18 @@ function slugServerName(serverName) {
827
878
  const collapsed = mapped.replace(/-+/g, "-").replace(/^-+|-+$/g, "");
828
879
  return collapsed.slice(0, SLUG_CAP).replace(/^-+|-+$/g, "") || void 0;
829
880
  }
881
+ function toolNameCandidate(serverName) {
882
+ const slug = slugServerName(serverName);
883
+ if (slug === void 0) return void 0;
884
+ const candidate = `${slug}${SUFFIX}`;
885
+ return TOOL_NAME_PATTERN.test(candidate) ? candidate : void 0;
886
+ }
830
887
  function displayNameFromServer(serverName, tool) {
831
888
  if (serverName === void 0) return void 0;
832
- const fallbackToolName = tool.annotationToolName || `${tool.vendorId}${SUFFIX}`;
833
- if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: fallbackToolName })) {
889
+ const proposed = tool.annotationToolName || toolNameCandidate(serverName) || `${tool.vendorId}${SUFFIX}`;
890
+ if (!fitsInstructionsCap({ vendorDisplayName: serverName, annotationToolName: proposed })) {
834
891
  warn(
835
- `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.`
892
+ `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.`
836
893
  );
837
894
  return void 0;
838
895
  }
@@ -840,10 +897,8 @@ function displayNameFromServer(serverName, tool) {
840
897
  }
841
898
  function annotationToolNameFromServer(serverName, vendorDisplayName) {
842
899
  if (serverName === void 0) return void 0;
843
- const slug = slugServerName(serverName);
844
- if (slug === void 0) return void 0;
845
- const candidate = `${slug}${SUFFIX}`;
846
- if (!TOOL_NAME_PATTERN.test(candidate)) return void 0;
900
+ const candidate = toolNameCandidate(serverName);
901
+ if (candidate === void 0) return void 0;
847
902
  if (!fitsInstructionsCap({ vendorDisplayName, annotationToolName: candidate })) {
848
903
  warn(
849
904
  `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.`
@@ -923,6 +978,9 @@ function extraHeaders(extra) {
923
978
  }
924
979
  return null;
925
980
  }
981
+ function isThenable(value) {
982
+ return typeof value?.then === "function";
983
+ }
926
984
 
927
985
  // src/integrations/mcp/principalResolution.ts
928
986
  function buildPrincipalResolutionContext(extra, toolName, args) {
@@ -934,15 +992,25 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
934
992
  authInfo: extraAuthInfo(extra)
935
993
  };
936
994
  }
937
- function warnIfIdentityCannotResolve(config) {
938
- if (config.resolvePrincipal === void 0) return;
939
- if (config.principalIdMode !== PRINCIPAL_ID_MODE_HASHED) return;
940
- if (config.principalIdHmacKey !== void 0) return;
941
- if (typeof process === "undefined" || typeof process.emitWarning !== "function") return;
942
- 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. " : "";
943
- process.emitWarning(
944
- `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.`
945
- );
995
+ var HOOK_TIMEOUT_MS = 5e3;
996
+ var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
997
+ async function withinHookBudget(answer) {
998
+ if (!isThenable(answer)) return answer;
999
+ let timer;
1000
+ const deadline = new Promise((resolve) => {
1001
+ timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
1002
+ timer.unref?.();
1003
+ });
1004
+ try {
1005
+ const first = await Promise.race([answer, deadline]);
1006
+ if (first !== TIMED_OUT) return first;
1007
+ warn(
1008
+ `baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
1009
+ );
1010
+ return null;
1011
+ } finally {
1012
+ clearTimeout(timer);
1013
+ }
946
1014
  }
947
1015
  var warnedPreRenameShape = false;
948
1016
  function warnIfPreRenameShape(result) {
@@ -953,30 +1021,28 @@ function warnIfPreRenameShape(result) {
953
1021
  "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."
954
1022
  );
955
1023
  }
956
- async function resolveCallPrincipal(hook, call, options) {
1024
+ async function resolveCallPrincipal(hook, call) {
957
1025
  if (hook === void 0) return null;
958
- let result;
959
1026
  try {
960
1027
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
961
- result = await hook(context);
962
- } catch {
963
- return null;
964
- }
965
- const principal = normalizePrincipal(result);
966
- if (principal === null) {
967
- warnIfPreRenameShape(result);
968
- return null;
969
- }
970
- try {
971
- return principalFor(principal, {
972
- mode: options.mode,
973
- tenantId: options.tenantId,
974
- key: options.key
1028
+ const result = await withinHookBudget(hook(context));
1029
+ const principal = normalizePrincipal(result);
1030
+ if (principal === null) {
1031
+ warnIfPreRenameShape(result);
1032
+ return null;
1033
+ }
1034
+ return principalFor(principal, (form) => {
1035
+ warn(
1036
+ `baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
1037
+ );
975
1038
  });
976
1039
  } catch {
977
1040
  return null;
978
1041
  }
979
1042
  }
1043
+ function describeForm(form) {
1044
+ return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
1045
+ }
980
1046
 
981
1047
  // src/integrations/mcp/safeScrub.ts
982
1048
  var warned = /* @__PURE__ */ new Set();
@@ -996,56 +1062,67 @@ function scrubOrNull(scrubber, value, field) {
996
1062
  }
997
1063
  }
998
1064
 
999
- // src/integrations/mcp/runtimeAdapter.ts
1065
+ // src/integrations/mcp/clientObserved.ts
1000
1066
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
1001
- var CLIENT_NAME_MAX_LEN = 128;
1002
- var UNKNOWN_AGENT_RUNTIME = "unknown";
1003
- function clean(name, scrubber) {
1004
- if (typeof name !== "string" || !name) return null;
1005
- let cleaned = name;
1006
- if (scrubber) {
1007
- const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
1008
- if (typeof scrubbed !== "string") return null;
1009
- cleaned = scrubbed;
1010
- }
1011
- if (!cleaned) return null;
1012
- return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
1013
- }
1014
- function declaredOnRequest(meta, envelope) {
1015
- for (const source of [envelope, meta]) {
1016
- if (!source) continue;
1017
- const info = source[CLIENT_INFO_META_KEY];
1018
- if (info && typeof info === "object") {
1019
- const name = info.name;
1020
- if (name !== void 0) return name;
1021
- }
1067
+ var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
1068
+ var CLIENT_INFO_MAX_LEN = 128;
1069
+ var HEADER_VALUE_MAX_LEN = 256;
1070
+ var hasText = (value) => typeof value === "string" && value !== "";
1071
+ function declared(info) {
1072
+ if (!info || typeof info !== "object") return void 0;
1073
+ const { name, version } = info;
1074
+ return hasText(name) || hasText(version) ? { name, version } : void 0;
1075
+ }
1076
+ function declaredOnRequest(extra) {
1077
+ for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
1078
+ const found = declared(source?.[CLIENT_INFO_META_KEY]);
1079
+ if (found) return found;
1022
1080
  }
1023
1081
  return void 0;
1024
1082
  }
1025
- function declaredOnConnection(options) {
1083
+ function declaredOnConnection(server) {
1084
+ if (!server) return void 0;
1085
+ const inner = server.server;
1086
+ const holder = inner ?? server;
1087
+ if (typeof holder.getClientVersion !== "function") return void 0;
1088
+ return declared(holder.getClientVersion());
1089
+ }
1090
+ function observedInfo(extra, options) {
1091
+ const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
1092
+ const info = {};
1093
+ const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
1094
+ const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
1095
+ if (name !== void 0) info.name = name;
1096
+ if (version !== void 0) info.version = version;
1097
+ return Object.keys(info).length > 0 ? info : void 0;
1098
+ }
1099
+ function observedHeaders(extra, options) {
1100
+ const sent = extraHeaders(extra);
1101
+ const headers = {};
1102
+ for (const header of OBSERVED_HEADERS) {
1103
+ const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
1104
+ if (value !== void 0) headers[header] = value;
1105
+ }
1106
+ return Object.keys(headers).length > 0 ? headers : void 0;
1107
+ }
1108
+ function clean(value, scrubber, max) {
1109
+ if (!hasText(value)) return void 0;
1110
+ const scrubbed = scrubOrNull(scrubber, value, "client_observed");
1111
+ if (!hasText(scrubbed)) return void 0;
1112
+ return capCodePoints(scrubbed, max);
1113
+ }
1114
+ function orNothing(read) {
1026
1115
  try {
1027
- const server = options.server;
1028
- if (!server) return void 0;
1029
- const inner = server.server;
1030
- const holder = inner ?? server;
1031
- if (typeof holder.getClientVersion !== "function") return void 0;
1032
- return holder.getClientVersion()?.name;
1116
+ return read();
1033
1117
  } catch {
1034
1118
  return void 0;
1035
1119
  }
1036
1120
  }
1037
- function detectAgentRuntime(meta, options = {}) {
1038
- const { envelope, scrubber } = options;
1039
- const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);
1040
- if (onRequest !== null) return onRequest;
1041
- const onConnection = clean(declaredOnConnection(options), scrubber);
1042
- if (onConnection !== null) return onConnection;
1043
- if (meta) {
1044
- for (const key of Object.keys(meta)) {
1045
- if (key.startsWith("claudecode/")) return "claude-code";
1046
- }
1047
- }
1048
- return null;
1121
+ function observeClient(extra, options) {
1122
+ const info = orNothing(() => observedInfo(extra, options));
1123
+ const headers = orNothing(() => observedHeaders(extra, options));
1124
+ if (info === void 0 && headers === void 0) return null;
1125
+ return { ...info && { info }, ...headers && { headers } };
1049
1126
  }
1050
1127
 
1051
1128
  // src/integrations/mcp/sessionResolution.ts
@@ -1075,11 +1152,6 @@ function registerAnnotationTool(server, options) {
1075
1152
  },
1076
1153
  async (args, extra) => {
1077
1154
  const meta = extraMeta(extra);
1078
- const runtime = detectAgentRuntime(meta, {
1079
- envelope: extraEnvelope(extra),
1080
- server,
1081
- scrubber: options.scrubber
1082
- }) ?? UNKNOWN_AGENT_RUNTIME;
1083
1155
  const scrubbedMeta = scrubOrNull(
1084
1156
  options.scrubber,
1085
1157
  meta ? roundMetaCoordinates(meta) : null,
@@ -1091,12 +1163,7 @@ function registerAnnotationTool(server, options) {
1091
1163
  }
1092
1164
  const principal = await resolveCallPrincipal(
1093
1165
  options.resolvePrincipal,
1094
- { extra, toolName: name, arguments: args },
1095
- {
1096
- mode: options.principalIdMode,
1097
- tenantId: options.tenantId,
1098
- key: options.principalIdHmacKey
1099
- }
1166
+ { extra, toolName: name, arguments: args }
1100
1167
  );
1101
1168
  await emit(
1102
1169
  options.sink,
@@ -1107,9 +1174,9 @@ function registerAnnotationTool(server, options) {
1107
1174
  sequence_number: options.counter.next(sessionId),
1108
1175
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1109
1176
  consent_token: options.consentToken,
1110
- agent_runtime: runtime,
1111
1177
  principal,
1112
1178
  transport_observed: observeTransport(extra),
1179
+ client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1113
1180
  runtime_meta: scrubbedMeta,
1114
1181
  payload: {
1115
1182
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -1410,19 +1477,13 @@ function requestSideErrorFields(text, errorBody2) {
1410
1477
  // src/integrations/mcp/config.ts
1411
1478
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
1412
1479
  var RESULT_CAPTURE_MODE_SET = new Set(RESULT_CAPTURE_MODES);
1413
- var PRINCIPAL_ID_MODE_SET = new Set(PRINCIPAL_ID_MODES);
1414
1480
  function resolveTenantId(explicit, vendorId) {
1415
1481
  if (explicit) return explicit;
1416
1482
  const fromEnv = typeof process !== "undefined" ? process.env?.BATON_TENANT_ID : void 0;
1417
1483
  if (fromEnv) return fromEnv;
1418
1484
  return vendorId;
1419
1485
  }
1420
- function resolvePrincipalIdHmacKey(explicit) {
1421
- if (explicit !== void 0) return explicit;
1422
- const fromEnv = typeof process !== "undefined" ? process.env?.BATON_PRINCIPAL_ID_HMAC_KEY : void 0;
1423
- return fromEnv ? fromEnv : void 0;
1424
- }
1425
- function resolveBatonConfig(config, serverName) {
1486
+ function resolveBatonConfig(config) {
1426
1487
  const dsnString = selectDsn(
1427
1488
  config.dsn,
1428
1489
  {
@@ -1458,14 +1519,7 @@ function resolveBatonConfig(config, serverName) {
1458
1519
  // in the server instructions and the annotation tool description, which is
1459
1520
  // the whitelabel obligation the validator cites when it refuses the empty
1460
1521
  // one. ⚠ Python uses `or` here and still has the inconsistency.
1461
- //
1462
- // Between the explicit value and the segment sits the server's own name,
1463
- // under the guards in `annotationName.ts`: the segment is an opaque
1464
- // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1465
- vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1466
- vendorId: dsn.vendorId,
1467
- annotationToolName: config.annotationToolName
1468
- }) ?? dsn.vendorId,
1522
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1469
1523
  // `??`, not `||`: an explicit empty string must survive to the validation
1470
1524
  // below and be REFUSED there, rather than be quietly replaced by the
1471
1525
  // default it was deliberately not left as.
@@ -1479,10 +1533,16 @@ function resolveBatonConfig(config, serverName) {
1479
1533
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
1480
1534
  };
1481
1535
  }
1536
+ function withServerDisplayName(resolved, supplied, serverName) {
1537
+ if (supplied.vendorDisplayName !== void 0) return resolved;
1538
+ const fromServer = displayNameFromServer(serverName, {
1539
+ vendorId: resolved.vendorId,
1540
+ annotationToolName: supplied.annotationToolName
1541
+ });
1542
+ return fromServer === void 0 ? resolved : { ...resolved, vendorDisplayName: fromServer };
1543
+ }
1482
1544
  var RENAMED_KEYS = {
1483
- resolveUser: "resolvePrincipal",
1484
- userIdMode: "principalIdMode",
1485
- userIdHmacKey: "principalIdHmacKey"
1545
+ resolveUser: "resolvePrincipal"
1486
1546
  };
1487
1547
  function validateBatonConfig(config) {
1488
1548
  for (const [was, now] of Object.entries(RENAMED_KEYS)) {
@@ -1531,14 +1591,6 @@ function validateBatonConfig(config) {
1531
1591
  if (config.resolvePrincipal !== void 0 && typeof config.resolvePrincipal !== "function") {
1532
1592
  throw new Error("BatonConfig.resolvePrincipal must be a function.");
1533
1593
  }
1534
- if (config.principalIdHmacKey !== void 0 && typeof config.principalIdHmacKey !== "string" && !(config.principalIdHmacKey instanceof Uint8Array)) {
1535
- throw new Error("BatonConfig.principalIdHmacKey must be a string or a Uint8Array.");
1536
- }
1537
- if (config.principalIdMode !== void 0 && !PRINCIPAL_ID_MODE_SET.has(config.principalIdMode)) {
1538
- throw new Error(
1539
- `BatonConfig.principalIdMode ${JSON.stringify(config.principalIdMode)} must be one of ${JSON.stringify([...PRINCIPAL_ID_MODE_SET].sort())}.`
1540
- );
1541
- }
1542
1594
  }
1543
1595
 
1544
1596
  // src/optout.ts
@@ -1725,13 +1777,8 @@ function injectGoalParams(inputSchema, intentParamMode) {
1725
1777
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1726
1778
  const dispositions = {};
1727
1779
  const toInject = {};
1728
- if (USER_GOAL_PARAM_NAME in existingShape) {
1729
- dispositions[USER_GOAL_PARAM_NAME] = "native";
1730
- } else {
1731
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
1732
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1733
- }
1734
1780
  for (const [name, buildDescription] of [
1781
+ [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1735
1782
  [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1736
1783
  [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1737
1784
  ]) {
@@ -1739,7 +1786,7 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1739
1786
  dispositions[name] = "native";
1740
1787
  } else {
1741
1788
  dispositions[name] = "injected";
1742
- toInject[name] = zodImpl.string().optional().describe(buildDescription());
1789
+ toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1743
1790
  }
1744
1791
  }
1745
1792
  return { dispositions, toInject };
@@ -1755,21 +1802,23 @@ function injectGoalParamsV2(inputSchema, intentParamMode) {
1755
1802
  return { schema: inputSchema, dispositions };
1756
1803
  return { schema: candidate.extend(toInject), dispositions };
1757
1804
  }
1758
- function advertiseUserGoalRequired(result, isInjected) {
1805
+ function advertiseIntentParamsRequired(result, names, isInjected) {
1759
1806
  const tools = result?.tools;
1760
1807
  if (!Array.isArray(tools)) return result;
1761
1808
  let changed = false;
1762
1809
  const advertised = tools.map((tool) => {
1763
1810
  const entry = tool;
1764
- if (typeof entry?.name !== "string" || !isInjected(entry.name)) return tool;
1765
- const schema = entry.inputSchema;
1811
+ const toolName = entry?.name;
1812
+ if (typeof toolName !== "string") return tool;
1813
+ const schema = entry?.inputSchema;
1766
1814
  if (!schema || typeof schema !== "object") return tool;
1767
- const declared = schema.required ?? [];
1768
- if (!Array.isArray(declared)) return tool;
1769
- const required = declared;
1770
- if (required.includes(USER_GOAL_PARAM_NAME)) return tool;
1815
+ const declared2 = schema.required ?? [];
1816
+ if (!Array.isArray(declared2)) return tool;
1817
+ const required = declared2;
1818
+ const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
1819
+ if (missing.length === 0) return tool;
1771
1820
  changed = true;
1772
- return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };
1821
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
1773
1822
  });
1774
1823
  return changed ? { ...result, tools: advertised } : result;
1775
1824
  }
@@ -1818,7 +1867,11 @@ function assembleSurface(serverMeta, tools) {
1818
1867
  function buildSeamAugmentations(options) {
1819
1868
  return {
1820
1869
  injected_tools: [...options.injectedToolNames].sort(),
1821
- intent_param: options.intentParamMode !== "off" ? { names: [...options.intentParamNames].sort(), mode: options.intentParamMode } : null,
1870
+ intent_param: options.intentParamMode !== "off" ? {
1871
+ names: [...options.intentParamNames].sort(),
1872
+ required_names: [...options.requiredParamNames].sort(),
1873
+ mode: options.intentParamMode
1874
+ } : null,
1822
1875
  instructions_suffix: true
1823
1876
  };
1824
1877
  }
@@ -1829,16 +1882,17 @@ var wired = /* @__PURE__ */ new WeakSet();
1829
1882
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1830
1883
  var callSlots = new AsyncLocalStorage();
1831
1884
  var SurfaceState = class {
1832
- constructor(serverMeta) {
1885
+ constructor(serverMeta, emittedHashes) {
1833
1886
  this.serverMeta = serverMeta;
1887
+ this.emittedHashes = emittedHashes;
1834
1888
  }
1835
1889
  serverMeta;
1890
+ emittedHashes;
1836
1891
  /** Every tool this install has seen, keyed by its CURRENT name. `disabled`
1837
1892
  * is tracked alongside rather than pruned, so re-enabling costs nothing and
1838
1893
  * — crucially — never needs a re-capture, which would re-read Baton's own
1839
1894
  * injected schema as if it were vendor-true. */
1840
1895
  rawTools = /* @__PURE__ */ new Map();
1841
- emittedHashes = /* @__PURE__ */ new Set();
1842
1896
  dirty = false;
1843
1897
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
1844
1898
  * which picks the spelling THIS SDK major puts on the wire. */
@@ -1890,23 +1944,13 @@ function messageOf(err) {
1890
1944
  }
1891
1945
  async function resolveEnvelopeParts(ctx, extra) {
1892
1946
  const meta = extraMeta(extra);
1893
- const runtime = detectAgentRuntime(meta, {
1894
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1895
- // `_meta`; 1.x leaves them in. Both are handed over — see
1896
- // `mcpTypes.extraEnvelope`.
1897
- envelope: extraEnvelope(extra),
1898
- // Tier 2's carrier: neither peer puts client identity on the
1899
- // handler context, both expose the cached handshake on the server.
1900
- server: ctx.server,
1901
- scrubber: ctx.scrubber
1902
- }) ?? UNKNOWN_AGENT_RUNTIME;
1903
1947
  const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1904
1948
  const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1905
- return { sessionId, runtime, scrubbedMeta };
1949
+ return { sessionId, scrubbedMeta };
1906
1950
  }
1907
1951
  async function openCall(ctx, toolName, extra, params, registered = true) {
1908
1952
  await maybeEmitSurfaceSnapshot(ctx);
1909
- const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1953
+ const { sessionId, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1910
1954
  const dispositions = ctx.paramRegistry.get(toolName);
1911
1955
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
1912
1956
  const rawExpected = extractGoalParam(
@@ -1920,30 +1964,22 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
1920
1964
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
1921
1965
  const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
1922
1966
  const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
1923
- const callId = uuidv72();
1967
+ const callId = uuid7();
1924
1968
  const principal = await resolveCallPrincipal(
1925
1969
  ctx.resolvePrincipal,
1926
- { extra, toolName, arguments: params },
1927
- { mode: ctx.principalIdMode, tenantId: ctx.tenantId, key: ctx.principalIdHmacKey }
1970
+ { extra, toolName, arguments: params }
1928
1971
  );
1929
1972
  const common = {
1930
1973
  tenant_id: ctx.tenantId,
1931
1974
  vendor_id: ctx.vendorId,
1932
1975
  session_id: sessionId,
1933
1976
  consent_token: ctx.consentToken,
1934
- agent_runtime: runtime,
1935
- // The five `...common` sites below are the tool-call legs — start, end,
1936
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1937
- // annotation, the same five Python stamps (`middleware.py`
1938
- // 503/547/586/644/674; it was four until the returned shape landed
1939
- // there too). `surface_snapshot` is deliberately NOT among them: it
1940
- // describes the SERVER and is captured outside any call, so there is no
1941
- // caller to name (register D5).
1977
+ // Every `...common` site is an event with a caller. `surface_snapshot`
1978
+ // is deliberately not among them: it describes the SERVER and is captured
1979
+ // outside any call, so it has no caller, transport or client to name.
1942
1980
  principal,
1943
- // Same five stamps, same exclusion: a surface_snapshot describes the
1944
- // SERVER and is captured outside any call, so it has no caller's
1945
- // transport to name any more than it has a caller to name.
1946
1981
  transport_observed: observeTransport(extra),
1982
+ client_observed: observeClient(extra, ctx),
1947
1983
  runtime_meta: scrubbedMeta
1948
1984
  };
1949
1985
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -2165,6 +2201,7 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2165
2201
  delete args[paramName];
2166
2202
  return typeof raw === "string" && raw.trim() ? raw : null;
2167
2203
  }
2204
+ var MAX_REMEMBERED_SURFACES = 1024;
2168
2205
  async function maybeEmitSurfaceSnapshot(ctx) {
2169
2206
  if (!ctx.surfaceState.dirty) return;
2170
2207
  ctx.surfaceState.dirty = false;
@@ -2178,21 +2215,24 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2178
2215
  `);
2179
2216
  return;
2180
2217
  }
2181
- if (ctx.surfaceState.emittedHashes.has(digest)) return;
2218
+ const emitted = ctx.surfaceState.emittedHashes;
2219
+ if (emitted.has(digest)) return;
2220
+ if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
2221
+ emitted.add(digest);
2182
2222
  const seam = buildSeamAugmentations({
2183
2223
  injectedToolNames: [ctx.annotationToolName],
2184
2224
  intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2185
- intentParamMode: ctx.intentParamMode
2225
+ intentParamMode: ctx.intentParamMode,
2226
+ requiredParamNames: requiredParamNames(ctx.intentParamMode)
2186
2227
  });
2187
2228
  try {
2188
2229
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
2189
2230
  } catch (err) {
2190
2231
  process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
2191
2232
  `);
2233
+ emitted.delete(digest);
2192
2234
  ctx.surfaceState.dirty = true;
2193
- return;
2194
2235
  }
2195
- ctx.surfaceState.emittedHashes.add(digest);
2196
2236
  }
2197
2237
  function captureAndInject(name, entry, ctx) {
2198
2238
  if (!entry || typeof entry !== "object") return;
@@ -2206,6 +2246,7 @@ function captureAndInject(name, entry, ctx) {
2206
2246
  mutable.inputSchema = schema;
2207
2247
  ctx.bustSchemaMemo(name);
2208
2248
  ctx.paramRegistry.set(name, dispositions);
2249
+ if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2209
2250
  } else {
2210
2251
  ctx.paramRegistry.delete(name);
2211
2252
  }
@@ -2226,6 +2267,7 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2226
2267
  const handler = handlers.get(method);
2227
2268
  if (typeof handler !== "function" || handler[seamTag]) return;
2228
2269
  const seamed = wrap(handler);
2270
+ for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];
2229
2271
  seamed[seamTag] = true;
2230
2272
  handlers.set(method, seamed);
2231
2273
  };
@@ -2237,10 +2279,11 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2237
2279
  };
2238
2280
  }
2239
2281
  function installToolsListSeam(lowLevel, ctx) {
2240
- const isInjected = (toolName) => ctx.paramRegistry.get(toolName)?.[USER_GOAL_PARAM_NAME] === "injected";
2282
+ const names = requiredParamNames(ctx.intentParamMode);
2283
+ const isInjected = (toolName, paramName) => ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
2241
2284
  const advertise = (result) => {
2242
2285
  try {
2243
- return advertiseUserGoalRequired(result, isInjected);
2286
+ return advertiseIntentParamsRequired(result, names, isInjected);
2244
2287
  } catch (err) {
2245
2288
  process.stderr.write(
2246
2289
  `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
@@ -2258,7 +2301,8 @@ var LIFECYCLE_SEAMS = {
2258
2301
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2259
2302
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2260
2303
  promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2261
- promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2304
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam"),
2305
+ toolList: /* @__PURE__ */ Symbol("batonToolListSeam")
2262
2306
  };
2263
2307
  function installLifecycleSeam(lowLevel, ctx, spec) {
2264
2308
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
@@ -2305,6 +2349,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2305
2349
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2306
2350
  try {
2307
2351
  const parts = await resolveEnvelopeParts(ctx, extra);
2352
+ const principal = spec.resolvesPrincipal ? await resolveCallPrincipal(ctx.resolvePrincipal, { extra, toolName: null, arguments: {} }) : null;
2308
2353
  return {
2309
2354
  sessionId: parts.sessionId,
2310
2355
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
@@ -2313,8 +2358,9 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2313
2358
  vendor_id: ctx.vendorId,
2314
2359
  session_id: parts.sessionId,
2315
2360
  consent_token: ctx.consentToken,
2316
- agent_runtime: parts.runtime,
2361
+ principal,
2317
2362
  transport_observed: observeTransport(extra),
2363
+ client_observed: observeClient(extra, ctx),
2318
2364
  runtime_meta: parts.scrubbedMeta
2319
2365
  }
2320
2366
  };
@@ -2387,6 +2433,18 @@ var LIFECYCLE_SPECS = [
2387
2433
  startParams: (params) => ({
2388
2434
  params: paramsBag(params["arguments"])
2389
2435
  })
2436
+ },
2437
+ {
2438
+ method: TOOLS_LIST_METHOD,
2439
+ seamTag: LIFECYCLE_SEAMS.toolList,
2440
+ schemas: {
2441
+ start: ToolListStartEventSchema,
2442
+ end: ToolListEndEventSchema,
2443
+ error: ToolListErrorEventSchema
2444
+ },
2445
+ countKey: "tools",
2446
+ startParams: NO_PARAMS,
2447
+ resolvesPrincipal: true
2390
2448
  }
2391
2449
  ];
2392
2450
  function installLifecycleSeams(lowLevel, ctx) {
@@ -2517,9 +2575,6 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2517
2575
  })
2518
2576
  );
2519
2577
  }
2520
- function isThenable(value) {
2521
- return typeof value?.then === "function";
2522
- }
2523
2578
  function wrapIfNeeded(nameRef, entry, ctx) {
2524
2579
  if (!entry || typeof entry !== "object") return;
2525
2580
  const mutable = entry;
@@ -2595,47 +2650,57 @@ function withBaton(server, supplied = {}) {
2595
2650
  annotationToolName: ""
2596
2651
  });
2597
2652
  }
2653
+ return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
2654
+ }
2655
+ function createBaton(supplied = {}) {
2656
+ const disabledBy = captureDisabled();
2657
+ if (disabledBy !== null) {
2658
+ logDisabled(disabledBy, "createBaton");
2659
+ const unused = supplied.sink ?? new DisabledSink();
2660
+ return { wrap: () => {
2661
+ }, flush: () => unused.flush(), aclose: () => unused.aclose() };
2662
+ }
2663
+ const resolved = resolveBatonConfig(supplied);
2664
+ deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
2665
+ const sink = resolved.sink ?? new StdoutSink();
2666
+ const config = {
2667
+ ...resolved,
2668
+ sink,
2669
+ tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
2670
+ };
2671
+ const emittedSurfaceHashes = /* @__PURE__ */ new Set();
2672
+ return {
2673
+ wrap: (server) => {
2674
+ install(server, supplied, config, emittedSurfaceHashes);
2675
+ },
2676
+ flush: () => sink.flush(),
2677
+ aclose: () => sink.aclose()
2678
+ };
2679
+ }
2680
+ function install(server, supplied, resolved, emittedSurfaceHashes) {
2598
2681
  const internals = server;
2599
2682
  const serverName = usableServerName(() => ({
2600
2683
  name: internals.server._serverInfo?.name,
2601
2684
  className: internals.constructor.name
2602
2685
  }));
2603
- const config = resolveBatonConfig(supplied, serverName);
2686
+ const config = withServerDisplayName(resolved, supplied, serverName);
2604
2687
  const sink = config.sink ?? new StdoutSink();
2605
2688
  const annotationToolName = resolveAnnotationToolName(serverName, config);
2606
2689
  const intentParamMode = config.intentParamMode ?? "required";
2607
- const counter = new SessionCounter();
2608
- const fallbackSessionId = `sdk-${uuidv72()}`;
2690
+ const counter2 = new SessionCounter();
2691
+ const fallbackSessionId = `sdk-${uuid7()}`;
2609
2692
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
2610
2693
  const scrubber = config.scrubber ?? new Scrubber().scrub;
2611
2694
  const serverMeta = buildServerMeta(server.server);
2612
- const surfaceState = new SurfaceState(serverMeta);
2695
+ const surfaceState = new SurfaceState(serverMeta, emittedSurfaceHashes);
2613
2696
  const emitSurface = async (sessionId, digest, snapshot) => {
2614
2697
  const event = SurfaceSnapshotEventSchema.parse({
2615
2698
  tenant_id: tenantId,
2616
2699
  vendor_id: config.vendorId,
2617
2700
  session_id: sessionId,
2618
2701
  consent_token: config.consentToken,
2619
- sequence_number: counter.next(sessionId),
2702
+ sequence_number: counter2.next(sessionId),
2620
2703
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2621
- // Deliberately the literal, NOT the ladder — and an earlier comment
2622
- // here justified that by saying no call is in scope, which is false:
2623
- // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
2624
- // handshake has happened and tier 2's carrier is live in this closure.
2625
- // The real reason is that the snapshot describes the VENDOR'S SURFACE,
2626
- // which is the same whoever is calling. It is hashed and emitted at
2627
- // most once per process per surface, so the client that happens to
2628
- // trigger it is whichever one called first — attributing the surface to
2629
- // that client would read as a fact about the surface and be an accident
2630
- // of timing. Python hardcodes it from the same in-call position
2631
- // (`_tool_wrap.py`), so this is parity, not a gap.
2632
- //
2633
- // ⚠ Consequence worth knowing: one session emits `surface_snapshot`
2634
- // with `unknown` and everything else with the client's name, so a
2635
- // consumer grouping on `agent_runtime` alone sees two runtimes for one
2636
- // client. Intended; group surfaces on `(tenant_id, vendor_id,
2637
- // surface_hash)`, which is what the Console's table is keyed on.
2638
- agent_runtime: UNKNOWN_AGENT_RUNTIME,
2639
2704
  payload: {
2640
2705
  surface_hash: digest,
2641
2706
  server_info: snapshot.server_info,
@@ -2651,6 +2716,15 @@ function withBaton(server, supplied = {}) {
2651
2716
  const memo = internals._toolInputSchemaJson;
2652
2717
  if (memo && typeof memo === "object") delete memo[name];
2653
2718
  };
2719
+ const dropSubagentClause = (name) => {
2720
+ const current = internals.server._instructions;
2721
+ if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
2722
+ internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
2723
+ process.stderr.write(
2724
+ `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
2725
+ `
2726
+ );
2727
+ };
2654
2728
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
2655
2729
  const vendorToolJsonSchema = (name, inputSchema) => {
2656
2730
  if (isV2Server) {
@@ -2675,7 +2749,7 @@ function withBaton(server, supplied = {}) {
2675
2749
  const tracker = new ProactiveTracker();
2676
2750
  const ctx = {
2677
2751
  sink,
2678
- counter,
2752
+ counter: counter2,
2679
2753
  tenantId,
2680
2754
  vendorId: config.vendorId,
2681
2755
  consentToken: config.consentToken,
@@ -2687,18 +2761,17 @@ function withBaton(server, supplied = {}) {
2687
2761
  resultCaptureMode: config.resultCaptureMode ?? "full",
2688
2762
  paramRegistry: /* @__PURE__ */ new Map(),
2689
2763
  resolvePrincipal: config.resolvePrincipal,
2690
- principalIdMode: config.principalIdMode ?? "hashed",
2691
- principalIdHmacKey: resolvePrincipalIdHmacKey(config.principalIdHmacKey),
2692
2764
  vendorToolJsonSchema,
2693
2765
  bustSchemaMemo,
2766
+ dropSubagentClause,
2694
2767
  tracker,
2695
2768
  surfaceState,
2696
2769
  emitSurface
2697
2770
  };
2698
- warnIfIdentityCannotResolve(ctx);
2699
2771
  const instructions = buildServerInstructions({
2700
2772
  vendorDisplayName: config.vendorDisplayName,
2701
- annotationToolName
2773
+ annotationToolName,
2774
+ intentParamMode
2702
2775
  });
2703
2776
  internals.server._instructions = instructions;
2704
2777
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
@@ -2725,15 +2798,7 @@ function withBaton(server, supplied = {}) {
2725
2798
  vendorId: ctx.vendorId,
2726
2799
  vendorDisplayName: config.vendorDisplayName,
2727
2800
  consentToken: ctx.consentToken,
2728
- // Read off `ctx`, never re-resolved from `config`: the two paths must
2729
- // agree on the actor, and `principalIdMode`/`principalIdHmacKey` each have a
2730
- // default and an env fallback that a second resolution could take
2731
- // differently. Required (not optional) on the options type ON PURPOSE —
2732
- // the compiler then refuses a registration that forgets them, which is
2733
- // the mechanical version of "wiring two of four call sites".
2734
2801
  resolvePrincipal: ctx.resolvePrincipal,
2735
- principalIdMode: ctx.principalIdMode,
2736
- principalIdHmacKey: ctx.principalIdHmacKey,
2737
2802
  fallbackSessionId: ctx.fallbackSessionId,
2738
2803
  scrubber: ctx.scrubber,
2739
2804
  // The RESOLVED name, never `config.annotationToolName`: handing over the
@@ -2779,8 +2844,7 @@ function principalFromOAuthSub(context) {
2779
2844
  const claims = claimsOf(context);
2780
2845
  if (claims === null) return null;
2781
2846
  const sub = stringClaim(claims, "sub");
2782
- const iss = claims.iss;
2783
- return sub === null ? null : { principalId: sub, issuer: typeof iss === "string" && iss !== "" ? iss : null };
2847
+ return sub === null ? null : { principalId: sub };
2784
2848
  }
2785
2849
  function principalFromOAuthEmail(context) {
2786
2850
  const claims = claimsOf(context);
@@ -2841,7 +2905,13 @@ export {
2841
2905
  ToolCallErrorPayloadSchema,
2842
2906
  ToolCallStartEventSchema,
2843
2907
  ToolCallStartPayloadSchema,
2844
- hashPrincipalId,
2908
+ ToolListEndEventSchema,
2909
+ ToolListEndPayloadSchema,
2910
+ ToolListErrorEventSchema,
2911
+ ToolListErrorPayloadSchema,
2912
+ ToolListStartEventSchema,
2913
+ ToolListStartPayloadSchema,
2914
+ createBaton,
2845
2915
  identityScrub,
2846
2916
  principalFromOAuthEmail,
2847
2917
  principalFromOAuthSub,