@goodtiming/baton-sdk 0.5.2 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/dist/index.cjs +331 -186
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +614 -34
- package/dist/index.d.ts +614 -34
- package/dist/index.js +322 -184
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -77,6 +77,13 @@ __export(index_exports, {
|
|
|
77
77
|
ToolCallErrorPayloadSchema: () => ToolCallErrorPayloadSchema,
|
|
78
78
|
ToolCallStartEventSchema: () => ToolCallStartEventSchema,
|
|
79
79
|
ToolCallStartPayloadSchema: () => ToolCallStartPayloadSchema,
|
|
80
|
+
ToolListEndEventSchema: () => ToolListEndEventSchema,
|
|
81
|
+
ToolListEndPayloadSchema: () => ToolListEndPayloadSchema,
|
|
82
|
+
ToolListErrorEventSchema: () => ToolListErrorEventSchema,
|
|
83
|
+
ToolListErrorPayloadSchema: () => ToolListErrorPayloadSchema,
|
|
84
|
+
ToolListStartEventSchema: () => ToolListStartEventSchema,
|
|
85
|
+
ToolListStartPayloadSchema: () => ToolListStartPayloadSchema,
|
|
86
|
+
createBaton: () => createBaton,
|
|
80
87
|
identityScrub: () => identityScrub,
|
|
81
88
|
principalFromOAuthEmail: () => principalFromOAuthEmail,
|
|
82
89
|
principalFromOAuthSub: () => principalFromOAuthSub,
|
|
@@ -86,11 +93,36 @@ __export(index_exports, {
|
|
|
86
93
|
module.exports = __toCommonJS(index_exports);
|
|
87
94
|
|
|
88
95
|
// src/version.ts
|
|
89
|
-
var SDK_VERSION = "ts-0.5.
|
|
96
|
+
var SDK_VERSION = "ts-0.5.4";
|
|
90
97
|
|
|
91
98
|
// src/events.ts
|
|
92
99
|
var import_zod = require("zod");
|
|
93
|
-
|
|
100
|
+
|
|
101
|
+
// src/uuid7.ts
|
|
102
|
+
var import_node_crypto = require("crypto");
|
|
103
|
+
var COUNTER_MAX = 4095;
|
|
104
|
+
var lastMs = -1;
|
|
105
|
+
var counter = 0;
|
|
106
|
+
function uuid7() {
|
|
107
|
+
const bytes = (0, import_node_crypto.randomBytes)(18);
|
|
108
|
+
const seed = (bytes[16] << 8 | bytes[17]) & 2047;
|
|
109
|
+
const now = Date.now();
|
|
110
|
+
if (now > lastMs) {
|
|
111
|
+
lastMs = now;
|
|
112
|
+
counter = seed;
|
|
113
|
+
} else if (++counter > COUNTER_MAX) {
|
|
114
|
+
lastMs += 1;
|
|
115
|
+
counter = seed;
|
|
116
|
+
}
|
|
117
|
+
bytes.writeUIntBE(lastMs, 0, 6);
|
|
118
|
+
bytes[6] = 112 | counter >> 8;
|
|
119
|
+
bytes[7] = counter & 255;
|
|
120
|
+
bytes[8] = 128 | bytes[8] & 63;
|
|
121
|
+
const hex = bytes.toString("hex", 0, 16);
|
|
122
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/events.ts
|
|
94
126
|
var ToolCallStartPayloadSchema = import_zod.z.object({
|
|
95
127
|
tool_name: import_zod.z.string(),
|
|
96
128
|
params: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({}),
|
|
@@ -167,6 +199,7 @@ var ToolCallErrorPayloadSchema = import_zod.z.object({
|
|
|
167
199
|
var AnnotationPayloadSchema = import_zod.z.object({
|
|
168
200
|
intent: import_zod.z.string().nullable().default(null),
|
|
169
201
|
expected_outcome: import_zod.z.string().nullable().default(null),
|
|
202
|
+
what_happened: import_zod.z.string().nullable().default(null),
|
|
170
203
|
signal_type: import_zod.z.string().nullable().default(null),
|
|
171
204
|
workflow: import_zod.z.string().nullable().default(null),
|
|
172
205
|
suggested_improvement: import_zod.z.string().nullable().default(null),
|
|
@@ -183,6 +216,10 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
|
|
|
183
216
|
seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
|
|
184
217
|
}).strict();
|
|
185
218
|
var DEFAULT_CONSENT_TOKEN = "customer-consented";
|
|
219
|
+
var ClientObservedSchema = import_zod.z.object({
|
|
220
|
+
info: import_zod.z.object({ name: import_zod.z.string().optional(), version: import_zod.z.string().optional() }).strict().optional(),
|
|
221
|
+
headers: import_zod.z.object({ "user-agent": import_zod.z.string().optional(), "x-anthropic-client": import_zod.z.string().optional() }).strict().optional()
|
|
222
|
+
}).strict();
|
|
186
223
|
var PrincipalWireSchema = import_zod.z.object({
|
|
187
224
|
id: import_zod.z.string(),
|
|
188
225
|
source: import_zod.z.string(),
|
|
@@ -190,7 +227,7 @@ var PrincipalWireSchema = import_zod.z.object({
|
|
|
190
227
|
display_name: import_zod.z.string().nullable().optional()
|
|
191
228
|
}).strict();
|
|
192
229
|
var envelopeShape = {
|
|
193
|
-
event_id: import_zod.z.uuid().default(() => (
|
|
230
|
+
event_id: import_zod.z.uuid().default(() => uuid7()),
|
|
194
231
|
tenant_id: import_zod.z.string(),
|
|
195
232
|
vendor_id: import_zod.z.string(),
|
|
196
233
|
session_id: import_zod.z.string(),
|
|
@@ -198,9 +235,12 @@ var envelopeShape = {
|
|
|
198
235
|
captured_at: import_zod.z.string(),
|
|
199
236
|
consent_token: import_zod.z.string(),
|
|
200
237
|
sdk_version: import_zod.z.string().default(SDK_VERSION),
|
|
238
|
+
// Legacy (SPEC §3.4): never set by this SDK, so always the default. The
|
|
239
|
+
// consumer names the client from `client_observed`.
|
|
201
240
|
agent_runtime: import_zod.z.string().default("unknown"),
|
|
202
241
|
principal: PrincipalWireSchema.nullable().default(null),
|
|
203
242
|
transport_observed: import_zod.z.string().nullable().default(null),
|
|
243
|
+
client_observed: ClientObservedSchema.nullable().default(null),
|
|
204
244
|
call_id: import_zod.z.string().nullable().default(null),
|
|
205
245
|
runtime_meta: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).nullable().default(null)
|
|
206
246
|
};
|
|
@@ -224,7 +264,11 @@ var EventTypeSchema = import_zod.z.enum([
|
|
|
224
264
|
"prompt_list_error",
|
|
225
265
|
"prompt_get_start",
|
|
226
266
|
"prompt_get_end",
|
|
227
|
-
"prompt_get_error"
|
|
267
|
+
"prompt_get_error",
|
|
268
|
+
// SPEC §11.4.5.
|
|
269
|
+
"tool_list_start",
|
|
270
|
+
"tool_list_end",
|
|
271
|
+
"tool_list_error"
|
|
228
272
|
]);
|
|
229
273
|
var timingShape = { duration_ms: import_zod.z.number().int().nullable().default(null) };
|
|
230
274
|
var failureShape = { error_type: import_zod.z.string(), error_body: import_zod.z.string(), ...timingShape };
|
|
@@ -263,6 +307,14 @@ var PromptListEndPayloadSchema = import_zod.z.object({
|
|
|
263
307
|
var PromptListErrorPayloadSchema = import_zod.z.object({
|
|
264
308
|
...failureShape
|
|
265
309
|
}).strict();
|
|
310
|
+
var ToolListStartPayloadSchema = import_zod.z.object({}).strict();
|
|
311
|
+
var ToolListEndPayloadSchema = import_zod.z.object({
|
|
312
|
+
count: import_zod.z.number().int(),
|
|
313
|
+
...timingShape
|
|
314
|
+
}).strict();
|
|
315
|
+
var ToolListErrorPayloadSchema = import_zod.z.object({
|
|
316
|
+
...failureShape
|
|
317
|
+
}).strict();
|
|
266
318
|
var PromptGetStartPayloadSchema = import_zod.z.object({
|
|
267
319
|
name: import_zod.z.string(),
|
|
268
320
|
/** The prompt's arguments, PII-scrubbed (SPEC §7). `{}` from this producer
|
|
@@ -278,18 +330,22 @@ var PromptGetErrorPayloadSchema = import_zod.z.object({
|
|
|
278
330
|
name: import_zod.z.string(),
|
|
279
331
|
...failureShape
|
|
280
332
|
}).strict();
|
|
333
|
+
var REQUIRED_CALL_ID = import_zod.z.string().min(1);
|
|
281
334
|
var ToolCallStartEventSchema = import_zod.z.object({
|
|
282
335
|
...envelopeShape,
|
|
336
|
+
call_id: REQUIRED_CALL_ID,
|
|
283
337
|
event_type: import_zod.z.literal("tool_call_start").default("tool_call_start"),
|
|
284
338
|
payload: ToolCallStartPayloadSchema
|
|
285
339
|
}).strict();
|
|
286
340
|
var ToolCallEndEventSchema = import_zod.z.object({
|
|
287
341
|
...envelopeShape,
|
|
342
|
+
call_id: REQUIRED_CALL_ID,
|
|
288
343
|
event_type: import_zod.z.literal("tool_call_end").default("tool_call_end"),
|
|
289
344
|
payload: ToolCallEndPayloadSchema
|
|
290
345
|
}).strict();
|
|
291
346
|
var ToolCallErrorEventSchema = import_zod.z.object({
|
|
292
347
|
...envelopeShape,
|
|
348
|
+
call_id: REQUIRED_CALL_ID,
|
|
293
349
|
event_type: import_zod.z.literal("tool_call_error").default("tool_call_error"),
|
|
294
350
|
payload: ToolCallErrorPayloadSchema
|
|
295
351
|
}).strict();
|
|
@@ -363,6 +419,21 @@ var PromptGetErrorEventSchema = import_zod.z.object({
|
|
|
363
419
|
event_type: import_zod.z.literal("prompt_get_error").default("prompt_get_error"),
|
|
364
420
|
payload: PromptGetErrorPayloadSchema
|
|
365
421
|
}).strict();
|
|
422
|
+
var ToolListStartEventSchema = import_zod.z.object({
|
|
423
|
+
...envelopeShape,
|
|
424
|
+
event_type: import_zod.z.literal("tool_list_start").default("tool_list_start"),
|
|
425
|
+
payload: ToolListStartPayloadSchema
|
|
426
|
+
}).strict();
|
|
427
|
+
var ToolListEndEventSchema = import_zod.z.object({
|
|
428
|
+
...envelopeShape,
|
|
429
|
+
event_type: import_zod.z.literal("tool_list_end").default("tool_list_end"),
|
|
430
|
+
payload: ToolListEndPayloadSchema
|
|
431
|
+
}).strict();
|
|
432
|
+
var ToolListErrorEventSchema = import_zod.z.object({
|
|
433
|
+
...envelopeShape,
|
|
434
|
+
event_type: import_zod.z.literal("tool_list_error").default("tool_list_error"),
|
|
435
|
+
payload: ToolListErrorPayloadSchema
|
|
436
|
+
}).strict();
|
|
366
437
|
var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
367
438
|
ToolCallStartEventSchema,
|
|
368
439
|
ToolCallEndEventSchema,
|
|
@@ -380,7 +451,10 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
|
380
451
|
PromptListErrorEventSchema,
|
|
381
452
|
PromptGetStartEventSchema,
|
|
382
453
|
PromptGetEndEventSchema,
|
|
383
|
-
PromptGetErrorEventSchema
|
|
454
|
+
PromptGetErrorEventSchema,
|
|
455
|
+
ToolListStartEventSchema,
|
|
456
|
+
ToolListEndEventSchema,
|
|
457
|
+
ToolListErrorEventSchema
|
|
384
458
|
]);
|
|
385
459
|
|
|
386
460
|
// src/scrub.ts
|
|
@@ -676,7 +750,6 @@ var HttpSink = class _HttpSink {
|
|
|
676
750
|
|
|
677
751
|
// src/integrations/mcp/withBaton.ts
|
|
678
752
|
var import_node_async_hooks = require("async_hooks");
|
|
679
|
-
var import_uuid2 = require("uuid");
|
|
680
753
|
|
|
681
754
|
// src/integrations/mcp/annotation.ts
|
|
682
755
|
var import_zod2 = require("zod");
|
|
@@ -792,30 +865,21 @@ function principalFor(principal, onUnregisteredForm) {
|
|
|
792
865
|
// src/integrations/mcp/llmText.ts
|
|
793
866
|
var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} usage and friction SDK. Use \`${annotationToolName}\` to report when a ${vendorDisplayName} tool call goes wrong, or when a tool you needed does not exist, so ${vendorDisplayName} can improve their product. See that tool's description for field-level detail.
|
|
794
867
|
|
|
795
|
-
AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\`
|
|
868
|
+
AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` with what_happened (REQUIRED, your own words, NOT a category), tool_name (REQUIRED) and suggested_improvement (REQUIRED whenever you can articulate one).
|
|
796
869
|
|
|
797
|
-
IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` with
|
|
870
|
+
IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` once per user request, not per call, with what_happened and tool_name (none if no tool) AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
|
|
798
871
|
var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Report a ${vendorDisplayName} tool call that went wrong \u2014 call this AFTER a call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. Do NOT call it before a tool call or to narrate normal successful work.
|
|
799
872
|
|
|
800
873
|
Fields:
|
|
801
874
|
- user_goal: one sentence on what the user is trying to accomplish.
|
|
875
|
+
- what_happened: REQUIRED on a report. 1-2 plain sentences in YOUR OWN WORDS: what you asked for, what came back, and why it was unusable. Do NOT pick a category or invent a label \u2014 describe it.
|
|
876
|
+
- tool_name: REQUIRED on a report. The ${vendorDisplayName} tool that went wrong. Write none if no tool exists for the request.
|
|
802
877
|
- expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
|
|
803
878
|
- overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task.
|
|
804
|
-
-
|
|
805
|
-
-
|
|
806
|
-
- context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. For signal_type='feature_gap' also missing_capability_field and requested_capability.`;
|
|
879
|
+
- suggested_improvement: A concrete sentence about what product change would have helped.
|
|
880
|
+
- context: supplementary info not covered above. Common keys: plan, alternatives_considered, likely_cause, user_impact, error_class, downstream_blocked, confidence_in_intent. When no tool covers the request also missing_capability_field and requested_capability.`;
|
|
807
881
|
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
808
882
|
var INSTRUCTIONS_LENGTH_CAP = 1500;
|
|
809
|
-
var SIGNAL_TYPES = [
|
|
810
|
-
"failure",
|
|
811
|
-
"retry_loop",
|
|
812
|
-
"dead_end",
|
|
813
|
-
"parameter_confusion",
|
|
814
|
-
"slow_performance",
|
|
815
|
-
"abandonment",
|
|
816
|
-
"feature_gap",
|
|
817
|
-
"other"
|
|
818
|
-
];
|
|
819
883
|
function renderServerInstructions(options) {
|
|
820
884
|
return SERVER_INSTRUCTIONS_TEMPLATE(options.vendorDisplayName, options.annotationToolName);
|
|
821
885
|
}
|
|
@@ -829,7 +893,7 @@ function buildServerInstructions(options) {
|
|
|
829
893
|
`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.`
|
|
830
894
|
);
|
|
831
895
|
}
|
|
832
|
-
return rendered;
|
|
896
|
+
return options.intentParamMode === "off" ? rendered : rendered + INSTRUCTIONS_SUBAGENT_CLAUSE;
|
|
833
897
|
}
|
|
834
898
|
function buildAnnotationToolDescription(options) {
|
|
835
899
|
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
@@ -841,16 +905,24 @@ var INTENT_SOURCE_PARAM = "injected_param";
|
|
|
841
905
|
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).";
|
|
842
906
|
var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. " + USER_GOAL_PARAM_BODY;
|
|
843
907
|
var USER_GOAL_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + USER_GOAL_PARAM_BODY;
|
|
844
|
-
var
|
|
845
|
-
var
|
|
908
|
+
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.";
|
|
909
|
+
var EXPECTED_RESULT_PARAM_DESCRIPTION = "OPTIONAL. " + EXPECTED_RESULT_PARAM_BODY;
|
|
910
|
+
var EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + EXPECTED_RESULT_PARAM_BODY;
|
|
911
|
+
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.";
|
|
912
|
+
var OVERALL_TASK_PARAM_DESCRIPTION = "OPTIONAL. " + OVERALL_TASK_PARAM_BODY;
|
|
913
|
+
var OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED = "REQUIRED. " + OVERALL_TASK_PARAM_BODY;
|
|
914
|
+
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.";
|
|
846
915
|
function buildUserGoalParamDescription(options = {}) {
|
|
847
916
|
return options.intentParamMode === "required" ? USER_GOAL_PARAM_DESCRIPTION_REQUIRED : USER_GOAL_PARAM_DESCRIPTION;
|
|
848
917
|
}
|
|
849
|
-
function buildOverallTaskParamDescription() {
|
|
850
|
-
return OVERALL_TASK_PARAM_DESCRIPTION;
|
|
918
|
+
function buildOverallTaskParamDescription(options = {}) {
|
|
919
|
+
return options.intentParamMode === "required" ? OVERALL_TASK_PARAM_DESCRIPTION_REQUIRED : OVERALL_TASK_PARAM_DESCRIPTION;
|
|
851
920
|
}
|
|
852
|
-
function buildExpectedResultParamDescription() {
|
|
853
|
-
return EXPECTED_RESULT_PARAM_DESCRIPTION;
|
|
921
|
+
function buildExpectedResultParamDescription(options = {}) {
|
|
922
|
+
return options.intentParamMode === "required" ? EXPECTED_RESULT_PARAM_DESCRIPTION_REQUIRED : EXPECTED_RESULT_PARAM_DESCRIPTION;
|
|
923
|
+
}
|
|
924
|
+
function requiredParamNames(intentParamMode) {
|
|
925
|
+
return intentParamMode === "required" ? [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME] : [];
|
|
854
926
|
}
|
|
855
927
|
|
|
856
928
|
// src/integrations/mcp/annotationName.ts
|
|
@@ -992,6 +1064,9 @@ function extraHeaders(extra) {
|
|
|
992
1064
|
}
|
|
993
1065
|
return null;
|
|
994
1066
|
}
|
|
1067
|
+
function isThenable(value) {
|
|
1068
|
+
return typeof value?.then === "function";
|
|
1069
|
+
}
|
|
995
1070
|
|
|
996
1071
|
// src/integrations/mcp/principalResolution.ts
|
|
997
1072
|
function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
@@ -1003,6 +1078,26 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
|
1003
1078
|
authInfo: extraAuthInfo(extra)
|
|
1004
1079
|
};
|
|
1005
1080
|
}
|
|
1081
|
+
var HOOK_TIMEOUT_MS = 5e3;
|
|
1082
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
|
|
1083
|
+
async function withinHookBudget(answer) {
|
|
1084
|
+
if (!isThenable(answer)) return answer;
|
|
1085
|
+
let timer;
|
|
1086
|
+
const deadline = new Promise((resolve) => {
|
|
1087
|
+
timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
|
|
1088
|
+
timer.unref?.();
|
|
1089
|
+
});
|
|
1090
|
+
try {
|
|
1091
|
+
const first = await Promise.race([answer, deadline]);
|
|
1092
|
+
if (first !== TIMED_OUT) return first;
|
|
1093
|
+
warn(
|
|
1094
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1095
|
+
);
|
|
1096
|
+
return null;
|
|
1097
|
+
} finally {
|
|
1098
|
+
clearTimeout(timer);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1006
1101
|
var warnedPreRenameShape = false;
|
|
1007
1102
|
function warnIfPreRenameShape(result) {
|
|
1008
1103
|
const userId = result?.userId;
|
|
@@ -1016,7 +1111,7 @@ async function resolveCallPrincipal(hook, call) {
|
|
|
1016
1111
|
if (hook === void 0) return null;
|
|
1017
1112
|
try {
|
|
1018
1113
|
const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
|
|
1019
|
-
const result = await hook(context);
|
|
1114
|
+
const result = await withinHookBudget(hook(context));
|
|
1020
1115
|
const principal = normalizePrincipal(result);
|
|
1021
1116
|
if (principal === null) {
|
|
1022
1117
|
warnIfPreRenameShape(result);
|
|
@@ -1053,56 +1148,67 @@ function scrubOrNull(scrubber, value, field) {
|
|
|
1053
1148
|
}
|
|
1054
1149
|
}
|
|
1055
1150
|
|
|
1056
|
-
// src/integrations/mcp/
|
|
1151
|
+
// src/integrations/mcp/clientObserved.ts
|
|
1057
1152
|
var CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo";
|
|
1058
|
-
var
|
|
1059
|
-
var
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
if (
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
function declaredOnRequest(meta, envelope) {
|
|
1072
|
-
for (const source of [envelope, meta]) {
|
|
1073
|
-
if (!source) continue;
|
|
1074
|
-
const info = source[CLIENT_INFO_META_KEY];
|
|
1075
|
-
if (info && typeof info === "object") {
|
|
1076
|
-
const name = info.name;
|
|
1077
|
-
if (name !== void 0) return name;
|
|
1078
|
-
}
|
|
1153
|
+
var OBSERVED_HEADERS = ["user-agent", "x-anthropic-client"];
|
|
1154
|
+
var CLIENT_INFO_MAX_LEN = 128;
|
|
1155
|
+
var HEADER_VALUE_MAX_LEN = 256;
|
|
1156
|
+
var hasText = (value) => typeof value === "string" && value !== "";
|
|
1157
|
+
function declared(info) {
|
|
1158
|
+
if (!info || typeof info !== "object") return void 0;
|
|
1159
|
+
const { name, version } = info;
|
|
1160
|
+
return hasText(name) || hasText(version) ? { name, version } : void 0;
|
|
1161
|
+
}
|
|
1162
|
+
function declaredOnRequest(extra) {
|
|
1163
|
+
for (const source of [extraEnvelope(extra), extraMeta(extra)]) {
|
|
1164
|
+
const found = declared(source?.[CLIENT_INFO_META_KEY]);
|
|
1165
|
+
if (found) return found;
|
|
1079
1166
|
}
|
|
1080
1167
|
return void 0;
|
|
1081
1168
|
}
|
|
1082
|
-
function declaredOnConnection(
|
|
1169
|
+
function declaredOnConnection(server) {
|
|
1170
|
+
if (!server) return void 0;
|
|
1171
|
+
const inner = server.server;
|
|
1172
|
+
const holder = inner ?? server;
|
|
1173
|
+
if (typeof holder.getClientVersion !== "function") return void 0;
|
|
1174
|
+
return declared(holder.getClientVersion());
|
|
1175
|
+
}
|
|
1176
|
+
function observedInfo(extra, options) {
|
|
1177
|
+
const sent = declaredOnRequest(extra) ?? declaredOnConnection(options.server);
|
|
1178
|
+
const info = {};
|
|
1179
|
+
const name = clean(sent?.name, options.scrubber, CLIENT_INFO_MAX_LEN);
|
|
1180
|
+
const version = clean(sent?.version, options.scrubber, CLIENT_INFO_MAX_LEN);
|
|
1181
|
+
if (name !== void 0) info.name = name;
|
|
1182
|
+
if (version !== void 0) info.version = version;
|
|
1183
|
+
return Object.keys(info).length > 0 ? info : void 0;
|
|
1184
|
+
}
|
|
1185
|
+
function observedHeaders(extra, options) {
|
|
1186
|
+
const sent = extraHeaders(extra);
|
|
1187
|
+
const headers = {};
|
|
1188
|
+
for (const header of OBSERVED_HEADERS) {
|
|
1189
|
+
const value = clean(sent?.get(header), options.scrubber, HEADER_VALUE_MAX_LEN);
|
|
1190
|
+
if (value !== void 0) headers[header] = value;
|
|
1191
|
+
}
|
|
1192
|
+
return Object.keys(headers).length > 0 ? headers : void 0;
|
|
1193
|
+
}
|
|
1194
|
+
function clean(value, scrubber, max) {
|
|
1195
|
+
if (!hasText(value)) return void 0;
|
|
1196
|
+
const scrubbed = scrubOrNull(scrubber, value, "client_observed");
|
|
1197
|
+
if (!hasText(scrubbed)) return void 0;
|
|
1198
|
+
return capCodePoints(scrubbed, max);
|
|
1199
|
+
}
|
|
1200
|
+
function orNothing(read) {
|
|
1083
1201
|
try {
|
|
1084
|
-
|
|
1085
|
-
if (!server) return void 0;
|
|
1086
|
-
const inner = server.server;
|
|
1087
|
-
const holder = inner ?? server;
|
|
1088
|
-
if (typeof holder.getClientVersion !== "function") return void 0;
|
|
1089
|
-
return holder.getClientVersion()?.name;
|
|
1202
|
+
return read();
|
|
1090
1203
|
} catch {
|
|
1091
1204
|
return void 0;
|
|
1092
1205
|
}
|
|
1093
1206
|
}
|
|
1094
|
-
function
|
|
1095
|
-
const
|
|
1096
|
-
const
|
|
1097
|
-
if (
|
|
1098
|
-
|
|
1099
|
-
if (onConnection !== null) return onConnection;
|
|
1100
|
-
if (meta) {
|
|
1101
|
-
for (const key of Object.keys(meta)) {
|
|
1102
|
-
if (key.startsWith("claudecode/")) return "claude-code";
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
return null;
|
|
1207
|
+
function observeClient(extra, options) {
|
|
1208
|
+
const info = orNothing(() => observedInfo(extra, options));
|
|
1209
|
+
const headers = orNothing(() => observedHeaders(extra, options));
|
|
1210
|
+
if (info === void 0 && headers === void 0) return null;
|
|
1211
|
+
return { ...info && { info }, ...headers && { headers } };
|
|
1106
1212
|
}
|
|
1107
1213
|
|
|
1108
1214
|
// src/integrations/mcp/sessionResolution.ts
|
|
@@ -1112,6 +1218,10 @@ async function resolveSessionId(fallbackSessionId, extra) {
|
|
|
1112
1218
|
}
|
|
1113
1219
|
|
|
1114
1220
|
// src/integrations/mcp/annotation.ts
|
|
1221
|
+
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
1222
|
+
function isReport(whatHappened) {
|
|
1223
|
+
return typeof whatHappened === "string" && whatHappened.trim() !== "";
|
|
1224
|
+
}
|
|
1115
1225
|
function registerAnnotationTool(server, options) {
|
|
1116
1226
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
1117
1227
|
const description = buildAnnotationToolDescription({
|
|
@@ -1124,28 +1234,38 @@ function registerAnnotationTool(server, options) {
|
|
|
1124
1234
|
inputSchema: {
|
|
1125
1235
|
user_goal: import_zod2.z.string(),
|
|
1126
1236
|
expected_result: import_zod2.z.string().optional(),
|
|
1127
|
-
|
|
1237
|
+
what_happened: import_zod2.z.string().optional(),
|
|
1238
|
+
// Nullable so a report whose agent sends an explicit null is taken,
|
|
1239
|
+
// not rejected by validation.
|
|
1240
|
+
tool_name: import_zod2.z.string().nullable().optional(),
|
|
1128
1241
|
overall_task: import_zod2.z.string().optional(),
|
|
1129
1242
|
suggested_improvement: import_zod2.z.string().optional(),
|
|
1130
1243
|
context: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional()
|
|
1131
1244
|
}
|
|
1132
1245
|
},
|
|
1133
1246
|
async (args, extra) => {
|
|
1247
|
+
const whatHappened = args.what_happened;
|
|
1248
|
+
if (!isReport(whatHappened)) {
|
|
1249
|
+
return {
|
|
1250
|
+
content: [
|
|
1251
|
+
{
|
|
1252
|
+
type: "text",
|
|
1253
|
+
text: JSON.stringify({
|
|
1254
|
+
ok: false,
|
|
1255
|
+
error: `${name} is reactive-only on this server. Call it only AFTER a tool call returns an unhelpful, empty, failed or contradictory result, or when no tool covers what the user asked for. What the user is trying to do is already recorded on each tool call, so no pre-call annotation is needed \u2014 nothing was lost. If a tool call really went wrong, or no tool covers the request, call this again and say what_happened. If neither is true, do NOT re-send: that would file a report for a call that did not go wrong.`
|
|
1256
|
+
})
|
|
1257
|
+
}
|
|
1258
|
+
]
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
const reportedTool = args.tool_name ?? null;
|
|
1134
1262
|
const meta = extraMeta(extra);
|
|
1135
|
-
const runtime = detectAgentRuntime(meta, {
|
|
1136
|
-
envelope: extraEnvelope(extra),
|
|
1137
|
-
server,
|
|
1138
|
-
scrubber: options.scrubber
|
|
1139
|
-
}) ?? UNKNOWN_AGENT_RUNTIME;
|
|
1140
1263
|
const scrubbedMeta = scrubOrNull(
|
|
1141
1264
|
options.scrubber,
|
|
1142
1265
|
meta ? roundMetaCoordinates(meta) : null,
|
|
1143
1266
|
"_meta"
|
|
1144
1267
|
);
|
|
1145
1268
|
const sessionId = await resolveSessionId(options.fallbackSessionId, extra);
|
|
1146
|
-
if (args.signal_type === void 0) {
|
|
1147
|
-
options.tracker?.mark(sessionId);
|
|
1148
|
-
}
|
|
1149
1269
|
const principal = await resolveCallPrincipal(
|
|
1150
1270
|
options.resolvePrincipal,
|
|
1151
1271
|
{ extra, toolName: name, arguments: args }
|
|
@@ -1159,9 +1279,9 @@ function registerAnnotationTool(server, options) {
|
|
|
1159
1279
|
sequence_number: options.counter.next(sessionId),
|
|
1160
1280
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1161
1281
|
consent_token: options.consentToken,
|
|
1162
|
-
agent_runtime: runtime,
|
|
1163
1282
|
principal,
|
|
1164
1283
|
transport_observed: observeTransport(extra),
|
|
1284
|
+
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1165
1285
|
runtime_meta: scrubbedMeta,
|
|
1166
1286
|
payload: {
|
|
1167
1287
|
// Agent-facing names -> wire keys, as with `overall_task`
|
|
@@ -1170,15 +1290,10 @@ function registerAnnotationTool(server, options) {
|
|
|
1170
1290
|
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1171
1291
|
intent: options.scrubber(args.user_goal),
|
|
1172
1292
|
expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
|
|
1173
|
-
//
|
|
1174
|
-
|
|
1175
|
-
//
|
|
1176
|
-
|
|
1177
|
-
// gap found 2026-08-11, fixed here and flagged for the sibling
|
|
1178
|
-
// rather than mirrored. Not a wire divergence: scrubbing changes
|
|
1179
|
-
// content, not shape, and it's deterministic, so the
|
|
1180
|
-
// exact-string continuity rung 3b groups on survives.
|
|
1181
|
-
signal_type: args.signal_type ?? null,
|
|
1293
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1294
|
+
what_happened: options.scrubber(whatHappened),
|
|
1295
|
+
// eslint-disable-next-line no-restricted-syntax -- inside the emit() build thunk: a throw is already contained, and null here would fabricate a shape
|
|
1296
|
+
tool_name: reportedTool ? options.scrubber(reportedTool) : reportedTool,
|
|
1182
1297
|
// Agent-facing param `overall_task` -> wire key `workflow`, the same
|
|
1183
1298
|
// split the injected params use (`overall_task` -> `call_workflow`):
|
|
1184
1299
|
// renaming the param must not move the key the console groups on.
|
|
@@ -1468,7 +1583,7 @@ function resolveTenantId(explicit, vendorId) {
|
|
|
1468
1583
|
if (fromEnv) return fromEnv;
|
|
1469
1584
|
return vendorId;
|
|
1470
1585
|
}
|
|
1471
|
-
function resolveBatonConfig(config
|
|
1586
|
+
function resolveBatonConfig(config) {
|
|
1472
1587
|
const dsnString = selectDsn(
|
|
1473
1588
|
config.dsn,
|
|
1474
1589
|
{
|
|
@@ -1504,14 +1619,7 @@ function resolveBatonConfig(config, serverName) {
|
|
|
1504
1619
|
// in the server instructions and the annotation tool description, which is
|
|
1505
1620
|
// the whitelabel obligation the validator cites when it refuses the empty
|
|
1506
1621
|
// one. ⚠ Python uses `or` here and still has the inconsistency.
|
|
1507
|
-
|
|
1508
|
-
// Between the explicit value and the segment sits the server's own name,
|
|
1509
|
-
// under the guards in `annotationName.ts`: the segment is an opaque
|
|
1510
|
-
// `srv-<8 hex>`, and it was what agents were told the vendor is called.
|
|
1511
|
-
vendorDisplayName: config.vendorDisplayName ?? displayNameFromServer(serverName, {
|
|
1512
|
-
vendorId: dsn.vendorId,
|
|
1513
|
-
annotationToolName: config.annotationToolName
|
|
1514
|
-
}) ?? dsn.vendorId,
|
|
1622
|
+
vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
|
|
1515
1623
|
// `??`, not `||`: an explicit empty string must survive to the validation
|
|
1516
1624
|
// below and be REFUSED there, rather than be quietly replaced by the
|
|
1517
1625
|
// default it was deliberately not left as.
|
|
@@ -1525,6 +1633,14 @@ function resolveBatonConfig(config, serverName) {
|
|
|
1525
1633
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
|
|
1526
1634
|
};
|
|
1527
1635
|
}
|
|
1636
|
+
function withServerDisplayName(resolved, supplied, serverName) {
|
|
1637
|
+
if (supplied.vendorDisplayName !== void 0) return resolved;
|
|
1638
|
+
const fromServer = displayNameFromServer(serverName, {
|
|
1639
|
+
vendorId: resolved.vendorId,
|
|
1640
|
+
annotationToolName: supplied.annotationToolName
|
|
1641
|
+
});
|
|
1642
|
+
return fromServer === void 0 ? resolved : { ...resolved, vendorDisplayName: fromServer };
|
|
1643
|
+
}
|
|
1528
1644
|
var RENAMED_KEYS = {
|
|
1529
1645
|
resolveUser: "resolvePrincipal"
|
|
1530
1646
|
};
|
|
@@ -1647,11 +1763,6 @@ var ProactiveTracker = class {
|
|
|
1647
1763
|
this.emitted.add(sessionId);
|
|
1648
1764
|
return true;
|
|
1649
1765
|
}
|
|
1650
|
-
/** Mark the slot claimed without emitting here (the annotation tool's own
|
|
1651
|
-
* handler already emitted the annotation event itself). */
|
|
1652
|
-
mark(sessionId) {
|
|
1653
|
-
this.emitted.add(sessionId);
|
|
1654
|
-
}
|
|
1655
1766
|
};
|
|
1656
1767
|
|
|
1657
1768
|
// src/integrations/mcp/sessionCounter.ts
|
|
@@ -1761,13 +1872,8 @@ function injectGoalParams(inputSchema, intentParamMode) {
|
|
|
1761
1872
|
function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
1762
1873
|
const dispositions = {};
|
|
1763
1874
|
const toInject = {};
|
|
1764
|
-
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
1765
|
-
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
1766
|
-
} else {
|
|
1767
|
-
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
1768
|
-
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription({ intentParamMode }));
|
|
1769
|
-
}
|
|
1770
1875
|
for (const [name, buildDescription] of [
|
|
1876
|
+
[USER_GOAL_PARAM_NAME, buildUserGoalParamDescription],
|
|
1771
1877
|
[EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
|
|
1772
1878
|
[OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
|
|
1773
1879
|
]) {
|
|
@@ -1775,7 +1881,7 @@ function buildIntentFields(existingShape, zodImpl, intentParamMode) {
|
|
|
1775
1881
|
dispositions[name] = "native";
|
|
1776
1882
|
} else {
|
|
1777
1883
|
dispositions[name] = "injected";
|
|
1778
|
-
toInject[name] = zodImpl.string().optional().describe(buildDescription());
|
|
1884
|
+
toInject[name] = zodImpl.string().optional().describe(buildDescription({ intentParamMode }));
|
|
1779
1885
|
}
|
|
1780
1886
|
}
|
|
1781
1887
|
return { dispositions, toInject };
|
|
@@ -1791,21 +1897,23 @@ function injectGoalParamsV2(inputSchema, intentParamMode) {
|
|
|
1791
1897
|
return { schema: inputSchema, dispositions };
|
|
1792
1898
|
return { schema: candidate.extend(toInject), dispositions };
|
|
1793
1899
|
}
|
|
1794
|
-
function
|
|
1900
|
+
function advertiseIntentParamsRequired(result, names, isInjected) {
|
|
1795
1901
|
const tools = result?.tools;
|
|
1796
1902
|
if (!Array.isArray(tools)) return result;
|
|
1797
1903
|
let changed = false;
|
|
1798
1904
|
const advertised = tools.map((tool) => {
|
|
1799
1905
|
const entry = tool;
|
|
1800
|
-
|
|
1801
|
-
|
|
1906
|
+
const toolName = entry?.name;
|
|
1907
|
+
if (typeof toolName !== "string") return tool;
|
|
1908
|
+
const schema = entry?.inputSchema;
|
|
1802
1909
|
if (!schema || typeof schema !== "object") return tool;
|
|
1803
|
-
const
|
|
1804
|
-
if (!Array.isArray(
|
|
1805
|
-
const required =
|
|
1806
|
-
|
|
1910
|
+
const declared2 = schema.required ?? [];
|
|
1911
|
+
if (!Array.isArray(declared2)) return tool;
|
|
1912
|
+
const required = declared2;
|
|
1913
|
+
const missing = names.filter((name) => isInjected(toolName, name) && !required.includes(name));
|
|
1914
|
+
if (missing.length === 0) return tool;
|
|
1807
1915
|
changed = true;
|
|
1808
|
-
return { ...entry, inputSchema: { ...schema, required: [...required,
|
|
1916
|
+
return { ...entry, inputSchema: { ...schema, required: [...required, ...missing] } };
|
|
1809
1917
|
});
|
|
1810
1918
|
return changed ? { ...result, tools: advertised } : result;
|
|
1811
1919
|
}
|
|
@@ -1819,10 +1927,10 @@ function toolInputJsonSchema(inputSchema) {
|
|
|
1819
1927
|
}
|
|
1820
1928
|
|
|
1821
1929
|
// src/integrations/mcp/surface.ts
|
|
1822
|
-
var
|
|
1930
|
+
var import_node_crypto2 = require("crypto");
|
|
1823
1931
|
function surfaceHash(surface) {
|
|
1824
1932
|
const canonical = canonicalJson(surface);
|
|
1825
|
-
const digest = (0,
|
|
1933
|
+
const digest = (0, import_node_crypto2.createHash)("sha256").update(canonical, "utf-8").digest("hex");
|
|
1826
1934
|
return `sha256:${digest}`;
|
|
1827
1935
|
}
|
|
1828
1936
|
function canonicalJson(value) {
|
|
@@ -1854,7 +1962,11 @@ function assembleSurface(serverMeta, tools) {
|
|
|
1854
1962
|
function buildSeamAugmentations(options) {
|
|
1855
1963
|
return {
|
|
1856
1964
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
1857
|
-
intent_param: options.intentParamMode !== "off" ? {
|
|
1965
|
+
intent_param: options.intentParamMode !== "off" ? {
|
|
1966
|
+
names: [...options.intentParamNames].sort(),
|
|
1967
|
+
required_names: [...options.requiredParamNames].sort(),
|
|
1968
|
+
mode: options.intentParamMode
|
|
1969
|
+
} : null,
|
|
1858
1970
|
instructions_suffix: true
|
|
1859
1971
|
};
|
|
1860
1972
|
}
|
|
@@ -1865,16 +1977,17 @@ var wired = /* @__PURE__ */ new WeakSet();
|
|
|
1865
1977
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
1866
1978
|
var callSlots = new import_node_async_hooks.AsyncLocalStorage();
|
|
1867
1979
|
var SurfaceState = class {
|
|
1868
|
-
constructor(serverMeta) {
|
|
1980
|
+
constructor(serverMeta, emittedHashes) {
|
|
1869
1981
|
this.serverMeta = serverMeta;
|
|
1982
|
+
this.emittedHashes = emittedHashes;
|
|
1870
1983
|
}
|
|
1871
1984
|
serverMeta;
|
|
1985
|
+
emittedHashes;
|
|
1872
1986
|
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
1873
1987
|
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
1874
1988
|
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
1875
1989
|
* injected schema as if it were vendor-true. */
|
|
1876
1990
|
rawTools = /* @__PURE__ */ new Map();
|
|
1877
|
-
emittedHashes = /* @__PURE__ */ new Set();
|
|
1878
1991
|
dirty = false;
|
|
1879
1992
|
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
1880
1993
|
* which picks the spelling THIS SDK major puts on the wire. */
|
|
@@ -1926,23 +2039,13 @@ function messageOf(err) {
|
|
|
1926
2039
|
}
|
|
1927
2040
|
async function resolveEnvelopeParts(ctx, extra) {
|
|
1928
2041
|
const meta = extraMeta(extra);
|
|
1929
|
-
const runtime = detectAgentRuntime(meta, {
|
|
1930
|
-
// v2 lifts the reserved `io.modelcontextprotocol/*` keys out of
|
|
1931
|
-
// `_meta`; 1.x leaves them in. Both are handed over — see
|
|
1932
|
-
// `mcpTypes.extraEnvelope`.
|
|
1933
|
-
envelope: extraEnvelope(extra),
|
|
1934
|
-
// Tier 2's carrier: neither peer puts client identity on the
|
|
1935
|
-
// handler context, both expose the cached handshake on the server.
|
|
1936
|
-
server: ctx.server,
|
|
1937
|
-
scrubber: ctx.scrubber
|
|
1938
|
-
}) ?? UNKNOWN_AGENT_RUNTIME;
|
|
1939
2042
|
const scrubbedMeta = scrubOrNull(ctx.scrubber, meta ? roundMetaCoordinates(meta) : null, "_meta");
|
|
1940
2043
|
const sessionId = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
1941
|
-
return { sessionId,
|
|
2044
|
+
return { sessionId, scrubbedMeta };
|
|
1942
2045
|
}
|
|
1943
2046
|
async function openCall(ctx, toolName, extra, params, registered = true) {
|
|
1944
2047
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
1945
|
-
const { sessionId,
|
|
2048
|
+
const { sessionId, scrubbedMeta } = await resolveEnvelopeParts(ctx, extra);
|
|
1946
2049
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
1947
2050
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
1948
2051
|
const rawExpected = extractGoalParam(
|
|
@@ -1956,7 +2059,7 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
|
|
|
1956
2059
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
1957
2060
|
const scrubbedExpected = scrubOrNull(ctx.scrubber, rawExpected, EXPECTED_RESULT_PARAM_NAME);
|
|
1958
2061
|
const scrubbedWorkflow = scrubOrNull(ctx.scrubber, rawWorkflow, OVERALL_TASK_PARAM_NAME);
|
|
1959
|
-
const callId = (
|
|
2062
|
+
const callId = uuid7();
|
|
1960
2063
|
const principal = await resolveCallPrincipal(
|
|
1961
2064
|
ctx.resolvePrincipal,
|
|
1962
2065
|
{ extra, toolName, arguments: params }
|
|
@@ -1966,19 +2069,12 @@ async function openCall(ctx, toolName, extra, params, registered = true) {
|
|
|
1966
2069
|
vendor_id: ctx.vendorId,
|
|
1967
2070
|
session_id: sessionId,
|
|
1968
2071
|
consent_token: ctx.consentToken,
|
|
1969
|
-
|
|
1970
|
-
//
|
|
1971
|
-
//
|
|
1972
|
-
// annotation, the same five Python stamps (`middleware.py`
|
|
1973
|
-
// 503/547/586/644/674; it was four until the returned shape landed
|
|
1974
|
-
// there too). `surface_snapshot` is deliberately NOT among them: it
|
|
1975
|
-
// describes the SERVER and is captured outside any call, so there is no
|
|
1976
|
-
// caller to name (register D5).
|
|
2072
|
+
// Every `...common` site is an event with a caller. `surface_snapshot`
|
|
2073
|
+
// is deliberately not among them: it describes the SERVER and is captured
|
|
2074
|
+
// outside any call, so it has no caller, transport or client to name.
|
|
1977
2075
|
principal,
|
|
1978
|
-
// Same five stamps, same exclusion: a surface_snapshot describes the
|
|
1979
|
-
// SERVER and is captured outside any call, so it has no caller's
|
|
1980
|
-
// transport to name any more than it has a caller to name.
|
|
1981
2076
|
transport_observed: observeTransport(extra),
|
|
2077
|
+
client_observed: observeClient(extra, ctx),
|
|
1982
2078
|
runtime_meta: scrubbedMeta
|
|
1983
2079
|
};
|
|
1984
2080
|
if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
|
|
@@ -2200,6 +2296,7 @@ function extractGoalParam(args, paramName, toolName, dispositions, registered) {
|
|
|
2200
2296
|
delete args[paramName];
|
|
2201
2297
|
return typeof raw === "string" && raw.trim() ? raw : null;
|
|
2202
2298
|
}
|
|
2299
|
+
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2203
2300
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2204
2301
|
if (!ctx.surfaceState.dirty) return;
|
|
2205
2302
|
ctx.surfaceState.dirty = false;
|
|
@@ -2213,21 +2310,24 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2213
2310
|
`);
|
|
2214
2311
|
return;
|
|
2215
2312
|
}
|
|
2216
|
-
|
|
2313
|
+
const emitted = ctx.surfaceState.emittedHashes;
|
|
2314
|
+
if (emitted.has(digest)) return;
|
|
2315
|
+
if (emitted.size >= MAX_REMEMBERED_SURFACES) emitted.clear();
|
|
2316
|
+
emitted.add(digest);
|
|
2217
2317
|
const seam = buildSeamAugmentations({
|
|
2218
2318
|
injectedToolNames: [ctx.annotationToolName],
|
|
2219
2319
|
intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
|
|
2220
|
-
intentParamMode: ctx.intentParamMode
|
|
2320
|
+
intentParamMode: ctx.intentParamMode,
|
|
2321
|
+
requiredParamNames: requiredParamNames(ctx.intentParamMode)
|
|
2221
2322
|
});
|
|
2222
2323
|
try {
|
|
2223
2324
|
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
2224
2325
|
} catch (err) {
|
|
2225
2326
|
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
2226
2327
|
`);
|
|
2328
|
+
emitted.delete(digest);
|
|
2227
2329
|
ctx.surfaceState.dirty = true;
|
|
2228
|
-
return;
|
|
2229
2330
|
}
|
|
2230
|
-
ctx.surfaceState.emittedHashes.add(digest);
|
|
2231
2331
|
}
|
|
2232
2332
|
function captureAndInject(name, entry, ctx) {
|
|
2233
2333
|
if (!entry || typeof entry !== "object") return;
|
|
@@ -2241,6 +2341,7 @@ function captureAndInject(name, entry, ctx) {
|
|
|
2241
2341
|
mutable.inputSchema = schema;
|
|
2242
2342
|
ctx.bustSchemaMemo(name);
|
|
2243
2343
|
ctx.paramRegistry.set(name, dispositions);
|
|
2344
|
+
if (dispositions[OVERALL_TASK_PARAM_NAME] === "native") ctx.dropSubagentClause(name);
|
|
2244
2345
|
} else {
|
|
2245
2346
|
ctx.paramRegistry.delete(name);
|
|
2246
2347
|
}
|
|
@@ -2261,6 +2362,7 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
|
|
|
2261
2362
|
const handler = handlers.get(method);
|
|
2262
2363
|
if (typeof handler !== "function" || handler[seamTag]) return;
|
|
2263
2364
|
const seamed = wrap(handler);
|
|
2365
|
+
for (const tag of Object.getOwnPropertySymbols(handler)) seamed[tag] = handler[tag];
|
|
2264
2366
|
seamed[seamTag] = true;
|
|
2265
2367
|
handlers.set(method, seamed);
|
|
2266
2368
|
};
|
|
@@ -2272,10 +2374,11 @@ function installRequestSeam(lowLevel, method, seamTag, wrap) {
|
|
|
2272
2374
|
};
|
|
2273
2375
|
}
|
|
2274
2376
|
function installToolsListSeam(lowLevel, ctx) {
|
|
2275
|
-
const
|
|
2377
|
+
const names = [...requiredParamNames(ctx.intentParamMode), TOOL_NAME_PARAM_NAME];
|
|
2378
|
+
const isInjected = (toolName, paramName) => toolName === ctx.annotationToolName ? paramName === TOOL_NAME_PARAM_NAME : ctx.paramRegistry.get(toolName)?.[paramName] === "injected";
|
|
2276
2379
|
const advertise = (result) => {
|
|
2277
2380
|
try {
|
|
2278
|
-
return
|
|
2381
|
+
return advertiseIntentParamsRequired(result, names, isInjected);
|
|
2279
2382
|
} catch (err) {
|
|
2280
2383
|
process.stderr.write(
|
|
2281
2384
|
`baton: tools/list advertisement failed; serving the SDK's own result: ${String(err)}
|
|
@@ -2293,7 +2396,8 @@ var LIFECYCLE_SEAMS = {
|
|
|
2293
2396
|
resourceList: /* @__PURE__ */ Symbol("batonResourceListSeam"),
|
|
2294
2397
|
resourceRead: /* @__PURE__ */ Symbol("batonResourceReadSeam"),
|
|
2295
2398
|
promptList: /* @__PURE__ */ Symbol("batonPromptListSeam"),
|
|
2296
|
-
promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam")
|
|
2399
|
+
promptGet: /* @__PURE__ */ Symbol("batonPromptGetSeam"),
|
|
2400
|
+
toolList: /* @__PURE__ */ Symbol("batonToolListSeam")
|
|
2297
2401
|
};
|
|
2298
2402
|
function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
2299
2403
|
installRequestSeam(lowLevel, spec.method, spec.seamTag, (handler) => async (...args) => {
|
|
@@ -2340,6 +2444,11 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2340
2444
|
async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
2341
2445
|
try {
|
|
2342
2446
|
const parts = await resolveEnvelopeParts(ctx, extra);
|
|
2447
|
+
const principal = await resolveCallPrincipal(ctx.resolvePrincipal, {
|
|
2448
|
+
extra,
|
|
2449
|
+
toolName: null,
|
|
2450
|
+
arguments: {}
|
|
2451
|
+
});
|
|
2343
2452
|
return {
|
|
2344
2453
|
sessionId: parts.sessionId,
|
|
2345
2454
|
subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
|
|
@@ -2348,8 +2457,9 @@ async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
|
2348
2457
|
vendor_id: ctx.vendorId,
|
|
2349
2458
|
session_id: parts.sessionId,
|
|
2350
2459
|
consent_token: ctx.consentToken,
|
|
2351
|
-
|
|
2460
|
+
principal,
|
|
2352
2461
|
transport_observed: observeTransport(extra),
|
|
2462
|
+
client_observed: observeClient(extra, ctx),
|
|
2353
2463
|
runtime_meta: parts.scrubbedMeta
|
|
2354
2464
|
}
|
|
2355
2465
|
};
|
|
@@ -2422,6 +2532,17 @@ var LIFECYCLE_SPECS = [
|
|
|
2422
2532
|
startParams: (params) => ({
|
|
2423
2533
|
params: paramsBag(params["arguments"])
|
|
2424
2534
|
})
|
|
2535
|
+
},
|
|
2536
|
+
{
|
|
2537
|
+
method: TOOLS_LIST_METHOD,
|
|
2538
|
+
seamTag: LIFECYCLE_SEAMS.toolList,
|
|
2539
|
+
schemas: {
|
|
2540
|
+
start: ToolListStartEventSchema,
|
|
2541
|
+
end: ToolListEndEventSchema,
|
|
2542
|
+
error: ToolListErrorEventSchema
|
|
2543
|
+
},
|
|
2544
|
+
countKey: "tools",
|
|
2545
|
+
startParams: NO_PARAMS
|
|
2425
2546
|
}
|
|
2426
2547
|
];
|
|
2427
2548
|
function installLifecycleSeams(lowLevel, ctx) {
|
|
@@ -2552,9 +2673,6 @@ async function emitRequestSideFailure(outcome, args, toolEntry, ctx) {
|
|
|
2552
2673
|
})
|
|
2553
2674
|
);
|
|
2554
2675
|
}
|
|
2555
|
-
function isThenable(value) {
|
|
2556
|
-
return typeof value?.then === "function";
|
|
2557
|
-
}
|
|
2558
2676
|
function wrapIfNeeded(nameRef, entry, ctx) {
|
|
2559
2677
|
if (!entry || typeof entry !== "object") return;
|
|
2560
2678
|
const mutable = entry;
|
|
@@ -2630,47 +2748,57 @@ function withBaton(server, supplied = {}) {
|
|
|
2630
2748
|
annotationToolName: ""
|
|
2631
2749
|
});
|
|
2632
2750
|
}
|
|
2751
|
+
return install(server, supplied, resolveBatonConfig(supplied), /* @__PURE__ */ new Set());
|
|
2752
|
+
}
|
|
2753
|
+
function createBaton(supplied = {}) {
|
|
2754
|
+
const disabledBy = captureDisabled();
|
|
2755
|
+
if (disabledBy !== null) {
|
|
2756
|
+
logDisabled(disabledBy, "createBaton");
|
|
2757
|
+
const unused = supplied.sink ?? new DisabledSink();
|
|
2758
|
+
return { wrap: () => {
|
|
2759
|
+
}, flush: () => unused.flush(), aclose: () => unused.aclose() };
|
|
2760
|
+
}
|
|
2761
|
+
const resolved = resolveBatonConfig(supplied);
|
|
2762
|
+
deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
|
|
2763
|
+
const sink = resolved.sink ?? new StdoutSink();
|
|
2764
|
+
const config = {
|
|
2765
|
+
...resolved,
|
|
2766
|
+
sink,
|
|
2767
|
+
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2768
|
+
};
|
|
2769
|
+
const emittedSurfaceHashes = /* @__PURE__ */ new Set();
|
|
2770
|
+
return {
|
|
2771
|
+
wrap: (server) => {
|
|
2772
|
+
install(server, supplied, config, emittedSurfaceHashes);
|
|
2773
|
+
},
|
|
2774
|
+
flush: () => sink.flush(),
|
|
2775
|
+
aclose: () => sink.aclose()
|
|
2776
|
+
};
|
|
2777
|
+
}
|
|
2778
|
+
function install(server, supplied, resolved, emittedSurfaceHashes) {
|
|
2633
2779
|
const internals = server;
|
|
2634
2780
|
const serverName = usableServerName(() => ({
|
|
2635
2781
|
name: internals.server._serverInfo?.name,
|
|
2636
2782
|
className: internals.constructor.name
|
|
2637
2783
|
}));
|
|
2638
|
-
const config =
|
|
2784
|
+
const config = withServerDisplayName(resolved, supplied, serverName);
|
|
2639
2785
|
const sink = config.sink ?? new StdoutSink();
|
|
2640
2786
|
const annotationToolName = resolveAnnotationToolName(serverName, config);
|
|
2641
2787
|
const intentParamMode = config.intentParamMode ?? "required";
|
|
2642
|
-
const
|
|
2643
|
-
const fallbackSessionId = `sdk-${(
|
|
2788
|
+
const counter2 = new SessionCounter();
|
|
2789
|
+
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
2644
2790
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
2645
2791
|
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
2646
2792
|
const serverMeta = buildServerMeta(server.server);
|
|
2647
|
-
const surfaceState = new SurfaceState(serverMeta);
|
|
2793
|
+
const surfaceState = new SurfaceState(serverMeta, emittedSurfaceHashes);
|
|
2648
2794
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
2649
2795
|
const event = SurfaceSnapshotEventSchema.parse({
|
|
2650
2796
|
tenant_id: tenantId,
|
|
2651
2797
|
vendor_id: config.vendorId,
|
|
2652
2798
|
session_id: sessionId,
|
|
2653
2799
|
consent_token: config.consentToken,
|
|
2654
|
-
sequence_number:
|
|
2800
|
+
sequence_number: counter2.next(sessionId),
|
|
2655
2801
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2656
|
-
// Deliberately the literal, NOT the ladder — and an earlier comment
|
|
2657
|
-
// here justified that by saying no call is in scope, which is false:
|
|
2658
|
-
// `maybeEmitSurfaceSnapshot` is the first line of `batonWrap`, so the
|
|
2659
|
-
// handshake has happened and tier 2's carrier is live in this closure.
|
|
2660
|
-
// The real reason is that the snapshot describes the VENDOR'S SURFACE,
|
|
2661
|
-
// which is the same whoever is calling. It is hashed and emitted at
|
|
2662
|
-
// most once per process per surface, so the client that happens to
|
|
2663
|
-
// trigger it is whichever one called first — attributing the surface to
|
|
2664
|
-
// that client would read as a fact about the surface and be an accident
|
|
2665
|
-
// of timing. Python hardcodes it from the same in-call position
|
|
2666
|
-
// (`_tool_wrap.py`), so this is parity, not a gap.
|
|
2667
|
-
//
|
|
2668
|
-
// ⚠ Consequence worth knowing: one session emits `surface_snapshot`
|
|
2669
|
-
// with `unknown` and everything else with the client's name, so a
|
|
2670
|
-
// consumer grouping on `agent_runtime` alone sees two runtimes for one
|
|
2671
|
-
// client. Intended; group surfaces on `(tenant_id, vendor_id,
|
|
2672
|
-
// surface_hash)`, which is what the Console's table is keyed on.
|
|
2673
|
-
agent_runtime: UNKNOWN_AGENT_RUNTIME,
|
|
2674
2802
|
payload: {
|
|
2675
2803
|
surface_hash: digest,
|
|
2676
2804
|
server_info: snapshot.server_info,
|
|
@@ -2686,6 +2814,15 @@ function withBaton(server, supplied = {}) {
|
|
|
2686
2814
|
const memo = internals._toolInputSchemaJson;
|
|
2687
2815
|
if (memo && typeof memo === "object") delete memo[name];
|
|
2688
2816
|
};
|
|
2817
|
+
const dropSubagentClause = (name) => {
|
|
2818
|
+
const current = internals.server._instructions;
|
|
2819
|
+
if (typeof current !== "string" || !current.includes(INSTRUCTIONS_SUBAGENT_CLAUSE)) return;
|
|
2820
|
+
internals.server._instructions = current.replace(INSTRUCTIONS_SUBAGENT_CLAUSE, "");
|
|
2821
|
+
process.stderr.write(
|
|
2822
|
+
`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
|
|
2823
|
+
`
|
|
2824
|
+
);
|
|
2825
|
+
};
|
|
2689
2826
|
const isV2Server = typeof internals.toolInputSchemaJson === "function";
|
|
2690
2827
|
const vendorToolJsonSchema = (name, inputSchema) => {
|
|
2691
2828
|
if (isV2Server) {
|
|
@@ -2710,7 +2847,7 @@ function withBaton(server, supplied = {}) {
|
|
|
2710
2847
|
const tracker = new ProactiveTracker();
|
|
2711
2848
|
const ctx = {
|
|
2712
2849
|
sink,
|
|
2713
|
-
counter,
|
|
2850
|
+
counter: counter2,
|
|
2714
2851
|
tenantId,
|
|
2715
2852
|
vendorId: config.vendorId,
|
|
2716
2853
|
consentToken: config.consentToken,
|
|
@@ -2724,16 +2861,18 @@ function withBaton(server, supplied = {}) {
|
|
|
2724
2861
|
resolvePrincipal: config.resolvePrincipal,
|
|
2725
2862
|
vendorToolJsonSchema,
|
|
2726
2863
|
bustSchemaMemo,
|
|
2864
|
+
dropSubagentClause,
|
|
2727
2865
|
tracker,
|
|
2728
2866
|
surfaceState,
|
|
2729
2867
|
emitSurface
|
|
2730
2868
|
};
|
|
2731
2869
|
const instructions = buildServerInstructions({
|
|
2732
2870
|
vendorDisplayName: config.vendorDisplayName,
|
|
2733
|
-
annotationToolName
|
|
2871
|
+
annotationToolName,
|
|
2872
|
+
intentParamMode
|
|
2734
2873
|
});
|
|
2735
2874
|
internals.server._instructions = instructions;
|
|
2736
|
-
|
|
2875
|
+
installToolsListSeam(internals.server, ctx);
|
|
2737
2876
|
installToolsCallSeam(
|
|
2738
2877
|
internals.server,
|
|
2739
2878
|
// ⚠ `Object.hasOwn`, never a bare index. `_registeredTools` is a plain
|
|
@@ -2763,8 +2902,7 @@ function withBaton(server, supplied = {}) {
|
|
|
2763
2902
|
// The RESOLVED name, never `config.annotationToolName`: handing over the
|
|
2764
2903
|
// raw override and letting the registration re-derive would register
|
|
2765
2904
|
// `srv-..._annotate` while the instructions name the server-derived one.
|
|
2766
|
-
annotationToolName
|
|
2767
|
-
tracker
|
|
2905
|
+
annotationToolName
|
|
2768
2906
|
});
|
|
2769
2907
|
const existing = internals._registeredTools;
|
|
2770
2908
|
if (existing) {
|
|
@@ -2865,6 +3003,13 @@ function principalFromOAuthEmail(context) {
|
|
|
2865
3003
|
ToolCallErrorPayloadSchema,
|
|
2866
3004
|
ToolCallStartEventSchema,
|
|
2867
3005
|
ToolCallStartPayloadSchema,
|
|
3006
|
+
ToolListEndEventSchema,
|
|
3007
|
+
ToolListEndPayloadSchema,
|
|
3008
|
+
ToolListErrorEventSchema,
|
|
3009
|
+
ToolListErrorPayloadSchema,
|
|
3010
|
+
ToolListStartEventSchema,
|
|
3011
|
+
ToolListStartPayloadSchema,
|
|
3012
|
+
createBaton,
|
|
2868
3013
|
identityScrub,
|
|
2869
3014
|
principalFromOAuthEmail,
|
|
2870
3015
|
principalFromOAuthSub,
|