@goodtiming/baton-sdk 0.1.0
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/LICENSE +201 -0
- package/README.md +82 -0
- package/dist/index.cjs +1304 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +685 -0
- package/dist/index.d.ts +685 -0
- package/dist/index.js +1247 -0
- package/dist/index.js.map +1 -0
- package/package.json +69 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1247 @@
|
|
|
1
|
+
// src/version.ts
|
|
2
|
+
var SDK_VERSION = "ts-0.1.0";
|
|
3
|
+
|
|
4
|
+
// src/events.ts
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { v7 as uuidv7 } from "uuid";
|
|
7
|
+
var ToolCallStartPayloadSchema = z.object({
|
|
8
|
+
tool_name: z.string(),
|
|
9
|
+
params: z.record(z.string(), z.unknown()).default({}),
|
|
10
|
+
call_intent: z.string().nullable().default(null),
|
|
11
|
+
call_expected: z.string().nullable().default(null),
|
|
12
|
+
call_workflow: z.string().nullable().default(null),
|
|
13
|
+
intent_source: z.string().nullable().default(null)
|
|
14
|
+
}).strict();
|
|
15
|
+
var ToolCallEndPayloadSchema = z.object({
|
|
16
|
+
tool_name: z.string(),
|
|
17
|
+
result: z.unknown().nullable().default(null),
|
|
18
|
+
duration_ms: z.number().int().nullable().default(null)
|
|
19
|
+
}).strict();
|
|
20
|
+
var ToolCallErrorPayloadSchema = z.object({
|
|
21
|
+
tool_name: z.string(),
|
|
22
|
+
error_type: z.string(),
|
|
23
|
+
error_body: z.string(),
|
|
24
|
+
duration_ms: z.number().int().nullable().default(null)
|
|
25
|
+
}).strict();
|
|
26
|
+
var AnnotationPayloadSchema = z.object({
|
|
27
|
+
intent: z.string().nullable().default(null),
|
|
28
|
+
expected_outcome: z.string().nullable().default(null),
|
|
29
|
+
signal_type: z.string().nullable().default(null),
|
|
30
|
+
workflow: z.string().nullable().default(null),
|
|
31
|
+
suggested_improvement: z.string().nullable().default(null),
|
|
32
|
+
context: z.record(z.string(), z.unknown()).nullable().default(null),
|
|
33
|
+
intent_source: z.string().nullable().default(null),
|
|
34
|
+
tool_name: z.string().nullable().default(null)
|
|
35
|
+
}).strict();
|
|
36
|
+
var SurfaceSnapshotPayloadSchema = z.object({
|
|
37
|
+
surface_hash: z.string(),
|
|
38
|
+
server_info: z.record(z.string(), z.unknown()).nullable().default(null),
|
|
39
|
+
capabilities: z.record(z.string(), z.unknown()).nullable().default(null),
|
|
40
|
+
instructions: z.string().nullable().default(null),
|
|
41
|
+
tools: z.array(z.record(z.string(), z.unknown())).default([]),
|
|
42
|
+
seam_augmentations: z.record(z.string(), z.unknown()).default({})
|
|
43
|
+
}).strict();
|
|
44
|
+
var envelopeShape = {
|
|
45
|
+
event_id: z.uuid().default(() => uuidv7()),
|
|
46
|
+
tenant_id: z.string(),
|
|
47
|
+
vendor_id: z.string(),
|
|
48
|
+
session_id: z.string(),
|
|
49
|
+
sequence_number: z.number().int().nonnegative(),
|
|
50
|
+
captured_at: z.string(),
|
|
51
|
+
consent_token: z.string(),
|
|
52
|
+
sdk_version: z.string().default(SDK_VERSION),
|
|
53
|
+
agent_runtime: z.string().default("unknown"),
|
|
54
|
+
user_id: z.string().nullable().default(null),
|
|
55
|
+
runtime_meta: z.record(z.string(), z.unknown()).nullable().default(null)
|
|
56
|
+
};
|
|
57
|
+
var EventTypeSchema = z.enum([
|
|
58
|
+
"tool_call_start",
|
|
59
|
+
"tool_call_end",
|
|
60
|
+
"tool_call_error",
|
|
61
|
+
"annotation",
|
|
62
|
+
"surface_snapshot"
|
|
63
|
+
]);
|
|
64
|
+
var ToolCallStartEventSchema = z.object({
|
|
65
|
+
...envelopeShape,
|
|
66
|
+
event_type: z.literal("tool_call_start").default("tool_call_start"),
|
|
67
|
+
payload: ToolCallStartPayloadSchema
|
|
68
|
+
}).strict();
|
|
69
|
+
var ToolCallEndEventSchema = z.object({
|
|
70
|
+
...envelopeShape,
|
|
71
|
+
event_type: z.literal("tool_call_end").default("tool_call_end"),
|
|
72
|
+
payload: ToolCallEndPayloadSchema
|
|
73
|
+
}).strict();
|
|
74
|
+
var ToolCallErrorEventSchema = z.object({
|
|
75
|
+
...envelopeShape,
|
|
76
|
+
event_type: z.literal("tool_call_error").default("tool_call_error"),
|
|
77
|
+
payload: ToolCallErrorPayloadSchema
|
|
78
|
+
}).strict();
|
|
79
|
+
var AnnotationEventSchema = z.object({
|
|
80
|
+
...envelopeShape,
|
|
81
|
+
event_type: z.literal("annotation").default("annotation"),
|
|
82
|
+
payload: AnnotationPayloadSchema
|
|
83
|
+
}).strict();
|
|
84
|
+
var SurfaceSnapshotEventSchema = z.object({
|
|
85
|
+
...envelopeShape,
|
|
86
|
+
event_type: z.literal("surface_snapshot").default("surface_snapshot"),
|
|
87
|
+
payload: SurfaceSnapshotPayloadSchema
|
|
88
|
+
}).strict();
|
|
89
|
+
var EventSchema = z.discriminatedUnion("event_type", [
|
|
90
|
+
ToolCallStartEventSchema,
|
|
91
|
+
ToolCallEndEventSchema,
|
|
92
|
+
ToolCallErrorEventSchema,
|
|
93
|
+
AnnotationEventSchema,
|
|
94
|
+
SurfaceSnapshotEventSchema
|
|
95
|
+
]);
|
|
96
|
+
|
|
97
|
+
// src/scrub.ts
|
|
98
|
+
var DEPTH_LIMIT = 10;
|
|
99
|
+
var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
100
|
+
"email",
|
|
101
|
+
"phone",
|
|
102
|
+
"ssn",
|
|
103
|
+
"api_key",
|
|
104
|
+
"token",
|
|
105
|
+
"secret",
|
|
106
|
+
"password",
|
|
107
|
+
"user_name"
|
|
108
|
+
]);
|
|
109
|
+
var PATTERNS = [
|
|
110
|
+
["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
|
|
111
|
+
["bearer", /\bBearer\s+[A-Za-z0-9_\-.+/=]{16,}/gi],
|
|
112
|
+
["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
113
|
+
["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
114
|
+
["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
|
|
115
|
+
// Phone: optional `+1`, optional area-code parens, separators
|
|
116
|
+
// `-` / `.` / space, 10 digits. Conservative — won't catch every
|
|
117
|
+
// international format, but won't trip on every 10-digit identifier.
|
|
118
|
+
["phone", /\b(?:\+?1[\s\-.]?)?\(?\d{3}\)?[\s\-.]?\d{3}[\s\-.]?\d{4}\b/g]
|
|
119
|
+
];
|
|
120
|
+
var CC_CANDIDATE = /\b\d{13,19}\b/g;
|
|
121
|
+
function luhnValid(digits) {
|
|
122
|
+
let total = 0;
|
|
123
|
+
for (let i = 0; i < digits.length; i += 1) {
|
|
124
|
+
let n = Number(digits[digits.length - 1 - i]);
|
|
125
|
+
if (i % 2 === 1) {
|
|
126
|
+
n *= 2;
|
|
127
|
+
if (n > 9) n -= 9;
|
|
128
|
+
}
|
|
129
|
+
total += n;
|
|
130
|
+
}
|
|
131
|
+
return total % 10 === 0;
|
|
132
|
+
}
|
|
133
|
+
function isPlainObject(value) {
|
|
134
|
+
if (typeof value !== "object" || value === null) return false;
|
|
135
|
+
const proto = Object.getPrototypeOf(value);
|
|
136
|
+
return proto === Object.prototype || proto === null;
|
|
137
|
+
}
|
|
138
|
+
var Scrubber = class {
|
|
139
|
+
counts = /* @__PURE__ */ new Map();
|
|
140
|
+
/** Bound so `new Scrubber().scrub` can be passed as a bare function
|
|
141
|
+
* reference — the closest TS gets to Python's `__call__`. */
|
|
142
|
+
scrub = (value) => this.walk(value, 0, null);
|
|
143
|
+
/** Python's `Counter[category]` zero-default read. */
|
|
144
|
+
count(category) {
|
|
145
|
+
return this.counts.get(category) ?? 0;
|
|
146
|
+
}
|
|
147
|
+
bump(category) {
|
|
148
|
+
this.counts.set(category, this.count(category) + 1);
|
|
149
|
+
}
|
|
150
|
+
walk(value, depth, forceField) {
|
|
151
|
+
if (depth >= DEPTH_LIMIT) return value;
|
|
152
|
+
if (isPlainObject(value)) {
|
|
153
|
+
const out = {};
|
|
154
|
+
for (const [k, v] of Object.entries(value)) {
|
|
155
|
+
const nextForce = REDACT_FIELD_NAMES.has(k.toLowerCase()) ? k.toLowerCase() : forceField;
|
|
156
|
+
out[k] = this.walk(v, depth + 1, nextForce);
|
|
157
|
+
}
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
if (Array.isArray(value)) {
|
|
161
|
+
return value.map((item) => this.walk(item, depth + 1, forceField));
|
|
162
|
+
}
|
|
163
|
+
if (typeof value === "string") {
|
|
164
|
+
if (forceField !== null) {
|
|
165
|
+
this.bump(`field:${forceField}`);
|
|
166
|
+
return `[REDACTED:field-${forceField}]`;
|
|
167
|
+
}
|
|
168
|
+
return this.scrubString(value);
|
|
169
|
+
}
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
scrubString(s) {
|
|
173
|
+
let out = s;
|
|
174
|
+
for (const [category, pattern] of PATTERNS) {
|
|
175
|
+
out = out.replace(pattern, () => {
|
|
176
|
+
this.bump(category);
|
|
177
|
+
return `[REDACTED:${category}]`;
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
return out.replace(CC_CANDIDATE, (match) => {
|
|
181
|
+
if (!luhnValid(match)) return match;
|
|
182
|
+
this.bump("cc");
|
|
183
|
+
return "[REDACTED:cc]";
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
function identityScrub(value) {
|
|
188
|
+
return value;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/sinks.ts
|
|
192
|
+
async function safeWrite(sink, event) {
|
|
193
|
+
try {
|
|
194
|
+
await sink.write(event);
|
|
195
|
+
} catch (err) {
|
|
196
|
+
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${String(err)}
|
|
197
|
+
`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
var StdoutSink = class {
|
|
201
|
+
stream;
|
|
202
|
+
closed = false;
|
|
203
|
+
constructor(options = {}) {
|
|
204
|
+
this.stream = options.stream ?? process.stderr;
|
|
205
|
+
}
|
|
206
|
+
async write(event) {
|
|
207
|
+
if (this.closed) throw new Error("StdoutSink is closed");
|
|
208
|
+
this.stream.write(JSON.stringify(event) + "\n");
|
|
209
|
+
}
|
|
210
|
+
async flush() {
|
|
211
|
+
}
|
|
212
|
+
async aclose() {
|
|
213
|
+
this.closed = true;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
var CircuitBreaker = class {
|
|
217
|
+
constructor(threshold, resetMs) {
|
|
218
|
+
this.threshold = threshold;
|
|
219
|
+
this.resetMs = resetMs;
|
|
220
|
+
}
|
|
221
|
+
threshold;
|
|
222
|
+
resetMs;
|
|
223
|
+
failures = 0;
|
|
224
|
+
openedAt = null;
|
|
225
|
+
canRequest() {
|
|
226
|
+
if (this.openedAt === null) return true;
|
|
227
|
+
return Date.now() - this.openedAt >= this.resetMs;
|
|
228
|
+
}
|
|
229
|
+
recordSuccess() {
|
|
230
|
+
this.failures = 0;
|
|
231
|
+
this.openedAt = null;
|
|
232
|
+
}
|
|
233
|
+
recordFailure() {
|
|
234
|
+
this.failures += 1;
|
|
235
|
+
if (this.failures >= this.threshold) {
|
|
236
|
+
this.openedAt = Date.now();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
var HttpSink = class _HttpSink {
|
|
241
|
+
url;
|
|
242
|
+
apiKey;
|
|
243
|
+
buffer = [];
|
|
244
|
+
bufferSize;
|
|
245
|
+
maxRetries;
|
|
246
|
+
backoffBaseMs;
|
|
247
|
+
backoffMaxMs;
|
|
248
|
+
circuit;
|
|
249
|
+
fetchImpl;
|
|
250
|
+
overflowWarned = false;
|
|
251
|
+
closed = false;
|
|
252
|
+
drainChain = Promise.resolve();
|
|
253
|
+
beforeExitHandler = null;
|
|
254
|
+
constructor(url, options) {
|
|
255
|
+
this.url = url.replace(/\/+$/, "");
|
|
256
|
+
this.apiKey = options.apiKey;
|
|
257
|
+
this.bufferSize = options.bufferSize ?? 1e3;
|
|
258
|
+
this.maxRetries = options.maxRetries ?? 3;
|
|
259
|
+
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
260
|
+
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
261
|
+
this.circuit = new CircuitBreaker(
|
|
262
|
+
options.circuitBreakerThreshold ?? 5,
|
|
263
|
+
options.circuitBreakerResetMs ?? 3e4
|
|
264
|
+
);
|
|
265
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
266
|
+
}
|
|
267
|
+
async write(event) {
|
|
268
|
+
if (this.closed) throw new Error("HttpSink is closed");
|
|
269
|
+
this.enqueue(event);
|
|
270
|
+
void this.scheduleDrain();
|
|
271
|
+
this.ensureBeforeExitRegistered();
|
|
272
|
+
}
|
|
273
|
+
async flush() {
|
|
274
|
+
if (this.closed) return;
|
|
275
|
+
await this.scheduleDrain();
|
|
276
|
+
}
|
|
277
|
+
async aclose() {
|
|
278
|
+
if (this.closed) return;
|
|
279
|
+
await this.flush();
|
|
280
|
+
this.closed = true;
|
|
281
|
+
if (this.beforeExitHandler) {
|
|
282
|
+
process.off("beforeExit", this.beforeExitHandler);
|
|
283
|
+
this.beforeExitHandler = null;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
enqueue(event) {
|
|
287
|
+
if (this.buffer.length >= this.bufferSize) {
|
|
288
|
+
if (!this.overflowWarned) {
|
|
289
|
+
process.emitWarning(
|
|
290
|
+
`Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
|
|
291
|
+
);
|
|
292
|
+
this.overflowWarned = true;
|
|
293
|
+
}
|
|
294
|
+
this.buffer.shift();
|
|
295
|
+
}
|
|
296
|
+
this.buffer.push(event);
|
|
297
|
+
}
|
|
298
|
+
/** Serializes every call to `drainLocked` — from `write()`'s background
|
|
299
|
+
* drain and from explicit `flush()` alike — onto one promise chain, so
|
|
300
|
+
* concurrent tool calls (the normal case once the MCP interceptor is
|
|
301
|
+
* wired up) can never run two drains at once racing on `buffer[0]`/
|
|
302
|
+
* `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */
|
|
303
|
+
scheduleDrain() {
|
|
304
|
+
this.drainChain = this.drainChain.then(
|
|
305
|
+
() => this.drainLocked(),
|
|
306
|
+
() => this.drainLocked()
|
|
307
|
+
);
|
|
308
|
+
return this.drainChain;
|
|
309
|
+
}
|
|
310
|
+
/** Best-effort flush when the process is about to exit without an
|
|
311
|
+
* explicit `aclose()`. Node re-runs `beforeExit` if new async work is
|
|
312
|
+
* scheduled during it, so an in-flight flush here can complete normally —
|
|
313
|
+
* unlike Python's synchronous `atexit`, no separate sync-client fallback
|
|
314
|
+
* is needed. Real residual gap, not fixable in-process: SIGKILL, or
|
|
315
|
+
* SIGTERM with no installed handler, skip `beforeExit` entirely. A vendor
|
|
316
|
+
* needing that guarantee must call `aclose()` from their own handler. */
|
|
317
|
+
ensureBeforeExitRegistered() {
|
|
318
|
+
if (this.beforeExitHandler) return;
|
|
319
|
+
this.beforeExitHandler = () => {
|
|
320
|
+
void this.flush();
|
|
321
|
+
};
|
|
322
|
+
process.on("beforeExit", this.beforeExitHandler);
|
|
323
|
+
}
|
|
324
|
+
events_url() {
|
|
325
|
+
return `${this.url}/v0/events`;
|
|
326
|
+
}
|
|
327
|
+
authHeaders() {
|
|
328
|
+
return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
|
|
329
|
+
}
|
|
330
|
+
static classifyStatus(status) {
|
|
331
|
+
if (status >= 200 && status < 300) return "success";
|
|
332
|
+
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
333
|
+
return "transient_failure";
|
|
334
|
+
}
|
|
335
|
+
async drainLocked() {
|
|
336
|
+
while (this.buffer.length > 0) {
|
|
337
|
+
if (!this.circuit.canRequest()) return;
|
|
338
|
+
const event = this.buffer[0];
|
|
339
|
+
const outcome = await this.sendWithRetry(event);
|
|
340
|
+
if (outcome === "success" || outcome === "permanent_failure") {
|
|
341
|
+
this.buffer.shift();
|
|
342
|
+
this.circuit.recordSuccess();
|
|
343
|
+
} else {
|
|
344
|
+
this.circuit.recordFailure();
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
async sendWithRetry(event) {
|
|
350
|
+
const url = this.events_url();
|
|
351
|
+
const headers = this.authHeaders();
|
|
352
|
+
const body = JSON.stringify(event);
|
|
353
|
+
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
354
|
+
try {
|
|
355
|
+
const response = await this.fetchImpl(url, { method: "POST", headers, body });
|
|
356
|
+
const outcome = _HttpSink.classifyStatus(response.status);
|
|
357
|
+
if (outcome !== "transient_failure") return outcome;
|
|
358
|
+
} catch {
|
|
359
|
+
}
|
|
360
|
+
if (attempt < this.maxRetries) {
|
|
361
|
+
const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
|
|
362
|
+
await new Promise((resolve) => setTimeout(resolve, backoff));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return "transient_failure";
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
// src/integrations/mcp/withBaton.ts
|
|
370
|
+
import { v7 as uuidv72 } from "uuid";
|
|
371
|
+
|
|
372
|
+
// src/integrations/mcp/annotation.ts
|
|
373
|
+
import { z as z2 } from "zod";
|
|
374
|
+
|
|
375
|
+
// src/integrations/mcp/emit.ts
|
|
376
|
+
async function emit(sink, build) {
|
|
377
|
+
let event;
|
|
378
|
+
try {
|
|
379
|
+
event = build();
|
|
380
|
+
} catch (err) {
|
|
381
|
+
process.stderr.write(`baton: event construction failed; event dropped: ${String(err)}
|
|
382
|
+
`);
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
await safeWrite(sink, event);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// src/integrations/mcp/llmText.ts
|
|
389
|
+
var SERVER_INSTRUCTIONS_TEMPLATE = (vendorDisplayName, annotationToolName) => `This server is wrapped in the ${vendorDisplayName} support-signal SDK. Use \`${annotationToolName}\` to record what the user is trying to do and how each ${vendorDisplayName} tool call went. See that tool's description for field-level detail.
|
|
390
|
+
|
|
391
|
+
BEFORE invoking any ${vendorDisplayName} tool, you MUST call \`${annotationToolName}\` with user_goal (REQUIRED), expected_result (REQUIRED), and overall_task (REQUIRED when the request fits a recognizable broader task, e.g., 'morning meeting prep', 'pre-outreach research').
|
|
392
|
+
|
|
393
|
+
AFTER any ${vendorDisplayName} tool errors, times out, returns an unhelpful or contradictory result, or the user shows signs of giving up, you MUST call \`${annotationToolName}\` again with signal_type (REQUIRED) \u2014 one of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other \u2014 and suggested_improvement (REQUIRED whenever you can articulate one).
|
|
394
|
+
|
|
395
|
+
IF a ${vendorDisplayName} tool response lacks a structured field for what the user asked about, OR you satisfied the user's intent via a workaround because no tool matched what they asked for, OR the user asked for something this server can't do \u2014 you MUST call \`${annotationToolName}\` with signal_type='feature_gap' AND still answer the user with your best inference. Filing the annotation does NOT replace answering.`;
|
|
396
|
+
var ANNOTATION_TOOL_DESCRIPTION_TEMPLATE = (vendorDisplayName) => `Record structured signal about a ${vendorDisplayName} tool call \u2014 what the user is trying to do, and how it went. Populate proactively before the call (user_goal + expected_result + overall_task) and reactively after if the result was unhelpful (signal_type + suggested_improvement).
|
|
397
|
+
|
|
398
|
+
Fields:
|
|
399
|
+
- user_goal: one sentence on what the user is trying to accomplish.
|
|
400
|
+
- expected_result: what a successful result should look like, so a silent/thin failure can be told apart from success.
|
|
401
|
+
- overall_task: short stable label for the broader task this call serves, e.g., 'morning meeting prep', 'pre-outreach research', 'personal scheduling'. REPEAT the exact same string on every call serving the same task; change it only when the user starts a different task. Skip when the call doesn't fit a recognizable broader task.
|
|
402
|
+
- signal_type: reactive-only \u2014 omit on a proactive annotation. Set only once a tool call has returned an unhelpful result. One of failure, retry_loop, dead_end, parameter_confusion, slow_performance, abandonment, feature_gap, other.
|
|
403
|
+
- suggested_improvement: reactive-only \u2014 omit on a proactive. A concrete sentence about what product change would have helped.
|
|
404
|
+
- 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.`;
|
|
405
|
+
var CLAUDE_CODE_TRUNCATION_CAP = 2087;
|
|
406
|
+
var INSTRUCTIONS_LENGTH_CAP = 1500;
|
|
407
|
+
var SIGNAL_TYPES = [
|
|
408
|
+
"failure",
|
|
409
|
+
"retry_loop",
|
|
410
|
+
"dead_end",
|
|
411
|
+
"parameter_confusion",
|
|
412
|
+
"slow_performance",
|
|
413
|
+
"abandonment",
|
|
414
|
+
"feature_gap",
|
|
415
|
+
"other"
|
|
416
|
+
];
|
|
417
|
+
function buildServerInstructions(options) {
|
|
418
|
+
const rendered = SERVER_INSTRUCTIONS_TEMPLATE(
|
|
419
|
+
options.vendorDisplayName,
|
|
420
|
+
options.annotationToolName
|
|
421
|
+
);
|
|
422
|
+
if (rendered.length > INSTRUCTIONS_LENGTH_CAP) {
|
|
423
|
+
throw new Error(
|
|
424
|
+
`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.`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
return rendered;
|
|
428
|
+
}
|
|
429
|
+
function buildAnnotationToolDescription(options) {
|
|
430
|
+
return ANNOTATION_TOOL_DESCRIPTION_TEMPLATE(options.vendorDisplayName);
|
|
431
|
+
}
|
|
432
|
+
var USER_GOAL_PARAM_NAME = "user_goal";
|
|
433
|
+
var EXPECTED_RESULT_PARAM_NAME = "expected_result";
|
|
434
|
+
var OVERALL_TASK_PARAM_NAME = "overall_task";
|
|
435
|
+
var INTENT_SOURCE_PARAM = "injected_param";
|
|
436
|
+
var USER_GOAL_PARAM_DESCRIPTION = "OPTIONAL. One sentence: what the user is actually trying to accomplish with this call (their goal, not a restatement of the arguments).";
|
|
437
|
+
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.";
|
|
438
|
+
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.";
|
|
439
|
+
function buildUserGoalParamDescription() {
|
|
440
|
+
return USER_GOAL_PARAM_DESCRIPTION;
|
|
441
|
+
}
|
|
442
|
+
function buildOverallTaskParamDescription() {
|
|
443
|
+
return OVERALL_TASK_PARAM_DESCRIPTION;
|
|
444
|
+
}
|
|
445
|
+
function buildExpectedResultParamDescription() {
|
|
446
|
+
return EXPECTED_RESULT_PARAM_DESCRIPTION;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// src/integrations/mcp/mcpTypes.ts
|
|
450
|
+
function extraMeta(extra) {
|
|
451
|
+
const direct = extra._meta;
|
|
452
|
+
if (direct) return direct;
|
|
453
|
+
const nested = extra.mcpReq?._meta;
|
|
454
|
+
return nested ?? null;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/integrations/mcp/runtimeAdapter.ts
|
|
458
|
+
function detectAgentRuntime(meta) {
|
|
459
|
+
if (!meta) return null;
|
|
460
|
+
const batonMeta = meta["baton"];
|
|
461
|
+
if (batonMeta && typeof batonMeta === "object") {
|
|
462
|
+
const runtime = batonMeta["agent_runtime"];
|
|
463
|
+
if (typeof runtime === "string" && runtime) return runtime;
|
|
464
|
+
}
|
|
465
|
+
for (const key of Object.keys(meta)) {
|
|
466
|
+
if (key.startsWith("claudecode/")) return "claude-code";
|
|
467
|
+
}
|
|
468
|
+
return null;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// src/integrations/mcp/sessionResolution.ts
|
|
472
|
+
async function resolveSessionId(hook, fallbackSessionId, extra, meta, toolName, args) {
|
|
473
|
+
if (hook) {
|
|
474
|
+
try {
|
|
475
|
+
const hookResult = await hook({ meta, toolName, arguments: args });
|
|
476
|
+
if (typeof hookResult === "string" && hookResult) return hookResult;
|
|
477
|
+
} catch {
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
if (typeof extra.sessionId === "string" && extra.sessionId) return extra.sessionId;
|
|
481
|
+
return fallbackSessionId;
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/integrations/mcp/annotation.ts
|
|
485
|
+
var TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]{1,64}$/;
|
|
486
|
+
function deriveAnnotationToolName(vendorId, override) {
|
|
487
|
+
const name = override || `${vendorId}_annotate`;
|
|
488
|
+
if (!TOOL_NAME_PATTERN.test(name)) {
|
|
489
|
+
throw new Error(
|
|
490
|
+
`Annotation tool name ${JSON.stringify(name)} violates the cross-runtime pattern ${TOOL_NAME_PATTERN.source} (Claude Desktop and others reject names with dots or other separators).`
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
return name;
|
|
494
|
+
}
|
|
495
|
+
function registerAnnotationTool(server, options) {
|
|
496
|
+
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
497
|
+
const description = buildAnnotationToolDescription({
|
|
498
|
+
vendorDisplayName: options.vendorDisplayName
|
|
499
|
+
});
|
|
500
|
+
server.registerTool(
|
|
501
|
+
name,
|
|
502
|
+
{
|
|
503
|
+
description,
|
|
504
|
+
inputSchema: {
|
|
505
|
+
user_goal: z2.string(),
|
|
506
|
+
expected_result: z2.string().optional(),
|
|
507
|
+
signal_type: z2.enum(SIGNAL_TYPES).optional(),
|
|
508
|
+
overall_task: z2.string().optional(),
|
|
509
|
+
suggested_improvement: z2.string().optional(),
|
|
510
|
+
context: z2.record(z2.string(), z2.unknown()).optional()
|
|
511
|
+
}
|
|
512
|
+
},
|
|
513
|
+
async (args, extra) => {
|
|
514
|
+
const meta = extraMeta(extra);
|
|
515
|
+
const runtime = detectAgentRuntime(meta) ?? options.defaultAgentRuntime;
|
|
516
|
+
const scrubbedMeta = meta ? options.scrubber(meta) : null;
|
|
517
|
+
const sessionId = await resolveSessionId(
|
|
518
|
+
options.resolveSessionId,
|
|
519
|
+
options.fallbackSessionId,
|
|
520
|
+
extra,
|
|
521
|
+
meta,
|
|
522
|
+
name,
|
|
523
|
+
args
|
|
524
|
+
);
|
|
525
|
+
if (args.signal_type === void 0) {
|
|
526
|
+
options.tracker?.mark(sessionId);
|
|
527
|
+
}
|
|
528
|
+
await emit(
|
|
529
|
+
options.sink,
|
|
530
|
+
() => AnnotationEventSchema.parse({
|
|
531
|
+
tenant_id: options.tenantId,
|
|
532
|
+
vendor_id: options.vendorId,
|
|
533
|
+
session_id: sessionId,
|
|
534
|
+
sequence_number: options.counter.next(sessionId),
|
|
535
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
536
|
+
consent_token: options.consentToken,
|
|
537
|
+
agent_runtime: runtime,
|
|
538
|
+
runtime_meta: scrubbedMeta,
|
|
539
|
+
payload: {
|
|
540
|
+
// Agent-facing names -> wire keys, as with `overall_task`
|
|
541
|
+
// below: `user_goal` is stored as `intent`, `expected_result` as
|
|
542
|
+
// `expected_outcome`.
|
|
543
|
+
intent: options.scrubber(args.user_goal),
|
|
544
|
+
expected_outcome: args.expected_result ? options.scrubber(args.expected_result) : null,
|
|
545
|
+
// `signal_type` is a closed enum — nothing to scrub. The task label
|
|
546
|
+
// is agent-authored free text ("processing invoice for
|
|
547
|
+
// bob@example.com" is a realistic value), so it IS scrubbed.
|
|
548
|
+
// Python's annotation.py does NOT scrub this field — a shared
|
|
549
|
+
// gap found 2026-08-11, fixed here and flagged for the sibling
|
|
550
|
+
// rather than mirrored. Not a wire divergence: scrubbing changes
|
|
551
|
+
// content, not shape, and it's deterministic, so the
|
|
552
|
+
// exact-string continuity rung 3b groups on survives.
|
|
553
|
+
signal_type: args.signal_type ?? null,
|
|
554
|
+
// Agent-facing param `overall_task` -> wire key `workflow`, the same
|
|
555
|
+
// split the injected params use (`overall_task` -> `call_workflow`):
|
|
556
|
+
// renaming the param must not move the key the console groups on.
|
|
557
|
+
workflow: args.overall_task ? options.scrubber(args.overall_task) : null,
|
|
558
|
+
suggested_improvement: args.suggested_improvement ? options.scrubber(args.suggested_improvement) : null,
|
|
559
|
+
context: args.context ? options.scrubber(args.context) : null
|
|
560
|
+
}
|
|
561
|
+
})
|
|
562
|
+
);
|
|
563
|
+
return { content: [{ type: "text", text: JSON.stringify({ ok: true }) }] };
|
|
564
|
+
}
|
|
565
|
+
);
|
|
566
|
+
return name;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// src/integrations/mcp/config.ts
|
|
570
|
+
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
571
|
+
var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
|
|
572
|
+
function validateBatonConfig(config) {
|
|
573
|
+
if (!VENDOR_ID_PATTERN.test(config.vendorId)) {
|
|
574
|
+
throw new Error(
|
|
575
|
+
`vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
if (!config.vendorDisplayName) {
|
|
579
|
+
throw new Error(
|
|
580
|
+
"BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
if (!config.consentToken) {
|
|
584
|
+
throw new Error(
|
|
585
|
+
"BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
if (config.intentParamMode !== void 0 && !INTENT_PARAM_MODES.has(config.intentParamMode)) {
|
|
589
|
+
throw new Error(
|
|
590
|
+
`BatonConfig.intentParamMode ${JSON.stringify(config.intentParamMode)} must be one of ${JSON.stringify([...INTENT_PARAM_MODES].sort())}.`
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// src/integrations/mcp/handle.ts
|
|
596
|
+
var BatonHandle = class {
|
|
597
|
+
sink;
|
|
598
|
+
vendorId;
|
|
599
|
+
/** Process-lifetime fallback session id — the value events fall back to
|
|
600
|
+
* when no real per-call session id resolves. Not every event necessarily
|
|
601
|
+
* carries this id; see `withBaton`'s session-resolution order. */
|
|
602
|
+
sessionId;
|
|
603
|
+
/** The resolved annotation tool name (`{vendorId}_annotate` unless
|
|
604
|
+
* overridden via `BatonConfig.annotationToolName`). */
|
|
605
|
+
annotationToolName;
|
|
606
|
+
constructor(options) {
|
|
607
|
+
this.sink = options.sink;
|
|
608
|
+
this.vendorId = options.vendorId;
|
|
609
|
+
this.sessionId = options.sessionId;
|
|
610
|
+
this.annotationToolName = options.annotationToolName;
|
|
611
|
+
}
|
|
612
|
+
/** Flush any pending events held by the sink. */
|
|
613
|
+
async flush() {
|
|
614
|
+
await this.sink.flush();
|
|
615
|
+
}
|
|
616
|
+
/** Flush and release sink resources. Subsequent writes reject. */
|
|
617
|
+
async aclose() {
|
|
618
|
+
await this.sink.aclose();
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
|
|
622
|
+
// src/integrations/mcp/proactiveTracker.ts
|
|
623
|
+
var ProactiveTracker = class {
|
|
624
|
+
emitted = /* @__PURE__ */ new Set();
|
|
625
|
+
/** Claim the session's proactive slot. Returns true exactly once per
|
|
626
|
+
* session (the caller should then emit); false if already claimed. */
|
|
627
|
+
claim(sessionId) {
|
|
628
|
+
if (this.emitted.has(sessionId)) return false;
|
|
629
|
+
this.emitted.add(sessionId);
|
|
630
|
+
return true;
|
|
631
|
+
}
|
|
632
|
+
/** Mark the slot claimed without emitting here (the annotation tool's own
|
|
633
|
+
* handler already emitted the annotation event itself). */
|
|
634
|
+
mark(sessionId) {
|
|
635
|
+
this.emitted.add(sessionId);
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
// src/integrations/mcp/sessionCounter.ts
|
|
640
|
+
var SessionCounter = class {
|
|
641
|
+
counters = /* @__PURE__ */ new Map();
|
|
642
|
+
next(sessionId) {
|
|
643
|
+
const current = this.counters.get(sessionId) ?? 0;
|
|
644
|
+
const next = current + 1;
|
|
645
|
+
this.counters.set(sessionId, next);
|
|
646
|
+
return next;
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
|
|
650
|
+
// src/integrations/mcp/zodCompat.ts
|
|
651
|
+
import * as z3rt from "zod/v3";
|
|
652
|
+
import * as z4mini from "zod/v4-mini";
|
|
653
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
654
|
+
function isZ4Schema(s) {
|
|
655
|
+
const schema = s;
|
|
656
|
+
return !!schema?._zod;
|
|
657
|
+
}
|
|
658
|
+
function objectFromShape(shape) {
|
|
659
|
+
const values = Object.values(shape);
|
|
660
|
+
if (values.length === 0) return z4mini.object({});
|
|
661
|
+
const allV4 = values.every(isZ4Schema);
|
|
662
|
+
const allV3 = values.every((s) => !isZ4Schema(s));
|
|
663
|
+
if (allV4) return z4mini.object(shape);
|
|
664
|
+
if (allV3) return z3rt.object(shape);
|
|
665
|
+
throw new Error("Mixed Zod versions detected in object shape.");
|
|
666
|
+
}
|
|
667
|
+
function getObjectShape(schema) {
|
|
668
|
+
if (!schema) return void 0;
|
|
669
|
+
let rawShape;
|
|
670
|
+
if (isZ4Schema(schema)) {
|
|
671
|
+
rawShape = schema._zod?.def?.shape;
|
|
672
|
+
} else {
|
|
673
|
+
rawShape = schema.shape;
|
|
674
|
+
}
|
|
675
|
+
if (!rawShape) return void 0;
|
|
676
|
+
if (typeof rawShape === "function") {
|
|
677
|
+
try {
|
|
678
|
+
return rawShape();
|
|
679
|
+
} catch {
|
|
680
|
+
return void 0;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
return rawShape;
|
|
684
|
+
}
|
|
685
|
+
function normalizeObjectSchema(schema) {
|
|
686
|
+
if (!schema) return void 0;
|
|
687
|
+
if (typeof schema === "object") {
|
|
688
|
+
const asAny = schema;
|
|
689
|
+
if (!asAny._def && !asAny._zod) {
|
|
690
|
+
const values = Object.values(schema);
|
|
691
|
+
if (values.length > 0 && values.every(
|
|
692
|
+
(v) => typeof v === "object" && v !== null && (v._def !== void 0 || v._zod !== void 0 || typeof v.parse === "function")
|
|
693
|
+
)) {
|
|
694
|
+
return objectFromShape(schema);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
if (isZ4Schema(schema)) {
|
|
699
|
+
const def = schema._zod?.def;
|
|
700
|
+
if (def && (def.type === "object" || def.shape !== void 0)) return schema;
|
|
701
|
+
} else {
|
|
702
|
+
if (schema.shape !== void 0) return schema;
|
|
703
|
+
}
|
|
704
|
+
return void 0;
|
|
705
|
+
}
|
|
706
|
+
function mapMiniTarget(t) {
|
|
707
|
+
if (!t) return "draft-7";
|
|
708
|
+
if (t === "jsonSchema7" || t === "draft-7") return "draft-7";
|
|
709
|
+
if (t === "jsonSchema2019-09" || t === "draft-2020-12") return "draft-2020-12";
|
|
710
|
+
return "draft-7";
|
|
711
|
+
}
|
|
712
|
+
function toJsonSchemaCompat(schema, opts) {
|
|
713
|
+
if (isZ4Schema(schema)) {
|
|
714
|
+
return z4mini.toJSONSchema(schema, {
|
|
715
|
+
target: mapMiniTarget(opts?.target),
|
|
716
|
+
io: opts?.pipeStrategy ?? "input"
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
return zodToJsonSchema(schema, {
|
|
720
|
+
strictUnions: opts?.strictUnions ?? true,
|
|
721
|
+
pipeStrategy: opts?.pipeStrategy ?? "input"
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// src/integrations/mcp/schemaCompat.ts
|
|
726
|
+
import { z as zV4 } from "zod";
|
|
727
|
+
import { z as zV3 } from "zod/v3";
|
|
728
|
+
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
729
|
+
function injectGoalParams(inputSchema) {
|
|
730
|
+
const objSchema = normalizeObjectSchema(inputSchema);
|
|
731
|
+
if (!objSchema) return { schema: inputSchema, dispositions: {} };
|
|
732
|
+
const existingShape = getObjectShape(objSchema) ?? {};
|
|
733
|
+
const values = Object.values(existingShape);
|
|
734
|
+
const useV4 = values.length === 0 || isZ4Schema(values[0]);
|
|
735
|
+
const zodImpl = useV4 ? zV4 : zV3;
|
|
736
|
+
const { dispositions, toInject } = buildIntentFields(existingShape, zodImpl);
|
|
737
|
+
if (Object.keys(toInject).length === 0)
|
|
738
|
+
return { schema: inputSchema, dispositions };
|
|
739
|
+
const mergedShape = { ...existingShape, ...toInject };
|
|
740
|
+
const newSchema = objectFromShape(mergedShape);
|
|
741
|
+
return { schema: newSchema, dispositions };
|
|
742
|
+
}
|
|
743
|
+
function buildIntentFields(existingShape, zodImpl) {
|
|
744
|
+
const dispositions = {};
|
|
745
|
+
const toInject = {};
|
|
746
|
+
if (USER_GOAL_PARAM_NAME in existingShape) {
|
|
747
|
+
dispositions[USER_GOAL_PARAM_NAME] = "native";
|
|
748
|
+
} else {
|
|
749
|
+
dispositions[USER_GOAL_PARAM_NAME] = "injected";
|
|
750
|
+
toInject[USER_GOAL_PARAM_NAME] = zodImpl.string().optional().describe(buildUserGoalParamDescription());
|
|
751
|
+
}
|
|
752
|
+
for (const [name, buildDescription] of [
|
|
753
|
+
[EXPECTED_RESULT_PARAM_NAME, buildExpectedResultParamDescription],
|
|
754
|
+
[OVERALL_TASK_PARAM_NAME, buildOverallTaskParamDescription]
|
|
755
|
+
]) {
|
|
756
|
+
if (name in existingShape) {
|
|
757
|
+
dispositions[name] = "native";
|
|
758
|
+
} else {
|
|
759
|
+
dispositions[name] = "injected";
|
|
760
|
+
toInject[name] = zodImpl.string().optional().describe(buildDescription());
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
return { dispositions, toInject };
|
|
764
|
+
}
|
|
765
|
+
function injectGoalParamsV2(inputSchema) {
|
|
766
|
+
const candidate = inputSchema;
|
|
767
|
+
const shape = candidate?.shape;
|
|
768
|
+
if (!shape || typeof shape !== "object" || typeof candidate?.extend !== "function") {
|
|
769
|
+
return { schema: inputSchema, dispositions: {} };
|
|
770
|
+
}
|
|
771
|
+
const { dispositions, toInject } = buildIntentFields(shape, zV4);
|
|
772
|
+
if (Object.keys(toInject).length === 0)
|
|
773
|
+
return { schema: inputSchema, dispositions };
|
|
774
|
+
return { schema: candidate.extend(toInject), dispositions };
|
|
775
|
+
}
|
|
776
|
+
function toolInputJsonSchema(inputSchema) {
|
|
777
|
+
const objSchema = normalizeObjectSchema(inputSchema);
|
|
778
|
+
if (!objSchema) return EMPTY_OBJECT_JSON_SCHEMA;
|
|
779
|
+
return toJsonSchemaCompat(objSchema, {
|
|
780
|
+
strictUnions: true,
|
|
781
|
+
pipeStrategy: "input"
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// src/integrations/mcp/surface.ts
|
|
786
|
+
import { createHash } from "crypto";
|
|
787
|
+
function surfaceHash(surface) {
|
|
788
|
+
const canonical = canonicalJson(surface);
|
|
789
|
+
const digest = createHash("sha256").update(canonical, "utf-8").digest("hex");
|
|
790
|
+
return `sha256:${digest}`;
|
|
791
|
+
}
|
|
792
|
+
function canonicalJson(value) {
|
|
793
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
794
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
795
|
+
const record = value;
|
|
796
|
+
const keys = Object.keys(record).sort();
|
|
797
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
|
|
798
|
+
}
|
|
799
|
+
function buildServerMeta(lowlevelServer) {
|
|
800
|
+
const server = lowlevelServer;
|
|
801
|
+
const info = server._serverInfo;
|
|
802
|
+
const capabilities = typeof server.getCapabilities === "function" ? server.getCapabilities() : null;
|
|
803
|
+
const instructions = server._instructions ?? null;
|
|
804
|
+
return {
|
|
805
|
+
server_info: info ? { name: info.name ?? "", version: info.version ?? "" } : null,
|
|
806
|
+
capabilities: capabilities ?? null,
|
|
807
|
+
instructions
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
function assembleSurface(serverMeta, tools) {
|
|
811
|
+
return {
|
|
812
|
+
server_info: serverMeta.server_info,
|
|
813
|
+
capabilities: serverMeta.capabilities,
|
|
814
|
+
instructions: serverMeta.instructions,
|
|
815
|
+
tools
|
|
816
|
+
};
|
|
817
|
+
}
|
|
818
|
+
function buildSeamAugmentations(options) {
|
|
819
|
+
return {
|
|
820
|
+
injected_tools: [...options.injectedToolNames].sort(),
|
|
821
|
+
intent_param: options.intentParamMode !== "off" ? { names: [...options.intentParamNames].sort(), mode: options.intentParamMode } : null,
|
|
822
|
+
instructions_suffix: true
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// src/integrations/mcp/withBaton.ts
|
|
827
|
+
var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
|
|
828
|
+
var wired = /* @__PURE__ */ new WeakSet();
|
|
829
|
+
var SurfaceState = class {
|
|
830
|
+
constructor(serverMeta) {
|
|
831
|
+
this.serverMeta = serverMeta;
|
|
832
|
+
}
|
|
833
|
+
serverMeta;
|
|
834
|
+
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
835
|
+
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
836
|
+
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
837
|
+
* injected schema as if it were vendor-true. */
|
|
838
|
+
rawTools = /* @__PURE__ */ new Map();
|
|
839
|
+
emittedHashes = /* @__PURE__ */ new Set();
|
|
840
|
+
dirty = false;
|
|
841
|
+
/** `inputSchemaJson` is already converted — by `ctx.vendorToolJsonSchema`,
|
|
842
|
+
* which picks the spelling THIS SDK major puts on the wire. */
|
|
843
|
+
noteTool(name, inputSchemaJson, description) {
|
|
844
|
+
this.rawTools.set(name, {
|
|
845
|
+
disabled: this.rawTools.get(name)?.disabled ?? false,
|
|
846
|
+
tool: { name, description: description ?? null, inputSchema: inputSchemaJson }
|
|
847
|
+
});
|
|
848
|
+
this.dirty = true;
|
|
849
|
+
}
|
|
850
|
+
pruneTool(name) {
|
|
851
|
+
if (this.rawTools.delete(name)) this.dirty = true;
|
|
852
|
+
}
|
|
853
|
+
/** Follow a `update({name})` rename, keeping the snapshot keyed the way
|
|
854
|
+
* `tools/list` now renders it. */
|
|
855
|
+
renameTool(from, to) {
|
|
856
|
+
const entry = this.rawTools.get(from);
|
|
857
|
+
if (!entry) return;
|
|
858
|
+
this.rawTools.delete(from);
|
|
859
|
+
this.rawTools.set(to, { ...entry, tool: { ...entry.tool, name: to } });
|
|
860
|
+
this.dirty = true;
|
|
861
|
+
}
|
|
862
|
+
/** Both majors filter `tools/list` on `tool.enabled`, so a disabled tool is
|
|
863
|
+
* not part of the surface a client sees and must not be part of the one we
|
|
864
|
+
* hash. Leaving it in is the same phantom-tool defect the `.remove()` patch
|
|
865
|
+
* exists to prevent, reached through `disable()` instead. */
|
|
866
|
+
setToolEnabled(name, enabled) {
|
|
867
|
+
const entry = this.rawTools.get(name);
|
|
868
|
+
if (!entry || entry.disabled === !enabled) return;
|
|
869
|
+
entry.disabled = !enabled;
|
|
870
|
+
this.dirty = true;
|
|
871
|
+
}
|
|
872
|
+
buildSnapshot() {
|
|
873
|
+
const names = [...this.rawTools.keys()].sort().filter((n) => !this.rawTools.get(n).disabled);
|
|
874
|
+
return assembleSurface(
|
|
875
|
+
this.serverMeta,
|
|
876
|
+
names.map((n) => this.rawTools.get(n).tool)
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
};
|
|
880
|
+
function batonWrap(nameRef, original, ctx) {
|
|
881
|
+
return async (...callArgs) => {
|
|
882
|
+
const toolName = nameRef.current;
|
|
883
|
+
await maybeEmitSurfaceSnapshot(ctx);
|
|
884
|
+
const extra = callArgs[callArgs.length - 1];
|
|
885
|
+
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
886
|
+
const meta = extraMeta(extra);
|
|
887
|
+
const runtime = detectAgentRuntime(meta) ?? ctx.defaultAgentRuntime;
|
|
888
|
+
const scrubbedMeta = meta ? ctx.scrubber(meta) : null;
|
|
889
|
+
const sessionId = await resolveSessionId(
|
|
890
|
+
ctx.resolveSessionId,
|
|
891
|
+
ctx.fallbackSessionId,
|
|
892
|
+
extra,
|
|
893
|
+
meta,
|
|
894
|
+
toolName,
|
|
895
|
+
params
|
|
896
|
+
);
|
|
897
|
+
const dispositions = ctx.paramRegistry.get(toolName);
|
|
898
|
+
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions);
|
|
899
|
+
const rawExpected = extractGoalParam(
|
|
900
|
+
params,
|
|
901
|
+
EXPECTED_RESULT_PARAM_NAME,
|
|
902
|
+
toolName,
|
|
903
|
+
dispositions
|
|
904
|
+
);
|
|
905
|
+
const rawWorkflow = extractGoalParam(params, OVERALL_TASK_PARAM_NAME, toolName, dispositions);
|
|
906
|
+
const scrubbedIntent = rawIntent !== null ? ctx.scrubber(rawIntent) : null;
|
|
907
|
+
const scrubbedExpected = rawExpected !== null ? ctx.scrubber(rawExpected) : null;
|
|
908
|
+
const scrubbedWorkflow = rawWorkflow !== null ? ctx.scrubber(rawWorkflow) : null;
|
|
909
|
+
const common = {
|
|
910
|
+
tenant_id: ctx.tenantId,
|
|
911
|
+
vendor_id: ctx.vendorId,
|
|
912
|
+
session_id: sessionId,
|
|
913
|
+
consent_token: ctx.consentToken,
|
|
914
|
+
agent_runtime: runtime,
|
|
915
|
+
runtime_meta: scrubbedMeta
|
|
916
|
+
};
|
|
917
|
+
if (scrubbedIntent !== null && ctx.tracker.claim(sessionId)) {
|
|
918
|
+
await emit(
|
|
919
|
+
ctx.sink,
|
|
920
|
+
() => AnnotationEventSchema.parse({
|
|
921
|
+
...common,
|
|
922
|
+
sequence_number: ctx.counter.next(sessionId),
|
|
923
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
924
|
+
payload: {
|
|
925
|
+
intent: scrubbedIntent,
|
|
926
|
+
expected_outcome: scrubbedExpected,
|
|
927
|
+
intent_source: INTENT_SOURCE_PARAM,
|
|
928
|
+
tool_name: toolName
|
|
929
|
+
}
|
|
930
|
+
})
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
await emit(
|
|
934
|
+
ctx.sink,
|
|
935
|
+
() => ToolCallStartEventSchema.parse({
|
|
936
|
+
...common,
|
|
937
|
+
sequence_number: ctx.counter.next(sessionId),
|
|
938
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
939
|
+
payload: {
|
|
940
|
+
tool_name: toolName,
|
|
941
|
+
params: ctx.scrubber(params),
|
|
942
|
+
call_intent: scrubbedIntent,
|
|
943
|
+
call_expected: scrubbedExpected,
|
|
944
|
+
call_workflow: scrubbedWorkflow,
|
|
945
|
+
intent_source: scrubbedIntent !== null ? INTENT_SOURCE_PARAM : null
|
|
946
|
+
}
|
|
947
|
+
})
|
|
948
|
+
);
|
|
949
|
+
const startedAt = performance.now();
|
|
950
|
+
let result;
|
|
951
|
+
try {
|
|
952
|
+
result = await original(...callArgs);
|
|
953
|
+
} catch (err) {
|
|
954
|
+
const durationMs2 = Math.round(performance.now() - startedAt);
|
|
955
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
956
|
+
await emit(
|
|
957
|
+
ctx.sink,
|
|
958
|
+
() => ToolCallErrorEventSchema.parse({
|
|
959
|
+
...common,
|
|
960
|
+
sequence_number: ctx.counter.next(sessionId),
|
|
961
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
962
|
+
payload: {
|
|
963
|
+
tool_name: toolName,
|
|
964
|
+
error_type: err instanceof Error ? err.constructor.name : "Error",
|
|
965
|
+
error_body: String(ctx.scrubber(message)).slice(0, 2e3),
|
|
966
|
+
duration_ms: durationMs2
|
|
967
|
+
}
|
|
968
|
+
})
|
|
969
|
+
);
|
|
970
|
+
throw err;
|
|
971
|
+
}
|
|
972
|
+
const durationMs = Math.round(performance.now() - startedAt);
|
|
973
|
+
await emit(
|
|
974
|
+
ctx.sink,
|
|
975
|
+
() => ToolCallEndEventSchema.parse({
|
|
976
|
+
...common,
|
|
977
|
+
sequence_number: ctx.counter.next(sessionId),
|
|
978
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
979
|
+
payload: { tool_name: toolName, result: ctx.scrubber(result), duration_ms: durationMs }
|
|
980
|
+
})
|
|
981
|
+
);
|
|
982
|
+
return result;
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
function extractGoalParam(args, paramName, toolName, dispositions) {
|
|
986
|
+
if (!(paramName in args)) return null;
|
|
987
|
+
const disposition = dispositions ? dispositions[paramName] : void 0;
|
|
988
|
+
if (disposition === "native") return null;
|
|
989
|
+
if (disposition === void 0) {
|
|
990
|
+
process.stderr.write(
|
|
991
|
+
`baton: stripping ${paramName} from unlisted tool ${JSON.stringify(toolName)} (cold registry)
|
|
992
|
+
`
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
const raw = args[paramName];
|
|
996
|
+
delete args[paramName];
|
|
997
|
+
return typeof raw === "string" && raw.trim() ? raw : null;
|
|
998
|
+
}
|
|
999
|
+
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
1000
|
+
if (!ctx.surfaceState.dirty) return;
|
|
1001
|
+
ctx.surfaceState.dirty = false;
|
|
1002
|
+
let snapshot;
|
|
1003
|
+
let digest;
|
|
1004
|
+
try {
|
|
1005
|
+
snapshot = ctx.surfaceState.buildSnapshot();
|
|
1006
|
+
digest = surfaceHash(snapshot);
|
|
1007
|
+
} catch (err) {
|
|
1008
|
+
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
1009
|
+
`);
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
if (ctx.surfaceState.emittedHashes.has(digest)) return;
|
|
1013
|
+
const seam = buildSeamAugmentations({
|
|
1014
|
+
injectedToolNames: [ctx.annotationToolName],
|
|
1015
|
+
intentParamNames: [USER_GOAL_PARAM_NAME, EXPECTED_RESULT_PARAM_NAME, OVERALL_TASK_PARAM_NAME],
|
|
1016
|
+
intentParamMode: ctx.intentParamMode
|
|
1017
|
+
});
|
|
1018
|
+
try {
|
|
1019
|
+
await ctx.emitSurface(ctx.fallbackSessionId, digest, { ...snapshot, seam_augmentations: seam });
|
|
1020
|
+
} catch (err) {
|
|
1021
|
+
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
1022
|
+
`);
|
|
1023
|
+
ctx.surfaceState.dirty = true;
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
ctx.surfaceState.emittedHashes.add(digest);
|
|
1027
|
+
}
|
|
1028
|
+
function captureAndInject(name, entry, ctx) {
|
|
1029
|
+
if (!entry || typeof entry !== "object") return;
|
|
1030
|
+
const mutable = entry;
|
|
1031
|
+
ctx.surfaceState.noteTool(name, ctx.vendorToolJsonSchema(name, mutable.inputSchema), mutable.description);
|
|
1032
|
+
if (ctx.intentParamMode === "off") return;
|
|
1033
|
+
const isV2 = typeof mutable.executor === "function";
|
|
1034
|
+
try {
|
|
1035
|
+
const { schema, dispositions } = isV2 ? injectGoalParamsV2(mutable.inputSchema) : injectGoalParams(mutable.inputSchema);
|
|
1036
|
+
if (Object.keys(dispositions).length > 0) {
|
|
1037
|
+
mutable.inputSchema = schema;
|
|
1038
|
+
ctx.bustSchemaMemo(name);
|
|
1039
|
+
ctx.paramRegistry.set(name, dispositions);
|
|
1040
|
+
} else {
|
|
1041
|
+
ctx.paramRegistry.delete(name);
|
|
1042
|
+
}
|
|
1043
|
+
} catch {
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
function wrapIfNeeded(nameRef, entry, ctx) {
|
|
1047
|
+
if (!entry || typeof entry !== "object") return;
|
|
1048
|
+
const mutable = entry;
|
|
1049
|
+
if (typeof mutable.executor === "function") {
|
|
1050
|
+
if (mutable.executor[BATON_WRAPPED]) return;
|
|
1051
|
+
const originalExecutor = mutable.executor;
|
|
1052
|
+
const wrapper2 = batonWrap(nameRef, originalExecutor, ctx);
|
|
1053
|
+
wrapper2[BATON_WRAPPED] = true;
|
|
1054
|
+
mutable.executor = wrapper2;
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
if (typeof mutable.handler !== "function") return;
|
|
1058
|
+
if (mutable.handler[BATON_WRAPPED]) return;
|
|
1059
|
+
const original = mutable.handler;
|
|
1060
|
+
const wrapper = batonWrap(nameRef, original, ctx);
|
|
1061
|
+
wrapper[BATON_WRAPPED] = true;
|
|
1062
|
+
mutable.handler = wrapper;
|
|
1063
|
+
}
|
|
1064
|
+
function wireEntry(name, entry, ctx) {
|
|
1065
|
+
if (name === ctx.annotationToolName) return;
|
|
1066
|
+
if (!entry || typeof entry !== "object") return;
|
|
1067
|
+
const nameRef = { current: name };
|
|
1068
|
+
captureAndInject(name, entry, ctx);
|
|
1069
|
+
wrapIfNeeded(nameRef, entry, ctx);
|
|
1070
|
+
if (wired.has(entry)) return;
|
|
1071
|
+
wired.add(entry);
|
|
1072
|
+
const removable = entry;
|
|
1073
|
+
if (typeof removable.remove === "function") {
|
|
1074
|
+
const originalRemove = removable.remove.bind(entry);
|
|
1075
|
+
removable.remove = () => {
|
|
1076
|
+
originalRemove();
|
|
1077
|
+
ctx.surfaceState.pruneTool(nameRef.current);
|
|
1078
|
+
ctx.paramRegistry.delete(nameRef.current);
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
const updatable = entry;
|
|
1082
|
+
if (typeof updatable.update === "function") {
|
|
1083
|
+
const originalUpdate = updatable.update.bind(entry);
|
|
1084
|
+
updatable.update = (updates) => {
|
|
1085
|
+
const u = updates ?? {};
|
|
1086
|
+
const renameTo = u.name;
|
|
1087
|
+
originalUpdate(updates);
|
|
1088
|
+
if (renameTo === null) {
|
|
1089
|
+
ctx.surfaceState.pruneTool(nameRef.current);
|
|
1090
|
+
ctx.paramRegistry.delete(nameRef.current);
|
|
1091
|
+
return;
|
|
1092
|
+
}
|
|
1093
|
+
if (typeof renameTo === "string" && renameTo !== nameRef.current) {
|
|
1094
|
+
ctx.surfaceState.renameTool(nameRef.current, renameTo);
|
|
1095
|
+
const dispositions = ctx.paramRegistry.get(nameRef.current);
|
|
1096
|
+
ctx.paramRegistry.delete(nameRef.current);
|
|
1097
|
+
if (dispositions) ctx.paramRegistry.set(renameTo, dispositions);
|
|
1098
|
+
nameRef.current = renameTo;
|
|
1099
|
+
}
|
|
1100
|
+
if (u.paramsSchema !== void 0) {
|
|
1101
|
+
captureAndInject(nameRef.current, entry, ctx);
|
|
1102
|
+
}
|
|
1103
|
+
if (typeof u.enabled === "boolean") {
|
|
1104
|
+
ctx.surfaceState.setToolEnabled(nameRef.current, u.enabled);
|
|
1105
|
+
}
|
|
1106
|
+
wrapIfNeeded(nameRef, entry, ctx);
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
function withBaton(server, config) {
|
|
1111
|
+
validateBatonConfig(config);
|
|
1112
|
+
const sink = config.sink ?? new StdoutSink();
|
|
1113
|
+
const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
|
|
1114
|
+
const intentParamMode = config.intentParamMode ?? "optional";
|
|
1115
|
+
const counter = new SessionCounter();
|
|
1116
|
+
const fallbackSessionId = `sdk-${uuidv72()}`;
|
|
1117
|
+
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
1118
|
+
const serverMeta = buildServerMeta(server.server);
|
|
1119
|
+
const surfaceState = new SurfaceState(serverMeta);
|
|
1120
|
+
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
1121
|
+
const event = SurfaceSnapshotEventSchema.parse({
|
|
1122
|
+
tenant_id: config.vendorId,
|
|
1123
|
+
vendor_id: config.vendorId,
|
|
1124
|
+
session_id: sessionId,
|
|
1125
|
+
consent_token: config.consentToken,
|
|
1126
|
+
sequence_number: counter.next(sessionId),
|
|
1127
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1128
|
+
agent_runtime: config.defaultAgentRuntime ?? "unknown",
|
|
1129
|
+
payload: {
|
|
1130
|
+
surface_hash: digest,
|
|
1131
|
+
server_info: snapshot.server_info,
|
|
1132
|
+
capabilities: snapshot.capabilities,
|
|
1133
|
+
instructions: snapshot.instructions,
|
|
1134
|
+
tools: snapshot.tools,
|
|
1135
|
+
seam_augmentations: snapshot.seam_augmentations
|
|
1136
|
+
}
|
|
1137
|
+
});
|
|
1138
|
+
await sink.write(event);
|
|
1139
|
+
};
|
|
1140
|
+
const internals = server;
|
|
1141
|
+
const bustSchemaMemo = (name) => {
|
|
1142
|
+
const memo = internals._toolInputSchemaJson;
|
|
1143
|
+
if (memo && typeof memo === "object") delete memo[name];
|
|
1144
|
+
};
|
|
1145
|
+
const isV2Server = typeof internals.toolInputSchemaJson === "function";
|
|
1146
|
+
const vendorToolJsonSchema = (name, inputSchema) => {
|
|
1147
|
+
if (isV2Server) {
|
|
1148
|
+
try {
|
|
1149
|
+
const json = internals.toolInputSchemaJson(name);
|
|
1150
|
+
if (json) return json;
|
|
1151
|
+
} catch {
|
|
1152
|
+
}
|
|
1153
|
+
try {
|
|
1154
|
+
const standard = inputSchema?.["~standard"];
|
|
1155
|
+
const json = standard?.jsonSchema?.input?.({ target: "draft-2020-12" });
|
|
1156
|
+
if (json) return json;
|
|
1157
|
+
} catch {
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
try {
|
|
1161
|
+
return toolInputJsonSchema(inputSchema);
|
|
1162
|
+
} catch {
|
|
1163
|
+
return { type: "object", properties: {} };
|
|
1164
|
+
}
|
|
1165
|
+
};
|
|
1166
|
+
const tracker = new ProactiveTracker();
|
|
1167
|
+
const ctx = {
|
|
1168
|
+
sink,
|
|
1169
|
+
counter,
|
|
1170
|
+
tenantId: config.vendorId,
|
|
1171
|
+
vendorId: config.vendorId,
|
|
1172
|
+
consentToken: config.consentToken,
|
|
1173
|
+
fallbackSessionId,
|
|
1174
|
+
defaultAgentRuntime: config.defaultAgentRuntime ?? "unknown",
|
|
1175
|
+
scrubber,
|
|
1176
|
+
resolveSessionId: config.resolveSessionId,
|
|
1177
|
+
annotationToolName,
|
|
1178
|
+
intentParamMode,
|
|
1179
|
+
paramRegistry: /* @__PURE__ */ new Map(),
|
|
1180
|
+
vendorToolJsonSchema,
|
|
1181
|
+
bustSchemaMemo,
|
|
1182
|
+
tracker,
|
|
1183
|
+
surfaceState,
|
|
1184
|
+
emitSurface
|
|
1185
|
+
};
|
|
1186
|
+
const instructions = buildServerInstructions({
|
|
1187
|
+
vendorDisplayName: config.vendorDisplayName,
|
|
1188
|
+
annotationToolName
|
|
1189
|
+
});
|
|
1190
|
+
internals.server._instructions = instructions;
|
|
1191
|
+
const resolvedAnnotationToolName = registerAnnotationTool(server, {
|
|
1192
|
+
sink,
|
|
1193
|
+
counter: ctx.counter,
|
|
1194
|
+
tenantId: ctx.tenantId,
|
|
1195
|
+
vendorId: ctx.vendorId,
|
|
1196
|
+
vendorDisplayName: config.vendorDisplayName,
|
|
1197
|
+
consentToken: ctx.consentToken,
|
|
1198
|
+
fallbackSessionId: ctx.fallbackSessionId,
|
|
1199
|
+
defaultAgentRuntime: ctx.defaultAgentRuntime,
|
|
1200
|
+
scrubber: ctx.scrubber,
|
|
1201
|
+
resolveSessionId: ctx.resolveSessionId,
|
|
1202
|
+
annotationToolName: config.annotationToolName,
|
|
1203
|
+
tracker
|
|
1204
|
+
});
|
|
1205
|
+
const existing = internals._registeredTools;
|
|
1206
|
+
if (existing) {
|
|
1207
|
+
for (const [name, entry] of Object.entries(existing)) {
|
|
1208
|
+
wireEntry(name, entry, ctx);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
const originalRegisterTool = internals.registerTool.bind(server);
|
|
1212
|
+
internals.registerTool = (...args) => {
|
|
1213
|
+
const registered = originalRegisterTool(...args);
|
|
1214
|
+
wireEntry(String(args[0]), registered, ctx);
|
|
1215
|
+
return registered;
|
|
1216
|
+
};
|
|
1217
|
+
return new BatonHandle({
|
|
1218
|
+
sink,
|
|
1219
|
+
vendorId: config.vendorId,
|
|
1220
|
+
sessionId: fallbackSessionId,
|
|
1221
|
+
annotationToolName: resolvedAnnotationToolName
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
export {
|
|
1225
|
+
AnnotationEventSchema,
|
|
1226
|
+
AnnotationPayloadSchema,
|
|
1227
|
+
BatonHandle,
|
|
1228
|
+
DEPTH_LIMIT,
|
|
1229
|
+
EventSchema,
|
|
1230
|
+
EventTypeSchema,
|
|
1231
|
+
HttpSink,
|
|
1232
|
+
SDK_VERSION,
|
|
1233
|
+
Scrubber,
|
|
1234
|
+
StdoutSink,
|
|
1235
|
+
SurfaceSnapshotEventSchema,
|
|
1236
|
+
SurfaceSnapshotPayloadSchema,
|
|
1237
|
+
ToolCallEndEventSchema,
|
|
1238
|
+
ToolCallEndPayloadSchema,
|
|
1239
|
+
ToolCallErrorEventSchema,
|
|
1240
|
+
ToolCallErrorPayloadSchema,
|
|
1241
|
+
ToolCallStartEventSchema,
|
|
1242
|
+
ToolCallStartPayloadSchema,
|
|
1243
|
+
identityScrub,
|
|
1244
|
+
safeWrite,
|
|
1245
|
+
withBaton
|
|
1246
|
+
};
|
|
1247
|
+
//# sourceMappingURL=index.js.map
|