@goodtiming/baton-sdk 0.5.2 → 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.2";
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";
@@ -742,7 +807,7 @@ function buildServerInstructions(options) {
742
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.`
743
808
  );
744
809
  }
745
- return rendered;
810
+ return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
746
811
  }
747
812
  function buildAnnotationToolDescription(options) {
748
813
  return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
@@ -754,16 +819,24 @@ var INTENT_SOURCE_PARAM = "injected_param";
754
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).";
755
820
  var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
756
821
  var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
757
- var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. One sentence: what a successful result should look like, so a silent/thin failure can be told apart from success.";
758
- var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. Short stable label for the broader task this call serves (e.g. 'prepare campaign approval'). REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.";
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.";
759
829
  function buildUserGoalParamDescription(options = {}) {
760
830
  return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
761
831
  }
762
- function buildOverallTaskParamDescription() {
763
- return OVERALL_TASK_PARAM_DESCRIPTION;
832
+ function buildOverallTaskParamDescription(options = {}) {
833
+ return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
764
834
  }
765
- function buildExpectedResultParamDescription() {
766
- return EXPECTED_RESULT_PARAM_DESCRIPTION;
835
+ function buildExpectedResultParamDescription(options = {}) {
836
+ return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
837
+ }
838
+ function requiredParamNames(intentParamMode) {
839
+ return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
767
840
  }
768
841
 
769
842
  // src/integrations/mcp/annotationName.ts
@@ -905,6 +978,9 @@ function extraHeaders(extra) {
905
978
  }
906
979
  return null;
907
980
  }
981
+ function isThenable(value) {
982
+ return typeof value?.then === "function";
983
+ }
908
984
 
909
985
  // src/integrations/mcp/principalResolution.ts
910
986
  function buildPrincipalResolutionContext(extra, toolName, args) {
@@ -916,6 +992,26 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
916
992
  authInfo: extraAuthInfo(extra)
917
993
  };
918
994
  }
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
+ }
1014
+ }
919
1015
  var warnedPreRenameShape = false;
920
1016
  function warnIfPreRenameShape(result) {
921
1017
  const userId = result?.userId;
@@ -929,7 +1025,7 @@ async function resolveCallPrincipal(hook, call) {
929
1025
  if (hook === void 0) return null;
930
1026
  try {
931
1027
  const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
932
- const result = await hook(context);
1028
+ const result = await withinHookBudget(hook(context));
933
1029
  const principal = normalizePrincipal(result);
934
1030
  if (principal === null) {
935
1031
  warnIfPreRenameShape(result);
@@ -966,56 +1062,67 @@ function scrubOrNull(scrubber, value, field) {
966
1062
  }
967
1063
  }
968
1064
 
969
- // src/integrations/mcp/runtimeAdapter.ts
1065
+ // src/integrations/mcp/clientObserved.ts
970
1066
  var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
971
- var CLIENT_NAME_MAX_LEN = 128;
972
- var UNKNOWN_AGENT_RUNTIME = "unknown";
973
- function clean(name, scrubber) {
974
- if (typeof name !== "string" || !name) return null;
975
- let cleaned = name;
976
- if (scrubber) {
977
- const scrubbed = scrubOrNull(scrubber, cleaned, "agent-runtime name");
978
- if (typeof scrubbed !== "string") return null;
979
- cleaned = scrubbed;
980
- }
981
- if (!cleaned) return null;
982
- return capCodePoints(cleaned, CLIENT_NAME_MAX_LEN);
983
- }
984
- function declaredOnRequest(meta, envelope) {
985
- for (const source of [envelope, meta]) {
986
- if (!source) continue;
987
- const info = source[CLIENT_INFO_META_KEY];
988
- if (info && typeof info === "object") {
989
- const name = info.name;
990
- if (name !== void 0) return name;
991
- }
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;
992
1080
  }
993
1081
  return void 0;
994
1082
  }
995
- 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) {
996
1115
  try {
997
- const server = options.server;
998
- if (!server) return void 0;
999
- const inner = server.server;
1000
- const holder = inner ?? server;
1001
- if (typeof holder.getClientVersion !== "function") return void 0;
1002
- return holder.getClientVersion()?.name;
1116
+ return read();
1003
1117
  } catch {
1004
1118
  return void 0;
1005
1119
  }
1006
1120
  }
1007
- function detectAgentRuntime(meta, options = {}) {
1008
- const { envelope, scrubber } = options;
1009
- const onRequest = clean(declaredOnRequest(meta, envelope), scrubber);
1010
- if (onRequest !== null) return onRequest;
1011
- const onConnection = clean(declaredOnConnection(options), scrubber);
1012
- if (onConnection !== null) return onConnection;
1013
- if (meta) {
1014
- for (const key of Object.keys(meta)) {
1015
- if (key.startsWith("claudecode/")) return "claude-code";
1016
- }
1017
- }
1018
- return null;
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 } };
1019
1126
  }
1020
1127
 
1021
1128
  // src/integrations/mcp/sessionResolution.ts
@@ -1045,11 +1152,6 @@ function registerAnnotationTool(server, options) {
1045
1152
  },
1046
1153
  async (args, extra) => {
1047
1154
  const meta = extraMeta(extra);
1048
- const runtime = detectAgentRuntime(meta, {
1049
- envelope: extraEnvelope(extra),
1050
- server,
1051
- scrubber: options.scrubber
1052
- }) ?? UNKNOWN_AGENT_RUNTIME;
1053
1155
  const scrubbedMeta = scrubOrNull(
1054
1156
  options.scrubber,
1055
1157
  meta ? roundMetaCoordinates(meta) : null,
@@ -1072,9 +1174,9 @@ function registerAnnotationTool(server, options) {
1072
1174
  sequence_number: options.counter.next(sessionId),
1073
1175
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1074
1176
  consent_token: options.consentToken,
1075
- agent_runtime: runtime,
1076
1177
  principal,
1077
1178
  transport_observed: observeTransport(extra),
1179
+ client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
1078
1180
  runtime_meta: scrubbedMeta,
1079
1181
  payload: {
1080
1182
  // Agent-facing names -> wire keys, as with `overall_task`
@@ -1381,7 +1483,7 @@ function resolveTenantId(explicit, vendorId) {
1381
1483
  if (fromEnv) return fromEnv;
1382
1484
  return vendorId;
1383
1485
  }
1384
- function resolveBatonConfig(config, serverName) {
1486
+ function resolveBatonConfig(config) {
1385
1487
  const dsnString = selectDsn(
1386
1488
  config.dsn,
1387
1489
  {
@@ -1417,14 +1519,7 @@ function resolveBatonConfig(config, serverName) {
1417
1519
  // in the server instructions and the annotation tool description, which is
1418
1520
  // the whitelabel obligation the validator cites when it refuses the empty
1419
1521
  // one. ⚠ Python uses `or` here and still has the inconsistency.
1420
- //
1421
- // Between the explicit value and the segment sits the server's own name,
1422
- // under the guards in `annotationName.ts`: the segment is an opaque
1423
- // `srv-<8 hex>`, and it was what agents were told the vendor is called.
1424
- vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
1425
- vendorId: dsn.vendorId,
1426
- annotationToolName: config.annotationToolName
1427
- }) ?? dsn.vendorId,
1522
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
1428
1523
  // `??`, not `||`: an explicit empty string must survive to the validation
1429
1524
  // below and be REFUSED there, rather than be quietly replaced by the
1430
1525
  // default it was deliberately not left as.
@@ -1438,6 +1533,14 @@ function resolveBatonConfig(config, serverName) {
1438
1533
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
1439
1534
  };
1440
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
+ }
1441
1544
  var RENAMED_KEYS = {
1442
1545
  resolveUser: "resolvePrincipal"
1443
1546
  };
@@ -1674,13 +1777,8 @@ function injectGoalParams(inputSchema, intentParamMode) {
1674
1777
  function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1675
1778
  const dispositions = {};
1676
1779
  const toInject = {};
1677
- if (USER_GOAL_PARAM_NAME in existingShape) {
1678
- dispositions[USER_GOAL_PARAM_NAME] = "native";
1679
- } else {
1680
- dispositions[USER_GOAL_PARAM_NAME] = "injected";
1681
- toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
1682
- }
1683
1780
  for (const [name, buildDescription] of [
1781
+ [USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
1684
1782
  [EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
1685
1783
  [OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
1686
1784
  ]) {
@@ -1688,7 +1786,7 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
1688
1786
  dispositions[name] = "native";
1689
1787
  } else {
1690
1788
  dispositions[name] = "injected";
1691
- toInject[name] = zodImpl.string().optional().describe(buildDescription());
1789
+ toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
1692
1790
  }
1693
1791
  }
1694
1792
  return { dispositions, toInject };
@@ -1704,21 +1802,23 @@ function injectGoalParamsV2(inputSchema, intentParamMode) {
1704
1802
  return { schema: inputSchema, dispositions };
1705
1803
  return { schema: candidate.extend(toInject), dispositions };
1706
1804
  }
1707
- function advertiseUserGoalRequired(result, isInjected) {
1805
+ function advertiseIntentParamsRequired(result, names, isInjected) {
1708
1806
  const tools = result?.tools;
1709
1807
  if (!Array.isArray(tools)) return result;
1710
1808
  let changed = false;
1711
1809
  const advertised = tools.map((tool) => {
1712
1810
  const entry = tool;
1713
- if (typeof entry?.name !== "string" || !isInjected(entry.name)) return tool;
1714
- const schema = entry.inputSchema;
1811
+ const toolName = entry?.name;
1812
+ if (typeof toolName !== "string") return tool;
1813
+ const schema = entry?.inputSchema;
1715
1814
  if (!schema || typeof schema !== "object") return tool;
1716
- const declared = schema.required ?? [];
1717
- if (!Array.isArray(declared)) return tool;
1718
- const required = declared;
1719
- if (required.includes(USER_GOAL_PARAM_NAME)) return tool;
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;
1720
1820
  changed = true;
1721
- return { ...entry, inputSchema: { ...schema, required: [...required, USER_GOAL_PARAM_NAME] } };
1821
+ return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
1722
1822
  });
1723
1823
  return changed ? { ...result, tools: advertised } : result;
1724
1824
  }
@@ -1767,7 +1867,11 @@ function assembleSurface(serverMeta, tools) {
1767
1867
  function buildSeamAugmentations(options) {
1768
1868
  return {
1769
1869
  injected_tools: [...options.injectedToolNames].sort(),
1770
- 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,
1771
1875
  instructions_suffix: true
1772
1876
  };
1773
1877
  }
@@ -1778,16 +1882,17 @@ var wired = /* @__PURE__ */ new WeakSet();
1778
1882
  var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
1779
1883
  var callSlots = new AsyncLocalStorage();
1780
1884
  var SurfaceState = class {
1781
- constructor(serverMeta) {
1885
+ constructor(serverMeta, emittedHashes) {
1782
1886
  this.serverMeta = serverMeta;
1887
+ this.emittedHashes = emittedHashes;
1783
1888
  }
1784
1889
  serverMeta;
1890
+ emittedHashes;
1785
1891
  /** Every tool this install has seen, keyed by its CURRENT name. `disabled`
1786
1892
  * is tracked alongside rather than pruned, so re-enabling costs nothing and
1787
1893
  * — crucially — never needs a re-capture, which would re-read Baton's own
1788
1894
  * injected schema as if it were vendor-true. */
1789
1895
  rawTools = /* @__PURE__ */ new Map();
1790
- emittedHashes = /* @__PURE__ */ new Set();
1791
1896
  dirty = false;
1792
1897
  /** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
1793
1898
  * which picks the spelling THIS SDK major puts on the wire. */
@@ -1839,23 +1944,13 @@ function messageOf(err) {
1839
1944
  }
1840
1945
  async function resolveEnvelopeParts(ctx, extra) {
1841
1946
  const meta = extraMeta(extra);
1842
- const runtime = detectAgentRuntime(meta, {
1843
- // v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
1844
- // `_meta`; 1.x leaves them in. Both are handed over — see
1845
- // `mcpTypes.extraEnvelope`.
1846
- envelope: extraEnvelope(extra),
1847
- // Tier 2's carrier: neither peer puts client identity on the
1848
- // handler context, both expose the cached handshake on the server.
1849
- server: ctx.server,
1850
- scrubber: ctx.scrubber
1851
- }) ?? UNKNOWN_AGENT_RUNTIME;
1852
1947
  const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
1853
1948
  const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
1854
- return { sessionId, runtime, scrubbedMeta };
1949
+ return { sessionId, scrubbedMeta };
1855
1950
  }
1856
1951
  async function openCall(ctx, toolName, extra, params, registered = true) {
1857
1952
  await maybeEmitSurfaceSnapshot(ctx);
1858
- const { sessionId, runtime, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1953
+ const { sessionId, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
1859
1954
  const dispositions = ctx.paramRegistry.get(toolName);
1860
1955
  const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
1861
1956
  const rawExpected = extractGoalParam(
@@ -1869,7 +1964,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
1869
1964
  const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
1870
1965
  const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
1871
1966
  const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
1872
- const callId = uuidv72();
1967
+ const callId = uuid7();
1873
1968
  const principal = await resolveCallPrincipal(
1874
1969
  ctx.resolvePrincipal,
1875
1970
  { extra, toolName, arguments: params }
@@ -1879,19 +1974,12 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
1879
1974
  vendor_id: ctx.vendorId,
1880
1975
  session_id: sessionId,
1881
1976
  consent_token: ctx.consentToken,
1882
- agent_runtime: runtime,
1883
- // The five `...common` sites below are the tool-call legs — start, end,
1884
- // and BOTH failure shapes (SPEC §11.4.3) — plus the proactive
1885
- // annotation, the same five Python stamps (`middleware.py`
1886
- // 503/547/586/644/674; it was four until the returned shape landed
1887
- // there too). `surface_snapshot` is deliberately NOT among them: it
1888
- // describes the SERVER and is captured outside any call, so there is no
1889
- // caller to name (register D5).
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.
1890
1980
  principal,
1891
- // Same five stamps, same exclusion: a surface_snapshot describes the
1892
- // SERVER and is captured outside any call, so it has no caller's
1893
- // transport to name any more than it has a caller to name.
1894
1981
  transport_observed: observeTransport(extra),
1982
+ client_observed: observeClient(extra, ctx),
1895
1983
  runtime_meta: scrubbedMeta
1896
1984
  };
1897
1985
  if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
@@ -2113,6 +2201,7 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
2113
2201
  delete args[paramName];
2114
2202
  return typeof raw === "string" && raw.trim() ? raw : null;
2115
2203
  }
2204
+ var MAX_REMEMBERED_SURFACES = 1024;
2116
2205
  async function maybeEmitSurfaceSnapshot(ctx) {
2117
2206
  if (!ctx.surfaceState.dirty) return;
2118
2207
  ctx.surfaceState.dirty = false;
@@ -2126,21 +2215,24 @@ async function maybeEmitSurfaceSnapshot(ctx) {
2126
2215
  `);
2127
2216
  return;
2128
2217
  }
2129
- 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);
2130
2222
  const seam = buildSeamAugmentations({
2131
2223
  injectedToolNames: [ctx.annotationToolName],
2132
2224
  intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
2133
- intentParamMode: ctx.intentParamMode
2225
+ intentParamMode: ctx.intentParamMode,
2226
+ requiredParamNames: requiredParamNames(ctx.intentParamMode)
2134
2227
  });
2135
2228
  try {
2136
2229
  await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
2137
2230
  } catch (err) {
2138
2231
  process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
2139
2232
  `);
2233
+ emitted.delete(digest);
2140
2234
  ctx.surfaceState.dirty = true;
2141
- return;
2142
2235
  }
2143
- ctx.surfaceState.emittedHashes.add(digest);
2144
2236
  }
2145
2237
  function captureAndInject(name, entry, ctx) {
2146
2238
  if (!entry || typeof entry !== "object") return;
@@ -2154,6 +2246,7 @@ function captureAndInject(name, entry, ctx) {
2154
2246
  mutable.inputSchema = schema;
2155
2247
  ctx.bustSchemaMemo(name);
2156
2248
  ctx.paramRegistry.set(name, dispositions);
2249
+ if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
2157
2250
  } else {
2158
2251
  ctx.paramRegistry.delete(name);
2159
2252
  }
@@ -2174,6 +2267,7 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2174
2267
  const handler = handlers.get(method);
2175
2268
  if (typeof handler !== "function" || handler[seamTag]) return;
2176
2269
  const seamed = wrap(handler);
2270
+ for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];
2177
2271
  seamed[seamTag] = true;
2178
2272
  handlers.set(method, seamed);
2179
2273
  };
@@ -2185,10 +2279,11 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
2185
2279
  };
2186
2280
  }
2187
2281
  function installToolsListSeam(lowLevel, ctx) {
2188
- 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";
2189
2284
  const advertise = (result) => {
2190
2285
  try {
2191
- return advertiseUserGoalRequired(result, isInjected);
2286
+ return advertiseIntentParamsRequired(result, names, isInjected);
2192
2287
  } catch (err) {
2193
2288
  process.stderr.write(
2194
2289
  `baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
@@ -2206,7 +2301,8 @@ var LIFECYCLE_SEAMS = {
2206
2301
  resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
2207
2302
  resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
2208
2303
  promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
2209
- promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
2304
+ promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam"),
2305
+ toolList: /* @__PURE__ */ Symbol("batonToolListSeam")
2210
2306
  };
2211
2307
  function installLifecycleSeam(lowLevel, ctx, spec) {
2212
2308
  installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
@@ -2253,6 +2349,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
2253
2349
  async function openLifecycleCall(ctx, spec, requestParams, extra) {
2254
2350
  try {
2255
2351
  const parts = await resolveEnvelopeParts(ctx, extra);
2352
+ const principal = spec.resolvesPrincipal ? await resolveCallPrincipal(ctx.resolvePrincipal, { extra, toolName: null, arguments: {} }) : null;
2256
2353
  return {
2257
2354
  sessionId: parts.sessionId,
2258
2355
  subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
@@ -2261,8 +2358,9 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
2261
2358
  vendor_id: ctx.vendorId,
2262
2359
  session_id: parts.sessionId,
2263
2360
  consent_token: ctx.consentToken,
2264
- agent_runtime: parts.runtime,
2361
+ principal,
2265
2362
  transport_observed: observeTransport(extra),
2363
+ client_observed: observeClient(extra, ctx),
2266
2364
  runtime_meta: parts.scrubbedMeta
2267
2365
  }
2268
2366
  };
@@ -2335,6 +2433,18 @@ var LIFECYCLE_SPECS = [
2335
2433
  startParams: (params) => ({
2336
2434
  params: paramsBag(params["arguments"])
2337
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
2338
2448
  }
2339
2449
  ];
2340
2450
  function installLifecycleSeams(lowLevel, ctx) {
@@ -2465,9 +2575,6 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
2465
2575
  })
2466
2576
  );
2467
2577
  }
2468
- function isThenable(value) {
2469
- return typeof value?.then === "function";
2470
- }
2471
2578
  function wrapIfNeeded(nameRef, entry, ctx) {
2472
2579
  if (!entry || typeof entry !== "object") return;
2473
2580
  const mutable = entry;
@@ -2543,47 +2650,57 @@ function withBaton(server, supplied = {}) {
2543
2650
  annotationToolName: ""
2544
2651
  });
2545
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) {
2546
2681
  const internals = server;
2547
2682
  const serverName = usableServerName(() => ({
2548
2683
  name: internals.server._serverInfo?.name,
2549
2684
  className: internals.constructor.name
2550
2685
  }));
2551
- const config = resolveBatonConfig(supplied, serverName);
2686
+ const config = withServerDisplayName(resolved, supplied, serverName);
2552
2687
  const sink = config.sink ?? new StdoutSink();
2553
2688
  const annotationToolName = resolveAnnotationToolName(serverName, config);
2554
2689
  const intentParamMode = config.intentParamMode ?? "required";
2555
- const counter = new SessionCounter();
2556
- const fallbackSessionId = `sdk-${uuidv72()}`;
2690
+ const counter2 = new SessionCounter();
2691
+ const fallbackSessionId = `sdk-${uuid7()}`;
2557
2692
  const tenantId = resolveTenantId(config.tenantId, config.vendorId);
2558
2693
  const scrubber = config.scrubber ?? new Scrubber().scrub;
2559
2694
  const serverMeta = buildServerMeta(server.server);
2560
- const surfaceState = new SurfaceState(serverMeta);
2695
+ const surfaceState = new SurfaceState(serverMeta, emittedSurfaceHashes);
2561
2696
  const emitSurface = async (sessionId, digest, snapshot) => {
2562
2697
  const event = SurfaceSnapshotEventSchema.parse({
2563
2698
  tenant_id: tenantId,
2564
2699
  vendor_id: config.vendorId,
2565
2700
  session_id: sessionId,
2566
2701
  consent_token: config.consentToken,
2567
- sequence_number: counter.next(sessionId),
2702
+ sequence_number: counter2.next(sessionId),
2568
2703
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
2569
- // Deliberately the literal, NOT the ladder — and an earlier comment
2570
- // here justified that by saying no call is in scope, which is false:
2571
- // `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
2572
- // handshake has happened and tier 2's carrier is live in this closure.
2573
- // The real reason is that the snapshot describes the VENDOR'S SURFACE,
2574
- // which is the same whoever is calling. It is hashed and emitted at
2575
- // most once per process per surface, so the client that happens to
2576
- // trigger it is whichever one called first — attributing the surface to
2577
- // that client would read as a fact about the surface and be an accident
2578
- // of timing. Python hardcodes it from the same in-call position
2579
- // (`_tool_wrap.py`), so this is parity, not a gap.
2580
- //
2581
- // ⚠ Consequence worth knowing: one session emits `surface_snapshot`
2582
- // with `unknown` and everything else with the client's name, so a
2583
- // consumer grouping on `agent_runtime` alone sees two runtimes for one
2584
- // client. Intended; group surfaces on `(tenant_id, vendor_id,
2585
- // surface_hash)`, which is what the Console's table is keyed on.
2586
- agent_runtime: UNKNOWN_AGENT_RUNTIME,
2587
2704
  payload: {
2588
2705
  surface_hash: digest,
2589
2706
  server_info: snapshot.server_info,
@@ -2599,6 +2716,15 @@ function withBaton(server, supplied = {}) {
2599
2716
  const memo = internals._toolInputSchemaJson;
2600
2717
  if (memo && typeof memo === "object") delete memo[name];
2601
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
+ };
2602
2728
  const isV2Server = typeof internals.toolInputSchemaJson === "function";
2603
2729
  const vendorToolJsonSchema = (name, inputSchema) => {
2604
2730
  if (isV2Server) {
@@ -2623,7 +2749,7 @@ function withBaton(server, supplied = {}) {
2623
2749
  const tracker = new ProactiveTracker();
2624
2750
  const ctx = {
2625
2751
  sink,
2626
- counter,
2752
+ counter: counter2,
2627
2753
  tenantId,
2628
2754
  vendorId: config.vendorId,
2629
2755
  consentToken: config.consentToken,
@@ -2637,13 +2763,15 @@ function withBaton(server, supplied = {}) {
2637
2763
  resolvePrincipal: config.resolvePrincipal,
2638
2764
  vendorToolJsonSchema,
2639
2765
  bustSchemaMemo,
2766
+ dropSubagentClause,
2640
2767
  tracker,
2641
2768
  surfaceState,
2642
2769
  emitSurface
2643
2770
  };
2644
2771
  const instructions = buildServerInstructions({
2645
2772
  vendorDisplayName: config.vendorDisplayName,
2646
- annotationToolName
2773
+ annotationToolName,
2774
+ intentParamMode
2647
2775
  });
2648
2776
  internals.server._instructions = instructions;
2649
2777
  if (intentParamMode === "required") installToolsListSeam(internals.server, ctx);
@@ -2777,6 +2905,13 @@ export {
2777
2905
  ToolCallErrorPayloadSchema,
2778
2906
  ToolCallStartEventSchema,
2779
2907
  ToolCallStartPayloadSchema,
2908
+ ToolListEndEventSchema,
2909
+ ToolListEndPayloadSchema,
2910
+ ToolListErrorEventSchema,
2911
+ ToolListErrorPayloadSchema,
2912
+ ToolListStartEventSchema,
2913
+ ToolListStartPayloadSchema,
2914
+ createBaton,
2780
2915
  identityScrub,
2781
2916
  principalFromOAuthEmail,
2782
2917
  principalFromOAuthSub,