@goodtiming/baton-sdk 0.6.1 → 0.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -10
- package/dist/index.cjs +1100 -403
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +238 -30
- package/dist/index.d.ts +238 -30
- package/dist/index.js +1094 -403
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-0.6.
|
|
2
|
+
var SDK_VERSION = "ts-0.6.3";
|
|
3
3
|
|
|
4
4
|
// src/events.ts
|
|
5
5
|
import { z } from "zod";
|
|
@@ -120,6 +120,10 @@ var SurfaceSnapshotPayloadSchema = z.object({
|
|
|
120
120
|
tools: z.array(z.record(z.string(), z.unknown())).default([]),
|
|
121
121
|
seam_augmentations: z.record(z.string(), z.unknown()).default({})
|
|
122
122
|
}).strict();
|
|
123
|
+
var ClientReportPayloadSchema = z.object({
|
|
124
|
+
instance_id: z.uuid(),
|
|
125
|
+
dropped: z.record(z.string(), z.number().int().nonnegative())
|
|
126
|
+
}).strict();
|
|
123
127
|
var DEFAULT_CONSENT_TOKEN = "customer-consented";
|
|
124
128
|
var ClientObservedSchema = z.object({
|
|
125
129
|
info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),
|
|
@@ -157,6 +161,7 @@ var EventTypeSchema = z.enum([
|
|
|
157
161
|
"tool_call_error",
|
|
158
162
|
"annotation",
|
|
159
163
|
"surface_snapshot",
|
|
164
|
+
"client_report",
|
|
160
165
|
// The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
|
|
161
166
|
// shapes were set by `baton-proxy`, which has been emitting all of them in
|
|
162
167
|
// production — see the payload schemas below.
|
|
@@ -266,6 +271,11 @@ var SurfaceSnapshotEventSchema = z.object({
|
|
|
266
271
|
event_type: z.literal("surface_snapshot").default("surface_snapshot"),
|
|
267
272
|
payload: SurfaceSnapshotPayloadSchema
|
|
268
273
|
}).strict();
|
|
274
|
+
var ClientReportEventSchema = z.object({
|
|
275
|
+
...envelopeShape,
|
|
276
|
+
event_type: z.literal("client_report").default("client_report"),
|
|
277
|
+
payload: ClientReportPayloadSchema
|
|
278
|
+
}).strict();
|
|
269
279
|
var ResourceListStartEventSchema = z.object({
|
|
270
280
|
...envelopeShape,
|
|
271
281
|
event_type: z.literal("resource_list_start").default("resource_list_start"),
|
|
@@ -347,6 +357,7 @@ var EventSchema = z.discriminatedUnion("event_type", [
|
|
|
347
357
|
ToolCallErrorEventSchema,
|
|
348
358
|
AnnotationEventSchema,
|
|
349
359
|
SurfaceSnapshotEventSchema,
|
|
360
|
+
ClientReportEventSchema,
|
|
350
361
|
ResourceListStartEventSchema,
|
|
351
362
|
ResourceListEndEventSchema,
|
|
352
363
|
ResourceListErrorEventSchema,
|
|
@@ -364,8 +375,33 @@ var EventSchema = z.discriminatedUnion("event_type", [
|
|
|
364
375
|
ToolListErrorEventSchema
|
|
365
376
|
]);
|
|
366
377
|
|
|
378
|
+
// src/warn.ts
|
|
379
|
+
function warn(message) {
|
|
380
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
381
|
+
process.emitWarning(message);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
function printable(err) {
|
|
385
|
+
try {
|
|
386
|
+
return String(err);
|
|
387
|
+
} catch {
|
|
388
|
+
return "(an error that cannot be printed)";
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// src/_object.ts
|
|
393
|
+
function isPlainObject(value) {
|
|
394
|
+
if (typeof value !== "object" || value === null) return false;
|
|
395
|
+
const proto = Object.getPrototypeOf(value);
|
|
396
|
+
return proto === Object.prototype || proto === null;
|
|
397
|
+
}
|
|
398
|
+
function isRecord(value) {
|
|
399
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
400
|
+
}
|
|
401
|
+
|
|
367
402
|
// src/scrub.ts
|
|
368
403
|
var DEPTH_LIMIT = 10;
|
|
404
|
+
var DEPTH_MARKER = "[REDACTED:depth-limit]";
|
|
369
405
|
var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
370
406
|
"email",
|
|
371
407
|
"phone",
|
|
@@ -376,16 +412,21 @@ var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
|
376
412
|
"password",
|
|
377
413
|
"user_name"
|
|
378
414
|
]);
|
|
415
|
+
var WS_CHARS = String.raw` \t\n\r\f\u00a0`;
|
|
416
|
+
var PHONE_SEP = String.raw`[${WS_CHARS}\-.]`;
|
|
379
417
|
var PATTERNS = [
|
|
380
418
|
["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
|
|
381
|
-
["bearer",
|
|
419
|
+
["bearer", new RegExp(String.raw`\bBearer[${WS_CHARS}]+[A-Za-z0-9_\-.+/=]{16,}`, "gi")],
|
|
382
420
|
["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
383
421
|
["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
384
422
|
["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
|
|
385
423
|
// Phone: optional `+1`, optional area-code parens, separators
|
|
386
|
-
//
|
|
424
|
+
// `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every
|
|
387
425
|
// international format, but won't trip on every 10-digit identifier.
|
|
388
|
-
[
|
|
426
|
+
[
|
|
427
|
+
"phone",
|
|
428
|
+
new RegExp(String.raw`\b(?:\+?1${PHONE_SEP}?)?\(?\d{3}\)?${PHONE_SEP}?\d{3}${PHONE_SEP}?\d{4}\b`, "g")
|
|
429
|
+
]
|
|
389
430
|
];
|
|
390
431
|
var CC_CANDIDATE = /\b\d{13,19}\b/g;
|
|
391
432
|
function luhnValid(digits) {
|
|
@@ -400,13 +441,9 @@ function luhnValid(digits) {
|
|
|
400
441
|
}
|
|
401
442
|
return total % 10 === 0;
|
|
402
443
|
}
|
|
403
|
-
function isPlainObject(value) {
|
|
404
|
-
if (typeof value !== "object" || value === null) return false;
|
|
405
|
-
const proto = Object.getPrototypeOf(value);
|
|
406
|
-
return proto === Object.prototype || proto === null;
|
|
407
|
-
}
|
|
408
444
|
var Scrubber = class {
|
|
409
445
|
counts = /* @__PURE__ */ new Map();
|
|
446
|
+
warnedDepth = false;
|
|
410
447
|
/** Bound so `new Scrubber().scrub` can be passed as a bare function
|
|
411
448
|
* reference — the closest TS gets to Python's `__call__`. */
|
|
412
449
|
scrub = (value) => this.walk(value, 0, null);
|
|
@@ -417,8 +454,20 @@ var Scrubber = class {
|
|
|
417
454
|
bump(category) {
|
|
418
455
|
this.counts.set(category, this.count(category) + 1);
|
|
419
456
|
}
|
|
457
|
+
pastTheDepthLimit() {
|
|
458
|
+
this.bump("depth_limit");
|
|
459
|
+
if (!this.warnedDepth) {
|
|
460
|
+
this.warnedDepth = true;
|
|
461
|
+
warn(
|
|
462
|
+
`baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
return DEPTH_MARKER;
|
|
466
|
+
}
|
|
420
467
|
walk(value, depth, forceField) {
|
|
421
|
-
if (depth >= DEPTH_LIMIT)
|
|
468
|
+
if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {
|
|
469
|
+
return this.pastTheDepthLimit();
|
|
470
|
+
}
|
|
422
471
|
if (isPlainObject(value)) {
|
|
423
472
|
const out = {};
|
|
424
473
|
for (const [k, v] of Object.entries(value)) {
|
|
@@ -459,12 +508,167 @@ function identityScrub(value) {
|
|
|
459
508
|
}
|
|
460
509
|
|
|
461
510
|
// src/sinks.ts
|
|
511
|
+
import { closeSync, openSync, writeSync } from "fs";
|
|
512
|
+
|
|
513
|
+
// src/_text.ts
|
|
514
|
+
var WHITE_SPACE = /^\p{White_Space}$/u;
|
|
515
|
+
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
516
|
+
function stripEdges(value, space) {
|
|
517
|
+
let start = 0;
|
|
518
|
+
let end = value.length;
|
|
519
|
+
while (start < end && space.test(value[start])) start++;
|
|
520
|
+
while (end > start && space.test(value[end - 1])) end--;
|
|
521
|
+
return value.slice(start, end);
|
|
522
|
+
}
|
|
523
|
+
function stripWhiteSpace(value) {
|
|
524
|
+
return stripEdges(value, WHITE_SPACE);
|
|
525
|
+
}
|
|
526
|
+
function isBlank(value) {
|
|
527
|
+
return ALL_WHITE_SPACE.test(value);
|
|
528
|
+
}
|
|
529
|
+
function exceedsCodePoints(value, max) {
|
|
530
|
+
if (value.length <= max) return false;
|
|
531
|
+
if (value.length > 2 * max) return true;
|
|
532
|
+
return [...value].length > max;
|
|
533
|
+
}
|
|
534
|
+
function capCodePoints(value, max) {
|
|
535
|
+
if (value.length <= max) return value;
|
|
536
|
+
return [...value].slice(0, max).join("");
|
|
537
|
+
}
|
|
538
|
+
function escapeForLog(value) {
|
|
539
|
+
return value.replace(/[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (c) => `\\u{${c.codePointAt(0).toString(16)}}`);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// src/deadline.ts
|
|
543
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timedOut");
|
|
544
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
545
|
+
async function raceDeadline(work, ms) {
|
|
546
|
+
let timer;
|
|
547
|
+
const deadline = new Promise((resolve) => {
|
|
548
|
+
timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));
|
|
549
|
+
timer.unref?.();
|
|
550
|
+
});
|
|
551
|
+
try {
|
|
552
|
+
return await Promise.race([work, deadline]);
|
|
553
|
+
} finally {
|
|
554
|
+
clearTimeout(timer);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
|
|
558
|
+
|
|
559
|
+
// src/drops.ts
|
|
560
|
+
var RECOVERY_LOG_MS = 6e4;
|
|
561
|
+
var DropCounts = class {
|
|
562
|
+
#instanceId = uuid7();
|
|
563
|
+
#total = /* @__PURE__ */ new Map();
|
|
564
|
+
#sinceDelivery = /* @__PURE__ */ new Map();
|
|
565
|
+
#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
566
|
+
add(reason, n = 1) {
|
|
567
|
+
if (n <= 0) return;
|
|
568
|
+
this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);
|
|
569
|
+
this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);
|
|
570
|
+
}
|
|
571
|
+
total() {
|
|
572
|
+
return Object.fromEntries(this.#total);
|
|
573
|
+
}
|
|
574
|
+
/** Called on each delivery: names what was lost before it, the other half of
|
|
575
|
+
* a drop's own warning, which says only that loss started. */
|
|
576
|
+
logRecovery() {
|
|
577
|
+
if (this.#sinceDelivery.size === 0) return;
|
|
578
|
+
const now = performance.now();
|
|
579
|
+
if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;
|
|
580
|
+
const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
|
|
581
|
+
this.#sinceDelivery.clear();
|
|
582
|
+
this.#lastRecoveryLog = now;
|
|
583
|
+
const total = lost.reduce((sum, [, n]) => sum + n, 0);
|
|
584
|
+
warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
|
|
585
|
+
}
|
|
586
|
+
/** For tests: the counts are one per process. */
|
|
587
|
+
/** Names this process in its loss reports (SPEC §11.4.7). */
|
|
588
|
+
get instanceId() {
|
|
589
|
+
return this.#instanceId;
|
|
590
|
+
}
|
|
591
|
+
clear() {
|
|
592
|
+
this.#instanceId = uuid7();
|
|
593
|
+
this.#total.clear();
|
|
594
|
+
this.#sinceDelivery.clear();
|
|
595
|
+
this.#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
var PROCESS_DROPS = new DropCounts();
|
|
599
|
+
|
|
600
|
+
// src/sequence.ts
|
|
601
|
+
var lastSequence = 0;
|
|
602
|
+
function nextClockSequence() {
|
|
603
|
+
const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
|
|
604
|
+
lastSequence = Math.max(lastSequence + 1, nowMicros);
|
|
605
|
+
return lastSequence;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// src/sinks.ts
|
|
609
|
+
var REFUSAL_BODY_MAX_LEN = 500;
|
|
610
|
+
var REFUSAL_LOG_MS = 6e4;
|
|
611
|
+
var SinkClosedError = class extends Error {
|
|
612
|
+
name = "SinkClosedError";
|
|
613
|
+
};
|
|
614
|
+
function isSinkClosed(err) {
|
|
615
|
+
return err instanceof Error && err.name === "SinkClosedError";
|
|
616
|
+
}
|
|
617
|
+
var warnedClosed = /* @__PURE__ */ new WeakSet();
|
|
618
|
+
function droppedAfterClose(sink) {
|
|
619
|
+
PROCESS_DROPS.add("after_close");
|
|
620
|
+
if (warnedClosed.has(sink)) return;
|
|
621
|
+
warnedClosed.add(sink);
|
|
622
|
+
warn("baton: the sink is closed; further events are dropped.");
|
|
623
|
+
}
|
|
462
624
|
async function safeWrite(sink, event) {
|
|
463
625
|
try {
|
|
464
626
|
await sink.write(event);
|
|
465
627
|
} catch (err) {
|
|
466
|
-
|
|
628
|
+
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
629
|
+
PROCESS_DROPS.add("write_failed");
|
|
630
|
+
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
|
|
631
|
+
`);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
function stderrLine(message) {
|
|
635
|
+
process.stderr.write(`${message}
|
|
467
636
|
`);
|
|
637
|
+
}
|
|
638
|
+
function isTimerMs(value) {
|
|
639
|
+
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
640
|
+
}
|
|
641
|
+
function shutdownFlushTimeoutOption(given) {
|
|
642
|
+
if (isTimerMs(given)) return given;
|
|
643
|
+
if (given !== void 0) {
|
|
644
|
+
warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
|
|
645
|
+
}
|
|
646
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
647
|
+
}
|
|
648
|
+
function shutdownBudgetMs(sink) {
|
|
649
|
+
try {
|
|
650
|
+
if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
|
|
651
|
+
const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
|
|
652
|
+
if (isTimerMs(budget)) return budget;
|
|
653
|
+
} catch {
|
|
654
|
+
}
|
|
655
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
656
|
+
}
|
|
657
|
+
function callWithin(sink, method, ms) {
|
|
658
|
+
if (sink[method] === HttpSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
659
|
+
if (sink[method] === MultiSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
660
|
+
return sink[method]();
|
|
661
|
+
}
|
|
662
|
+
async function boundedSinkCall(sink, method, work = () => sink[method]()) {
|
|
663
|
+
const what = `${method}()`;
|
|
664
|
+
const budget = shutdownBudgetMs(sink);
|
|
665
|
+
const ms = budget + 250;
|
|
666
|
+
const settled = Promise.resolve().then(() => work(budget)).then(
|
|
667
|
+
() => void 0,
|
|
668
|
+
(err) => warn(`baton: ${what} failed: ${printable(err)}`)
|
|
669
|
+
);
|
|
670
|
+
if (await raceDeadline(settled, ms) === TIMED_OUT) {
|
|
671
|
+
warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);
|
|
468
672
|
}
|
|
469
673
|
}
|
|
470
674
|
var StdoutSink = class {
|
|
@@ -474,7 +678,7 @@ var StdoutSink = class {
|
|
|
474
678
|
this.stream = options.stream ?? process.stderr;
|
|
475
679
|
}
|
|
476
680
|
async write(event) {
|
|
477
|
-
if (this.closed) throw new
|
|
681
|
+
if (this.closed) throw new SinkClosedError("StdoutSink is closed");
|
|
478
682
|
this.stream.write(JSON.stringify(event) + "\n");
|
|
479
683
|
}
|
|
480
684
|
async flush() {
|
|
@@ -483,6 +687,59 @@ var StdoutSink = class {
|
|
|
483
687
|
this.closed = true;
|
|
484
688
|
}
|
|
485
689
|
};
|
|
690
|
+
var FileSink = class {
|
|
691
|
+
constructor(path) {
|
|
692
|
+
this.path = path;
|
|
693
|
+
}
|
|
694
|
+
path;
|
|
695
|
+
fd = null;
|
|
696
|
+
closed = false;
|
|
697
|
+
async write(event) {
|
|
698
|
+
if (this.closed) throw new SinkClosedError("FileSink is closed");
|
|
699
|
+
this.fd ??= openSync(this.path, "a");
|
|
700
|
+
writeSync(this.fd, JSON.stringify(event) + "\n");
|
|
701
|
+
}
|
|
702
|
+
async flush() {
|
|
703
|
+
}
|
|
704
|
+
async aclose() {
|
|
705
|
+
if (this.closed) return;
|
|
706
|
+
this.closed = true;
|
|
707
|
+
if (this.fd !== null) {
|
|
708
|
+
closeSync(this.fd);
|
|
709
|
+
this.fd = null;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
var MultiSink = class {
|
|
714
|
+
sinks;
|
|
715
|
+
constructor(sinks) {
|
|
716
|
+
if (sinks.length === 0) throw new Error("MultiSink requires at least one sink");
|
|
717
|
+
this.sinks = [...sinks];
|
|
718
|
+
}
|
|
719
|
+
write(event) {
|
|
720
|
+
return this.fanOut((sink) => sink.write(event));
|
|
721
|
+
}
|
|
722
|
+
flush() {
|
|
723
|
+
return this.flushWithin(Infinity);
|
|
724
|
+
}
|
|
725
|
+
aclose() {
|
|
726
|
+
return this.acloseWithin(Infinity);
|
|
727
|
+
}
|
|
728
|
+
flushWithin(ms) {
|
|
729
|
+
return this.fanOut((sink) => callWithin(sink, "flush", ms));
|
|
730
|
+
}
|
|
731
|
+
acloseWithin(ms) {
|
|
732
|
+
return this.fanOut((sink) => callWithin(sink, "aclose", ms));
|
|
733
|
+
}
|
|
734
|
+
async fanOut(op) {
|
|
735
|
+
const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
|
|
736
|
+
let errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
737
|
+
if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));
|
|
738
|
+
if (errors.length === 0) return;
|
|
739
|
+
if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];
|
|
740
|
+
throw new AggregateError(errors, "MultiSink fan-out failures");
|
|
741
|
+
}
|
|
742
|
+
};
|
|
486
743
|
var CircuitBreaker = class {
|
|
487
744
|
constructor(threshold, resetMs) {
|
|
488
745
|
this.threshold = threshold;
|
|
@@ -512,19 +769,43 @@ var HttpSink = class _HttpSink {
|
|
|
512
769
|
apiKey;
|
|
513
770
|
buffer = [];
|
|
514
771
|
bufferSize;
|
|
772
|
+
requestTimeoutMs;
|
|
773
|
+
shutdownFlushTimeoutMs;
|
|
774
|
+
/** Set when an exit pass ends; cleared once a normal drain empties the
|
|
775
|
+
* buffer, which means the process went on. */
|
|
776
|
+
exitPassRan = false;
|
|
777
|
+
/** Whether the exit pass warned about every event now buffered. */
|
|
778
|
+
unsentWarned = false;
|
|
515
779
|
maxRetries;
|
|
516
780
|
backoffBaseMs;
|
|
517
781
|
backoffMaxMs;
|
|
518
782
|
circuit;
|
|
519
783
|
fetchImpl;
|
|
520
784
|
overflowWarned = false;
|
|
521
|
-
|
|
785
|
+
/** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
|
|
786
|
+
refusals = /* @__PURE__ */ new Map();
|
|
787
|
+
/** Aborted once `aclose()` returns: nothing Baton started may keep the
|
|
788
|
+
* process alive after the vendor closed it. */
|
|
789
|
+
closing = new AbortController();
|
|
790
|
+
/** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */
|
|
791
|
+
stalledDrain = null;
|
|
792
|
+
skipWarnedFor = null;
|
|
793
|
+
closeOnce;
|
|
522
794
|
drainChain = Promise.resolve();
|
|
523
|
-
|
|
795
|
+
exitHooks = null;
|
|
796
|
+
/** The least time between two of this sink's loss reports. */
|
|
797
|
+
static reportIntervalMs = 6e4;
|
|
798
|
+
/** Totals only grow, so their sum tells whether they changed. */
|
|
799
|
+
reportedSum = 0;
|
|
800
|
+
lastReportAt = -Infinity;
|
|
801
|
+
reportsStopped = false;
|
|
802
|
+
reportInFlight = null;
|
|
524
803
|
constructor(url, options) {
|
|
525
804
|
this.url = url.replace(/\/+$/, "");
|
|
526
805
|
this.apiKey = options.apiKey;
|
|
527
806
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
807
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
808
|
+
this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
|
|
528
809
|
this.maxRetries = options.maxRetries ?? 3;
|
|
529
810
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
530
811
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -540,9 +821,7 @@ var HttpSink = class _HttpSink {
|
|
|
540
821
|
* ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
|
|
541
822
|
* hangs off `BatonHandle.sink` and off the resolved config, so
|
|
542
823
|
* `console.log(handle.sink)` or a structured logger serialising either one
|
|
543
|
-
*
|
|
544
|
-
* asserts the DSN's own string does not survive resolution: it does not, and
|
|
545
|
-
* the key was one field further down. Same treatment as the parsed DSN —
|
|
824
|
+
* would write a publishable key into the vendor's logs. Same treatment as the parsed DSN —
|
|
546
825
|
* `toJSON` for serialisers, the inspect symbol for `console.log`, and
|
|
547
826
|
* `Symbol.for` rather than importing `node:util`, since this package runs on
|
|
548
827
|
* runtimes that have no such module.
|
|
@@ -553,29 +832,84 @@ var HttpSink = class _HttpSink {
|
|
|
553
832
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
554
833
|
return this.toJSON();
|
|
555
834
|
}
|
|
835
|
+
get closed() {
|
|
836
|
+
return this.closing.signal.aborted;
|
|
837
|
+
}
|
|
556
838
|
async write(event) {
|
|
557
|
-
if (this.closed) throw new
|
|
839
|
+
if (this.closed) throw new SinkClosedError("HttpSink is closed");
|
|
558
840
|
this.enqueue(event);
|
|
841
|
+
this.unsentWarned = false;
|
|
559
842
|
void this.scheduleDrain();
|
|
560
|
-
this.
|
|
843
|
+
this.ensureExitHooksRegistered();
|
|
561
844
|
}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
await this.scheduleDrain();
|
|
845
|
+
flush() {
|
|
846
|
+
return this.flushWithin(Infinity);
|
|
565
847
|
}
|
|
566
|
-
|
|
848
|
+
/** A second call waits for the first (SPEC §11.2 rule 7). */
|
|
849
|
+
aclose() {
|
|
850
|
+
return this.acloseWithin(Infinity);
|
|
851
|
+
}
|
|
852
|
+
async flushWithin(ms) {
|
|
567
853
|
if (this.closed) return;
|
|
568
|
-
await this.flush();
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
854
|
+
await this.drainWithinBudget("flush()", Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
855
|
+
}
|
|
856
|
+
acloseWithin(ms) {
|
|
857
|
+
this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
858
|
+
return this.closeOnce;
|
|
859
|
+
}
|
|
860
|
+
async close(ms) {
|
|
861
|
+
this.stopReports();
|
|
862
|
+
await this.drainWithinBudget("aclose()", ms);
|
|
863
|
+
this.closing.abort();
|
|
864
|
+
if (this.buffer.length > 0) {
|
|
865
|
+
PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
|
|
866
|
+
warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
|
|
867
|
+
}
|
|
868
|
+
this.warnUnloggedRefusals("the sink closed");
|
|
869
|
+
if (this.exitHooks) {
|
|
870
|
+
process.off("beforeExit", this.exitHooks.beforeExit);
|
|
871
|
+
process.off("exit", this.exitHooks.exit);
|
|
872
|
+
this.exitHooks = null;
|
|
573
873
|
}
|
|
574
874
|
}
|
|
875
|
+
/** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
|
|
876
|
+
* never rejects. While an earlier wait's drain is still stuck, a flush
|
|
877
|
+
* returns at once, without queuing a pass, and a close gives it `ms`. The
|
|
878
|
+
* drain is not cancelled here, so after `flush()` it goes on sending;
|
|
879
|
+
* `aclose()` stops it. */
|
|
880
|
+
async drainWithinBudget(what, ms) {
|
|
881
|
+
if (this.stalledDrain) {
|
|
882
|
+
if (what === "aclose()") {
|
|
883
|
+
await raceDeadline(this.stalledDrain, ms);
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
if (this.skipWarnedFor !== this.stalledDrain) {
|
|
887
|
+
this.skipWarnedFor = this.stalledDrain;
|
|
888
|
+
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
|
|
889
|
+
}
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
const settled = this.scheduleDrain().catch(() => void 0);
|
|
893
|
+
if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
|
|
894
|
+
if (ms < this.shutdownFlushTimeoutMs) return;
|
|
895
|
+
const stalled = this.drainChain.catch(() => void 0);
|
|
896
|
+
this.stalledDrain = stalled;
|
|
897
|
+
void stalled.then(() => {
|
|
898
|
+
if (this.stalledDrain === stalled) this.stalledDrain = null;
|
|
899
|
+
});
|
|
900
|
+
if (what === "flush()") {
|
|
901
|
+
warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
/** A full buffer may already have pushed `event` out while it was being sent. */
|
|
905
|
+
dequeue(event) {
|
|
906
|
+
if (this.buffer[0] === event) this.buffer.shift();
|
|
907
|
+
}
|
|
575
908
|
enqueue(event) {
|
|
576
909
|
if (this.buffer.length >= this.bufferSize) {
|
|
910
|
+
PROCESS_DROPS.add("buffer_full");
|
|
577
911
|
if (!this.overflowWarned) {
|
|
578
|
-
|
|
912
|
+
warn(
|
|
579
913
|
`Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
|
|
580
914
|
);
|
|
581
915
|
this.overflowWarned = true;
|
|
@@ -597,18 +931,58 @@ var HttpSink = class _HttpSink {
|
|
|
597
931
|
return this.drainChain;
|
|
598
932
|
}
|
|
599
933
|
/** Best-effort flush when the process is about to exit without an
|
|
600
|
-
* explicit `aclose()`.
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
934
|
+
* explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
|
|
935
|
+
* both hooks: a vendor needing that guarantee must call `aclose()` from
|
|
936
|
+
* their own handler. */
|
|
937
|
+
ensureExitHooksRegistered() {
|
|
938
|
+
if (this.exitHooks) return;
|
|
939
|
+
const beforeExit = () => {
|
|
940
|
+
if (this.buffer.length === 0 || this.exitPassRan) {
|
|
941
|
+
this.warnUnloggedRefusals("process exiting");
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
this.drainChain = this.drainChain.then(
|
|
945
|
+
() => this.exitPass(),
|
|
946
|
+
() => this.exitPass()
|
|
947
|
+
);
|
|
610
948
|
};
|
|
611
|
-
|
|
949
|
+
const exit = () => {
|
|
950
|
+
try {
|
|
951
|
+
if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
|
|
952
|
+
this.warnUnloggedRefusals("process exiting", stderrLine);
|
|
953
|
+
} catch {
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
this.exitHooks = { beforeExit, exit };
|
|
957
|
+
process.on("beforeExit", beforeExit);
|
|
958
|
+
process.on("exit", exit);
|
|
959
|
+
}
|
|
960
|
+
/** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
|
|
961
|
+
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
962
|
+
async exitPass() {
|
|
963
|
+
const deadline = Date.now() + this.shutdownFlushTimeoutMs;
|
|
964
|
+
while (this.buffer.length > 0 && this.circuit.canRequest()) {
|
|
965
|
+
const timeLeft = deadline - Date.now();
|
|
966
|
+
if (timeLeft <= 0) break;
|
|
967
|
+
const event = this.buffer[0];
|
|
968
|
+
const body = this.encode(event);
|
|
969
|
+
if (body !== null) {
|
|
970
|
+
const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
|
|
971
|
+
if (outcome === "transient_failure") {
|
|
972
|
+
this.circuit.recordFailure();
|
|
973
|
+
break;
|
|
974
|
+
}
|
|
975
|
+
this.circuit.recordSuccess();
|
|
976
|
+
}
|
|
977
|
+
this.dequeue(event);
|
|
978
|
+
}
|
|
979
|
+
this.exitPassRan = true;
|
|
980
|
+
this.unsentWarned = true;
|
|
981
|
+
if (this.buffer.length > 0) warn(this.unsentAtExit());
|
|
982
|
+
this.warnUnloggedRefusals("process exiting");
|
|
983
|
+
}
|
|
984
|
+
unsentAtExit() {
|
|
985
|
+
return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
|
|
612
986
|
}
|
|
613
987
|
events_url() {
|
|
614
988
|
return `${this.url}/v0/events`;
|
|
@@ -621,38 +995,197 @@ var HttpSink = class _HttpSink {
|
|
|
621
995
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
622
996
|
return "transient_failure";
|
|
623
997
|
}
|
|
998
|
+
/** A refused event is otherwise dropped silently, which looks the same from
|
|
999
|
+
* the vendor's process as an accepted one. The collector's own message is
|
|
1000
|
+
* logged because it names the field at fault; it is capped and escaped
|
|
1001
|
+
* because it is a remote server's text landing in the vendor's log. */
|
|
1002
|
+
static async logRefusal(response, unlogged) {
|
|
1003
|
+
const detail = await _HttpSink.readHead(response).then(
|
|
1004
|
+
(text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
|
|
1005
|
+
() => "<unreadable>"
|
|
1006
|
+
);
|
|
1007
|
+
warn(
|
|
1008
|
+
`baton: collector REFUSED an event and it has been dropped (HTTP ${response.status}): ${detail} \u2014 the event is gone; nothing retries a 4xx.` + (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : "")
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
warnUnloggedRefusals(when, emit2 = warn) {
|
|
1012
|
+
let total = 0;
|
|
1013
|
+
for (const seen of this.refusals.values()) {
|
|
1014
|
+
total += seen.unlogged;
|
|
1015
|
+
seen.unlogged = 0;
|
|
1016
|
+
}
|
|
1017
|
+
if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
|
|
1018
|
+
}
|
|
1019
|
+
/** How many refusals with `status` went unlogged before this one, or `null`
|
|
1020
|
+
* when this one goes unlogged too. */
|
|
1021
|
+
refusalToLog(status) {
|
|
1022
|
+
const now = performance.now();
|
|
1023
|
+
const seen = this.refusals.get(status);
|
|
1024
|
+
if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
|
|
1025
|
+
seen.unlogged++;
|
|
1026
|
+
return null;
|
|
1027
|
+
}
|
|
1028
|
+
this.refusals.set(status, { loggedAt: now, unlogged: 0 });
|
|
1029
|
+
return seen?.unlogged ?? 0;
|
|
1030
|
+
}
|
|
1031
|
+
/** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
|
|
1032
|
+
* cancelled unread, so a large error page does not hold the drain. */
|
|
1033
|
+
static async readHead(response) {
|
|
1034
|
+
const reader = response.body?.getReader();
|
|
1035
|
+
if (reader === void 0) return "";
|
|
1036
|
+
const decoder = new TextDecoder();
|
|
1037
|
+
let text = "";
|
|
1038
|
+
try {
|
|
1039
|
+
while (text.length < REFUSAL_BODY_MAX_LEN * 2) {
|
|
1040
|
+
const { done, value } = await reader.read();
|
|
1041
|
+
if (done) return text + decoder.decode();
|
|
1042
|
+
text += decoder.decode(value, { stream: true });
|
|
1043
|
+
}
|
|
1044
|
+
return text;
|
|
1045
|
+
} finally {
|
|
1046
|
+
void reader.cancel().catch(() => {
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
624
1050
|
async drainLocked() {
|
|
625
1051
|
while (this.buffer.length > 0) {
|
|
626
|
-
if (!this.circuit.canRequest()) return;
|
|
1052
|
+
if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
|
|
627
1053
|
const event = this.buffer[0];
|
|
628
1054
|
const outcome = await this.sendWithRetry(event);
|
|
629
1055
|
if (outcome === "success" || outcome === "permanent_failure") {
|
|
630
|
-
this.
|
|
1056
|
+
this.dequeue(event);
|
|
631
1057
|
this.circuit.recordSuccess();
|
|
1058
|
+
if (outcome === "success") {
|
|
1059
|
+
PROCESS_DROPS.logRecovery();
|
|
1060
|
+
this.maybeReport(event);
|
|
1061
|
+
}
|
|
1062
|
+
} else if (outcome === "unencodable") {
|
|
1063
|
+
this.dequeue(event);
|
|
632
1064
|
} else {
|
|
633
1065
|
this.circuit.recordFailure();
|
|
634
1066
|
return;
|
|
635
1067
|
}
|
|
636
1068
|
}
|
|
1069
|
+
this.exitPassRan = false;
|
|
1070
|
+
}
|
|
1071
|
+
/** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
|
|
1072
|
+
* drain and outside the buffer, so it never delays an event and is never
|
|
1073
|
+
* counted as one. */
|
|
1074
|
+
maybeReport({ tenant_id, vendor_id, consent_token }) {
|
|
1075
|
+
const now = performance.now();
|
|
1076
|
+
if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
const totals = PROCESS_DROPS.total();
|
|
1080
|
+
const sum = Object.values(totals).reduce((a, b) => a + b, 0);
|
|
1081
|
+
if (sum === this.reportedSum) return;
|
|
1082
|
+
this.lastReportAt = now;
|
|
1083
|
+
const abort = new AbortController();
|
|
1084
|
+
this.reportInFlight = abort;
|
|
1085
|
+
const envelope = { tenant_id, vendor_id, consent_token };
|
|
1086
|
+
void this.sendReport(envelope, totals, sum, abort).finally(() => {
|
|
1087
|
+
this.reportInFlight = null;
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
stopReports() {
|
|
1091
|
+
this.reportsStopped = true;
|
|
1092
|
+
this.reportInFlight?.abort();
|
|
1093
|
+
}
|
|
1094
|
+
async sendReport(envelope, totals, sum, abort) {
|
|
1095
|
+
const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
|
|
1096
|
+
try {
|
|
1097
|
+
const report = ClientReportEventSchema.parse({
|
|
1098
|
+
...envelope,
|
|
1099
|
+
session_id: PROCESS_DROPS.instanceId,
|
|
1100
|
+
sequence_number: nextClockSequence(),
|
|
1101
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1102
|
+
payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
|
|
1103
|
+
});
|
|
1104
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1105
|
+
method: "POST",
|
|
1106
|
+
headers: this.authHeaders(),
|
|
1107
|
+
body: JSON.stringify(report),
|
|
1108
|
+
signal: abort.signal
|
|
1109
|
+
});
|
|
1110
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1111
|
+
if (response.status === 400 || response.status === 422) this.reportsStopped = true;
|
|
1112
|
+
else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
|
|
1113
|
+
} catch {
|
|
1114
|
+
} finally {
|
|
1115
|
+
clearTimeout(timer);
|
|
1116
|
+
}
|
|
637
1117
|
}
|
|
638
1118
|
async sendWithRetry(event) {
|
|
639
|
-
const
|
|
640
|
-
|
|
641
|
-
const body = JSON.stringify(event);
|
|
1119
|
+
const body = this.encode(event);
|
|
1120
|
+
if (body === null) return "unencodable";
|
|
642
1121
|
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
const outcome = _HttpSink.classifyStatus(response.status);
|
|
646
|
-
if (outcome !== "transient_failure") return outcome;
|
|
647
|
-
} catch {
|
|
648
|
-
}
|
|
1122
|
+
const outcome = await this.postOnce(body, this.requestTimeoutMs);
|
|
1123
|
+
if (outcome !== "transient_failure") return outcome;
|
|
649
1124
|
if (attempt < this.maxRetries) {
|
|
650
1125
|
const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
|
|
651
|
-
await
|
|
1126
|
+
await this.sleepUnlessClosed(backoff);
|
|
1127
|
+
if (this.closing.signal.aborted) return "transient_failure";
|
|
652
1128
|
}
|
|
653
1129
|
}
|
|
654
1130
|
return "transient_failure";
|
|
655
1131
|
}
|
|
1132
|
+
/** `null`, with a warning, for an event `JSON.stringify` rejects. */
|
|
1133
|
+
encode(event) {
|
|
1134
|
+
try {
|
|
1135
|
+
return JSON.stringify(event);
|
|
1136
|
+
} catch (err) {
|
|
1137
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1138
|
+
warn(
|
|
1139
|
+
`baton: a ${event.event_type} event could not be encoded and has been dropped (${err?.name ?? "Error"}) \u2014 the event is gone; the events after it are still sent.`
|
|
1140
|
+
);
|
|
1141
|
+
return null;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
sleepUnlessClosed(ms) {
|
|
1145
|
+
if (this.closed) return Promise.resolve();
|
|
1146
|
+
return new Promise((resolve) => {
|
|
1147
|
+
const done = () => {
|
|
1148
|
+
clearTimeout(timer);
|
|
1149
|
+
this.closing.signal.removeEventListener("abort", done);
|
|
1150
|
+
resolve();
|
|
1151
|
+
};
|
|
1152
|
+
const timer = setTimeout(done, ms);
|
|
1153
|
+
this.closing.signal.addEventListener("abort", done);
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
/** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
|
|
1157
|
+
* is missing before Node 20.3, and on some later versions it keeps every
|
|
1158
|
+
* combined signal alive as long as the long-lived `closing` signal. */
|
|
1159
|
+
async postOnce(body, timeoutMs) {
|
|
1160
|
+
const request = new AbortController();
|
|
1161
|
+
const abort = () => request.abort();
|
|
1162
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
1163
|
+
this.closing.signal.addEventListener("abort", abort);
|
|
1164
|
+
try {
|
|
1165
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1166
|
+
method: "POST",
|
|
1167
|
+
headers: this.authHeaders(),
|
|
1168
|
+
body,
|
|
1169
|
+
signal: request.signal
|
|
1170
|
+
});
|
|
1171
|
+
const outcome = _HttpSink.classifyStatus(response.status);
|
|
1172
|
+
if (outcome === "permanent_failure") {
|
|
1173
|
+
PROCESS_DROPS.add("refused");
|
|
1174
|
+
const unlogged = this.refusalToLog(response.status);
|
|
1175
|
+
if (unlogged !== null) {
|
|
1176
|
+
await _HttpSink.logRefusal(response, unlogged);
|
|
1177
|
+
return outcome;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1181
|
+
return outcome;
|
|
1182
|
+
} catch {
|
|
1183
|
+
return "transient_failure";
|
|
1184
|
+
} finally {
|
|
1185
|
+
clearTimeout(timer);
|
|
1186
|
+
this.closing.signal.removeEventListener("abort", abort);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
656
1189
|
};
|
|
657
1190
|
|
|
658
1191
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -664,11 +1197,6 @@ import { z as z2 } from "zod";
|
|
|
664
1197
|
// src/metaCoordinates.ts
|
|
665
1198
|
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
666
1199
|
var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
667
|
-
function isPlainObject2(value) {
|
|
668
|
-
if (typeof value !== "object" || value === null) return false;
|
|
669
|
-
const proto = Object.getPrototypeOf(value);
|
|
670
|
-
return proto === Object.prototype || proto === null;
|
|
671
|
-
}
|
|
672
1200
|
function toOneDecimal(value) {
|
|
673
1201
|
const magnitude = Math.abs(value);
|
|
674
1202
|
if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
|
|
@@ -689,7 +1217,7 @@ function roundCoordinate(value) {
|
|
|
689
1217
|
}
|
|
690
1218
|
function walk(value, depth) {
|
|
691
1219
|
if (depth >= DEPTH_LIMIT) return value;
|
|
692
|
-
if (
|
|
1220
|
+
if (isPlainObject(value)) {
|
|
693
1221
|
const out = {};
|
|
694
1222
|
for (const [k, v] of Object.entries(value)) {
|
|
695
1223
|
const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
|
|
@@ -706,126 +1234,6 @@ function roundMetaCoordinates(meta) {
|
|
|
706
1234
|
return walk(meta, 0);
|
|
707
1235
|
}
|
|
708
1236
|
|
|
709
|
-
// src/_text.ts
|
|
710
|
-
function exceedsCodePoints(value, max) {
|
|
711
|
-
if (value.length <= max) return false;
|
|
712
|
-
if (value.length > 2 * max) return true;
|
|
713
|
-
return [...value].length > max;
|
|
714
|
-
}
|
|
715
|
-
function capCodePoints(value, max) {
|
|
716
|
-
if (value.length <= max) return value;
|
|
717
|
-
return [...value].slice(0, max).join("");
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
// src/identity.ts
|
|
721
|
-
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
722
|
-
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
723
|
-
var PRINCIPAL_FORM_RAW = "raw";
|
|
724
|
-
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
725
|
-
var DISPLAY_NAME_MAX_LEN = 128;
|
|
726
|
-
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
727
|
-
function wireDisplayName(value) {
|
|
728
|
-
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
729
|
-
if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
|
|
730
|
-
return value;
|
|
731
|
-
}
|
|
732
|
-
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
733
|
-
var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
734
|
-
var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
|
|
735
|
-
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
736
|
-
function pythonStrip(value) {
|
|
737
|
-
return value.replace(PYTHON_STRIP, "");
|
|
738
|
-
}
|
|
739
|
-
function usableId(id) {
|
|
740
|
-
if (typeof id !== "string") return false;
|
|
741
|
-
if (LONE_SURROGATE.test(id)) return false;
|
|
742
|
-
if (id.includes("\0")) return false;
|
|
743
|
-
return pythonStrip(id) !== "";
|
|
744
|
-
}
|
|
745
|
-
function readIdentity(result, idKey) {
|
|
746
|
-
if (result === null || typeof result !== "object") return null;
|
|
747
|
-
const candidate = result;
|
|
748
|
-
const id = candidate[idKey];
|
|
749
|
-
if (!usableId(id)) return null;
|
|
750
|
-
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
751
|
-
return { id, form: candidate.form, displayName };
|
|
752
|
-
}
|
|
753
|
-
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
754
|
-
function callerFor(result, warn4) {
|
|
755
|
-
try {
|
|
756
|
-
return readCaller(result, warn4);
|
|
757
|
-
} catch {
|
|
758
|
-
warn4("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
759
|
-
return NO_CALLER;
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
function readCaller(result, warn4) {
|
|
763
|
-
if (result === void 0 || result === null) return NO_CALLER;
|
|
764
|
-
if (typeof result !== "object") {
|
|
765
|
-
warn4("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
766
|
-
return NO_CALLER;
|
|
767
|
-
}
|
|
768
|
-
if (!("principalId" in result) && !("organization" in result)) {
|
|
769
|
-
if ("organizationId" in result) {
|
|
770
|
-
return { principal: null, organization: identityFor(result, "organization", warn4) };
|
|
771
|
-
}
|
|
772
|
-
if (typeof result.userId === "string") {
|
|
773
|
-
warn4(
|
|
774
|
-
"user-id",
|
|
775
|
-
"returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until it returns the new key."
|
|
776
|
-
);
|
|
777
|
-
} else {
|
|
778
|
-
warn4("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
779
|
-
}
|
|
780
|
-
return NO_CALLER;
|
|
781
|
-
}
|
|
782
|
-
if ("organizationId" in result) {
|
|
783
|
-
warn4("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
784
|
-
}
|
|
785
|
-
const nested = result.organization;
|
|
786
|
-
return {
|
|
787
|
-
principal: identityFor(result, "principal", warn4),
|
|
788
|
-
organization: nested == null ? null : identityFor(nested, "organization", warn4)
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
function identityFor(value, member, warn4) {
|
|
792
|
-
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
793
|
-
const identity = readIdentity(value, idKey);
|
|
794
|
-
if (identity === null) {
|
|
795
|
-
warn4(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
796
|
-
return null;
|
|
797
|
-
}
|
|
798
|
-
return identityWire(
|
|
799
|
-
identity.id,
|
|
800
|
-
identity.form,
|
|
801
|
-
identity.displayName,
|
|
802
|
-
(form) => warn4(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
803
|
-
);
|
|
804
|
-
}
|
|
805
|
-
function describeForm(form) {
|
|
806
|
-
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
807
|
-
}
|
|
808
|
-
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
809
|
-
let form = PRINCIPAL_FORM_RAW;
|
|
810
|
-
if (stated !== void 0) {
|
|
811
|
-
if (PRINCIPAL_FORMS.has(stated)) {
|
|
812
|
-
form = stated;
|
|
813
|
-
} else {
|
|
814
|
-
onUnregisteredForm?.(stated);
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
const wire = {
|
|
818
|
-
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
819
|
-
// an astral id cut at the boundary would ship a lone surrogate.
|
|
820
|
-
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
821
|
-
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
822
|
-
form
|
|
823
|
-
};
|
|
824
|
-
const name = wireDisplayName(displayName);
|
|
825
|
-
if (name !== null) wire.display_name = name;
|
|
826
|
-
return wire;
|
|
827
|
-
}
|
|
828
|
-
|
|
829
1237
|
// src/integrations/mcp/llmText.ts
|
|
830
1238
|
var REPORT_POINTER_TEMPLATE = (vendorDisplayName, annotationToolName) => `Use \`${annotationToolName}\` to report a ${vendorDisplayName} tool call that went wrong, or a request no tool covers; its description says when and how.`;
|
|
831
1239
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -897,14 +1305,14 @@ var OURS_STARTS = [
|
|
|
897
1305
|
];
|
|
898
1306
|
function endsInOurs(current2, vendor) {
|
|
899
1307
|
if (typeof current2 !== "string") return false;
|
|
900
|
-
const prefix = typeof vendor === "string" && vendor
|
|
1308
|
+
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
901
1309
|
|
|
902
1310
|
` : "";
|
|
903
1311
|
if (!current2.startsWith(prefix)) return false;
|
|
904
1312
|
const rest = current2.slice(prefix.length);
|
|
905
1313
|
return OURS_STARTS.some((start) => start.test(rest));
|
|
906
1314
|
}
|
|
907
|
-
function withVendorInstructions(server, ours,
|
|
1315
|
+
function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
|
|
908
1316
|
const holder = server;
|
|
909
1317
|
const current2 = holder._instructions;
|
|
910
1318
|
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
@@ -912,12 +1320,12 @@ function withVendorInstructions(server, ours, warn4 = (message) => process.stder
|
|
|
912
1320
|
vendor = current2;
|
|
913
1321
|
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
914
1322
|
}
|
|
915
|
-
if (typeof vendor !== "string" ||
|
|
1323
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
916
1324
|
const combined = `${vendor}
|
|
917
1325
|
|
|
918
1326
|
${ours}`;
|
|
919
1327
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
920
|
-
|
|
1328
|
+
warn3(
|
|
921
1329
|
`baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there
|
|
922
1330
|
`
|
|
923
1331
|
);
|
|
@@ -931,17 +1339,17 @@ var SUFFIX = "_annotate";
|
|
|
931
1339
|
var SLUG_CAP = 30;
|
|
932
1340
|
var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
|
|
933
1341
|
var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
|
|
1342
|
+
var SEPARATORS = "\\x1c-\\x1f";
|
|
1343
|
+
var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
|
|
1344
|
+
function pythonStrip(value) {
|
|
1345
|
+
return stripEdges(value, PYTHON_SPACE);
|
|
1346
|
+
}
|
|
934
1347
|
function isLibraryPlaceholder(serverName, className) {
|
|
935
1348
|
const stripped = pythonStrip(serverName);
|
|
936
1349
|
if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
|
|
937
1350
|
const stem = stripped.replace(RANDOM_SUFFIX, "");
|
|
938
1351
|
return stem !== stripped && stem === className;
|
|
939
1352
|
}
|
|
940
|
-
function warn(message) {
|
|
941
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
942
|
-
process.emitWarning(message);
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
1353
|
function usableServerName(read) {
|
|
946
1354
|
let name;
|
|
947
1355
|
let className;
|
|
@@ -1015,13 +1423,117 @@ async function emit(sink, build) {
|
|
|
1015
1423
|
try {
|
|
1016
1424
|
event = build();
|
|
1017
1425
|
} catch (err) {
|
|
1018
|
-
|
|
1426
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1427
|
+
process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
|
|
1019
1428
|
`);
|
|
1020
1429
|
return;
|
|
1021
1430
|
}
|
|
1022
1431
|
await safeWrite(sink, event);
|
|
1023
1432
|
}
|
|
1024
1433
|
|
|
1434
|
+
// src/identity.ts
|
|
1435
|
+
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
1436
|
+
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
1437
|
+
var PRINCIPAL_FORM_RAW = "raw";
|
|
1438
|
+
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
1439
|
+
var DISPLAY_NAME_MAX_LEN = 128;
|
|
1440
|
+
function wireDisplayName(value) {
|
|
1441
|
+
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
1442
|
+
if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
|
|
1443
|
+
return value;
|
|
1444
|
+
}
|
|
1445
|
+
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
1446
|
+
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
1447
|
+
function usableId(id) {
|
|
1448
|
+
if (typeof id !== "string") return false;
|
|
1449
|
+
if (LONE_SURROGATE.test(id)) return false;
|
|
1450
|
+
if (id.includes("\0")) return false;
|
|
1451
|
+
return !isBlank(id);
|
|
1452
|
+
}
|
|
1453
|
+
function readIdentity(result, idKey) {
|
|
1454
|
+
if (result === null || typeof result !== "object") return null;
|
|
1455
|
+
const candidate = result;
|
|
1456
|
+
const id = candidate[idKey];
|
|
1457
|
+
if (!usableId(id)) return null;
|
|
1458
|
+
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
1459
|
+
return { id, form: candidate.form, displayName };
|
|
1460
|
+
}
|
|
1461
|
+
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
1462
|
+
function callerFor(result, warn3) {
|
|
1463
|
+
try {
|
|
1464
|
+
return readCaller(result, warn3);
|
|
1465
|
+
} catch {
|
|
1466
|
+
warn3("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
1467
|
+
return NO_CALLER;
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
function readCaller(result, warn3) {
|
|
1471
|
+
if (result === void 0 || result === null) return NO_CALLER;
|
|
1472
|
+
if (typeof result !== "object") {
|
|
1473
|
+
warn3("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
1474
|
+
return NO_CALLER;
|
|
1475
|
+
}
|
|
1476
|
+
if (!("principalId" in result) && !("organization" in result)) {
|
|
1477
|
+
if ("organizationId" in result) {
|
|
1478
|
+
return { principal: null, organization: identityFor(result, "organization", warn3) };
|
|
1479
|
+
}
|
|
1480
|
+
if (typeof result.userId === "string") {
|
|
1481
|
+
warn3(
|
|
1482
|
+
"user-id",
|
|
1483
|
+
"returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until it returns the new key."
|
|
1484
|
+
);
|
|
1485
|
+
} else {
|
|
1486
|
+
warn3("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
1487
|
+
}
|
|
1488
|
+
return NO_CALLER;
|
|
1489
|
+
}
|
|
1490
|
+
if ("organizationId" in result) {
|
|
1491
|
+
warn3("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
1492
|
+
}
|
|
1493
|
+
const nested = result.organization;
|
|
1494
|
+
return {
|
|
1495
|
+
principal: identityFor(result, "principal", warn3),
|
|
1496
|
+
organization: nested == null ? null : identityFor(nested, "organization", warn3)
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
function identityFor(value, member, warn3) {
|
|
1500
|
+
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
1501
|
+
const identity = readIdentity(value, idKey);
|
|
1502
|
+
if (identity === null) {
|
|
1503
|
+
warn3(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
1504
|
+
return null;
|
|
1505
|
+
}
|
|
1506
|
+
return identityWire(
|
|
1507
|
+
identity.id,
|
|
1508
|
+
identity.form,
|
|
1509
|
+
identity.displayName,
|
|
1510
|
+
(form) => warn3(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
1511
|
+
);
|
|
1512
|
+
}
|
|
1513
|
+
function describeForm(form) {
|
|
1514
|
+
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
1515
|
+
}
|
|
1516
|
+
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
1517
|
+
let form = PRINCIPAL_FORM_RAW;
|
|
1518
|
+
if (stated !== void 0) {
|
|
1519
|
+
if (PRINCIPAL_FORMS.has(stated)) {
|
|
1520
|
+
form = stated;
|
|
1521
|
+
} else {
|
|
1522
|
+
onUnregisteredForm?.(stated);
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
const wire = {
|
|
1526
|
+
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
1527
|
+
// an astral id cut at the boundary would ship a lone surrogate.
|
|
1528
|
+
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
1529
|
+
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
1530
|
+
form
|
|
1531
|
+
};
|
|
1532
|
+
const name = wireDisplayName(displayName);
|
|
1533
|
+
if (name !== null) wire.display_name = name;
|
|
1534
|
+
return wire;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1025
1537
|
// src/integrations/mcp/mcpTypes.ts
|
|
1026
1538
|
function extraAuthInfo(extra) {
|
|
1027
1539
|
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
@@ -1079,24 +1591,14 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
|
1079
1591
|
};
|
|
1080
1592
|
}
|
|
1081
1593
|
var HOOK_TIMEOUT_MS = 5e3;
|
|
1082
|
-
var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
|
|
1083
1594
|
async function withinHookBudget(answer) {
|
|
1084
1595
|
if (!isThenable(answer)) return answer;
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
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
|
-
}
|
|
1596
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
1597
|
+
if (first !== TIMED_OUT) return first;
|
|
1598
|
+
warn(
|
|
1599
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1600
|
+
);
|
|
1601
|
+
return null;
|
|
1100
1602
|
}
|
|
1101
1603
|
var warned = /* @__PURE__ */ new Set();
|
|
1102
1604
|
function warnOnce(key, message) {
|
|
@@ -1125,7 +1627,7 @@ function scrubOrNull(scrubber, value, field) {
|
|
|
1125
1627
|
if (!warned2.has(field)) {
|
|
1126
1628
|
warned2.add(field);
|
|
1127
1629
|
process.stderr.write(
|
|
1128
|
-
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${
|
|
1630
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
|
|
1129
1631
|
`
|
|
1130
1632
|
);
|
|
1131
1633
|
}
|
|
@@ -1224,9 +1726,9 @@ function registeredHeaders(input) {
|
|
|
1224
1726
|
}
|
|
1225
1727
|
return out;
|
|
1226
1728
|
}
|
|
1227
|
-
function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
1729
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
1228
1730
|
return assemble(
|
|
1229
|
-
orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
|
|
1731
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
1230
1732
|
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
1231
1733
|
);
|
|
1232
1734
|
}
|
|
@@ -1234,16 +1736,19 @@ function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
|
1234
1736
|
// src/integrations/mcp/sessionResolution.ts
|
|
1235
1737
|
async function resolveSessionId(fallbackSessionId, extra) {
|
|
1236
1738
|
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
1237
|
-
return { sessionId: extra.sessionId, origin: "observed" };
|
|
1739
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
1238
1740
|
}
|
|
1239
1741
|
const fromHeader = sessionIdFromHeader(extra);
|
|
1240
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
|
|
1241
|
-
|
|
1742
|
+
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
1743
|
+
if (observeTransport(extra) === "http") {
|
|
1744
|
+
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
1745
|
+
}
|
|
1746
|
+
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
1242
1747
|
}
|
|
1243
1748
|
function sessionIdFromHeader(extra) {
|
|
1244
1749
|
try {
|
|
1245
|
-
const value = extraHeaders(extra)?.get("mcp-session-id")
|
|
1246
|
-
return value ? value : null;
|
|
1750
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
1751
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
1247
1752
|
} catch {
|
|
1248
1753
|
return null;
|
|
1249
1754
|
}
|
|
@@ -1252,7 +1757,7 @@ function sessionIdFromHeader(extra) {
|
|
|
1252
1757
|
// src/integrations/mcp/annotation.ts
|
|
1253
1758
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
1254
1759
|
function isReport(whatHappened) {
|
|
1255
|
-
return typeof whatHappened === "string" && whatHappened
|
|
1760
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
1256
1761
|
}
|
|
1257
1762
|
function registerAnnotationTool(server, options) {
|
|
1258
1763
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
@@ -1295,7 +1800,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1295
1800
|
meta ? roundMetaCoordinates(meta) : null,
|
|
1296
1801
|
"_meta"
|
|
1297
1802
|
);
|
|
1298
|
-
const
|
|
1803
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
1299
1804
|
const caller = await resolveCaller(
|
|
1300
1805
|
options.resolvePrincipal,
|
|
1301
1806
|
{ extra, toolName: name, arguments: args }
|
|
@@ -1305,14 +1810,14 @@ function registerAnnotationTool(server, options) {
|
|
|
1305
1810
|
() => AnnotationEventSchema.parse({
|
|
1306
1811
|
tenant_id: options.tenantId,
|
|
1307
1812
|
vendor_id: options.vendorId,
|
|
1308
|
-
session_id: sessionId,
|
|
1309
|
-
sequence_number: options.counter.
|
|
1813
|
+
session_id: session.sessionId,
|
|
1814
|
+
sequence_number: options.counter.nextFor(session),
|
|
1310
1815
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1311
1816
|
consent_token: options.consentToken,
|
|
1312
1817
|
principal: caller.principal,
|
|
1313
1818
|
organization: caller.organization,
|
|
1314
1819
|
transport_observed: observeTransport(extra),
|
|
1315
|
-
session_id_origin: origin,
|
|
1820
|
+
session_id_origin: session.origin,
|
|
1316
1821
|
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1317
1822
|
runtime_meta: scrubbedMeta,
|
|
1318
1823
|
payload: {
|
|
@@ -1339,7 +1844,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1339
1844
|
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
1340
1845
|
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
1341
1846
|
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
1342
|
-
var NOT_IN_A_KEY = /[\x00\n\r]/;
|
|
1847
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
1343
1848
|
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
1344
1849
|
var SECRET_PREFIX = "baton_sk_";
|
|
1345
1850
|
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
@@ -1350,11 +1855,6 @@ function containsKey(value) {
|
|
|
1350
1855
|
return sweep(value) !== value;
|
|
1351
1856
|
}
|
|
1352
1857
|
var BARE_KEY_HINT = "this looks like a bare key, not a DSN \u2014 copy the full value from /account, which starts with https:// and ends with your server's name";
|
|
1353
|
-
function warn2(message) {
|
|
1354
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1355
|
-
process.emitWarning(message);
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
1858
|
function splitDsn(raw) {
|
|
1359
1859
|
const schemeEnd = raw.indexOf("://");
|
|
1360
1860
|
if (schemeEnd === -1) return null;
|
|
@@ -1414,7 +1914,7 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1414
1914
|
const ambient = dsnFromEnvironment();
|
|
1415
1915
|
if (ambient === void 0) return void 0;
|
|
1416
1916
|
if (conflicts.length > 0) {
|
|
1417
|
-
|
|
1917
|
+
warn(
|
|
1418
1918
|
`baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(", ")} directly, so BATON_DSN is being IGNORED and these events are NOT going to the collector it names. Remove the explicit value to use it, or unset BATON_DSN if it was meant for a different server.`
|
|
1419
1919
|
);
|
|
1420
1920
|
return void 0;
|
|
@@ -1422,10 +1922,8 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1422
1922
|
return ambient;
|
|
1423
1923
|
}
|
|
1424
1924
|
function parseDsn(raw) {
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
}
|
|
1428
|
-
const dsn = raw.trim();
|
|
1925
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
1926
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
1429
1927
|
if (looksLikeAKey(dsn)) {
|
|
1430
1928
|
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
1431
1929
|
}
|
|
@@ -1451,7 +1949,7 @@ function parseDsn(raw) {
|
|
|
1451
1949
|
}
|
|
1452
1950
|
if (NOT_IN_A_KEY.test(key)) {
|
|
1453
1951
|
fail(
|
|
1454
|
-
`dsn ${safe} has a line break or a null inside its key \u2014
|
|
1952
|
+
`dsn ${safe} has a tab, a line break or a null inside its key \u2014 no key from /account contains one, so this DSN could not have worked. Check for a line wrap where the value was copied.`
|
|
1455
1953
|
);
|
|
1456
1954
|
}
|
|
1457
1955
|
if (key.includes(":")) {
|
|
@@ -1510,7 +2008,7 @@ function parseDsn(raw) {
|
|
|
1510
2008
|
);
|
|
1511
2009
|
}
|
|
1512
2010
|
if (key.startsWith(SECRET_PREFIX)) {
|
|
1513
|
-
|
|
2011
|
+
warn(
|
|
1514
2012
|
`baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
|
|
1515
2013
|
);
|
|
1516
2014
|
}
|
|
@@ -1549,7 +2047,7 @@ function requestSideFailureKind(entry, validation) {
|
|
|
1549
2047
|
if (entry.enabled === false) return "tool_disabled";
|
|
1550
2048
|
if (validation === "rejected") return "invalid_argument";
|
|
1551
2049
|
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
1552
|
-
return
|
|
2050
|
+
return REFUSED;
|
|
1553
2051
|
}
|
|
1554
2052
|
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
1555
2053
|
function isErrorResult(value) {
|
|
@@ -1568,7 +2066,7 @@ function errorText(value) {
|
|
|
1568
2066
|
for (const part of content) {
|
|
1569
2067
|
const text = part?.text;
|
|
1570
2068
|
if (typeof text !== "string") continue;
|
|
1571
|
-
const trimmed = text
|
|
2069
|
+
const trimmed = stripWhiteSpace(text);
|
|
1572
2070
|
if (trimmed) parts.push(trimmed);
|
|
1573
2071
|
}
|
|
1574
2072
|
} catch {
|
|
@@ -1748,7 +2246,7 @@ var SWITCH = "BATON_DISABLED";
|
|
|
1748
2246
|
var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
|
|
1749
2247
|
function captureDisabled() {
|
|
1750
2248
|
const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
|
|
1751
|
-
if (value !== void 0 && !OFF_VALUES.has(value
|
|
2249
|
+
if (value !== void 0 && !OFF_VALUES.has(stripWhiteSpace(value).toLowerCase())) {
|
|
1752
2250
|
return SWITCH;
|
|
1753
2251
|
}
|
|
1754
2252
|
return null;
|
|
@@ -1775,13 +2273,31 @@ var DisabledSink = class {
|
|
|
1775
2273
|
}
|
|
1776
2274
|
};
|
|
1777
2275
|
|
|
2276
|
+
// src/integrations/mcp/inputRequired.ts
|
|
2277
|
+
function isInputRequired(result) {
|
|
2278
|
+
try {
|
|
2279
|
+
return isRecord(result) && result.resultType === "input_required";
|
|
2280
|
+
} catch {
|
|
2281
|
+
return false;
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
function resumesPausedCall(extra) {
|
|
2285
|
+
try {
|
|
2286
|
+
const req = extra?.mcpReq;
|
|
2287
|
+
if (req === void 0) return false;
|
|
2288
|
+
return req.inputResponses !== void 0 || req.requestState?.() !== void 0;
|
|
2289
|
+
} catch {
|
|
2290
|
+
return false;
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
|
|
1778
2294
|
// src/integrations/mcp/handle.ts
|
|
1779
2295
|
var BatonHandle = class {
|
|
1780
2296
|
sink;
|
|
1781
2297
|
vendorId;
|
|
1782
|
-
/**
|
|
1783
|
-
* when no
|
|
1784
|
-
*
|
|
2298
|
+
/** The install's own session id: what stdio and in-memory calls, and the
|
|
2299
|
+
* surface snapshot, carry when no session id resolves. A call over HTTP
|
|
2300
|
+
* with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */
|
|
1785
2301
|
sessionId;
|
|
1786
2302
|
/** The resolved annotation tool name: `BatonConfig.annotationToolName` if
|
|
1787
2303
|
* set, else derived from the server's own name (`{slug}_annotate`), else
|
|
@@ -1793,19 +2309,25 @@ var BatonHandle = class {
|
|
|
1793
2309
|
this.sessionId = options.sessionId;
|
|
1794
2310
|
this.annotationToolName = options.annotationToolName;
|
|
1795
2311
|
}
|
|
1796
|
-
/** Flush any pending events held by the sink.
|
|
2312
|
+
/** Flush any pending events held by the sink. Never rejects; returns within
|
|
2313
|
+
* the shutdown budget (SPEC §11.2 rule 7). */
|
|
1797
2314
|
async flush() {
|
|
1798
|
-
await this.sink
|
|
2315
|
+
await boundedSinkCall(this.sink, "flush");
|
|
1799
2316
|
}
|
|
1800
|
-
/** Flush and release sink resources
|
|
2317
|
+
/** Flush and release sink resources, on the same terms as `flush()`. */
|
|
1801
2318
|
async aclose() {
|
|
1802
|
-
await this.sink
|
|
2319
|
+
await boundedSinkCall(this.sink, "aclose");
|
|
1803
2320
|
}
|
|
1804
2321
|
};
|
|
1805
2322
|
|
|
1806
2323
|
// src/integrations/mcp/sessionCounter.ts
|
|
1807
2324
|
var SessionCounter = class {
|
|
1808
2325
|
counters = /* @__PURE__ */ new Map();
|
|
2326
|
+
/** A per-call session is numbered by the clock: a counter would keep an
|
|
2327
|
+
* entry for every request the process serves. */
|
|
2328
|
+
nextFor(session) {
|
|
2329
|
+
return session.perCall ? nextClockSequence() : this.next(session.sessionId);
|
|
2330
|
+
}
|
|
1809
2331
|
next(sessionId) {
|
|
1810
2332
|
const current2 = this.counters.get(sessionId) ?? 0;
|
|
1811
2333
|
const next = current2 + 1;
|
|
@@ -1892,6 +2414,7 @@ function toJsonSchemaCompat(schema, opts) {
|
|
|
1892
2414
|
// src/integrations/mcp/schemaCompat.ts
|
|
1893
2415
|
import { z as zV4 } from "zod";
|
|
1894
2416
|
import { z as zV3 } from "zod/v3";
|
|
2417
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
1895
2418
|
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
1896
2419
|
function injectGoalParams(inputSchema, intentParamMode) {
|
|
1897
2420
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
@@ -1970,9 +2493,9 @@ function surfaceHash(surface) {
|
|
|
1970
2493
|
}
|
|
1971
2494
|
function canonicalJson(value) {
|
|
1972
2495
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1973
|
-
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
2496
|
+
if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
|
|
1974
2497
|
const record = value;
|
|
1975
|
-
const keys = Object.keys(record).sort();
|
|
2498
|
+
const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
|
|
1976
2499
|
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
|
|
1977
2500
|
}
|
|
1978
2501
|
function buildServerMeta(lowlevelServer) {
|
|
@@ -1994,6 +2517,25 @@ function assembleSurface(serverMeta, tools) {
|
|
|
1994
2517
|
tools
|
|
1995
2518
|
};
|
|
1996
2519
|
}
|
|
2520
|
+
var SENT_SURFACES_CAP = 256;
|
|
2521
|
+
var SentSurfaces = class {
|
|
2522
|
+
hashes = /* @__PURE__ */ new Set();
|
|
2523
|
+
wasSent(digest) {
|
|
2524
|
+
if (!this.hashes.has(digest)) return false;
|
|
2525
|
+
this.hashes.delete(digest);
|
|
2526
|
+
this.hashes.add(digest);
|
|
2527
|
+
return true;
|
|
2528
|
+
}
|
|
2529
|
+
mark(digest) {
|
|
2530
|
+
this.hashes.add(digest);
|
|
2531
|
+
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
2532
|
+
this.hashes.delete(this.hashes.values().next().value);
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
unmark(digest) {
|
|
2536
|
+
this.hashes.delete(digest);
|
|
2537
|
+
}
|
|
2538
|
+
};
|
|
1997
2539
|
function buildSeamAugmentations(options) {
|
|
1998
2540
|
return {
|
|
1999
2541
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
@@ -2012,12 +2554,12 @@ var wired = /* @__PURE__ */ new WeakSet();
|
|
|
2012
2554
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
2013
2555
|
var callSlots = new AsyncLocalStorage();
|
|
2014
2556
|
var SurfaceState = class {
|
|
2015
|
-
constructor(serverMeta,
|
|
2557
|
+
constructor(serverMeta, sentSurfaces) {
|
|
2016
2558
|
this.serverMeta = serverMeta;
|
|
2017
|
-
this.
|
|
2559
|
+
this.sentSurfaces = sentSurfaces;
|
|
2018
2560
|
}
|
|
2019
2561
|
serverMeta;
|
|
2020
|
-
|
|
2562
|
+
sentSurfaces;
|
|
2021
2563
|
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
2022
2564
|
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
2023
2565
|
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
@@ -2074,7 +2616,7 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
2074
2616
|
}
|
|
2075
2617
|
async function openCall(ctx, toolName, extra, params, retired, registered = true) {
|
|
2076
2618
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
2077
|
-
const {
|
|
2619
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2078
2620
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2079
2621
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2080
2622
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
@@ -2088,7 +2630,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2088
2630
|
const common = {
|
|
2089
2631
|
tenant_id: ctx.tenantId,
|
|
2090
2632
|
vendor_id: ctx.vendorId,
|
|
2091
|
-
session_id: sessionId,
|
|
2633
|
+
session_id: session.sessionId,
|
|
2092
2634
|
consent_token: ctx.consentToken,
|
|
2093
2635
|
// Every `...common` site is an event of this call, so `call_id` rides in
|
|
2094
2636
|
// it. `surface_snapshot` is deliberately not among them: it describes the
|
|
@@ -2097,16 +2639,17 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2097
2639
|
principal: caller.principal,
|
|
2098
2640
|
organization: caller.organization,
|
|
2099
2641
|
transport_observed: observeTransport(extra),
|
|
2100
|
-
session_id_origin: origin,
|
|
2642
|
+
session_id_origin: session.origin,
|
|
2101
2643
|
client_observed: observeClient(extra, ctx),
|
|
2102
2644
|
runtime_meta: scrubbedMeta,
|
|
2103
2645
|
call_id: uuid7()
|
|
2104
2646
|
};
|
|
2647
|
+
if (resumesPausedCall(extra)) return { common, session };
|
|
2105
2648
|
await emit(
|
|
2106
2649
|
ctx.sink,
|
|
2107
2650
|
() => ToolCallStartEventSchema.parse({
|
|
2108
2651
|
...common,
|
|
2109
|
-
sequence_number: ctx.counter.
|
|
2652
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2110
2653
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2111
2654
|
payload: {
|
|
2112
2655
|
tool_name: toolName,
|
|
@@ -2119,7 +2662,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2119
2662
|
}
|
|
2120
2663
|
})
|
|
2121
2664
|
);
|
|
2122
|
-
return { common,
|
|
2665
|
+
return { common, session };
|
|
2123
2666
|
}
|
|
2124
2667
|
function batonWrap(nameRef, original, ctx) {
|
|
2125
2668
|
return async (...callArgs) => {
|
|
@@ -2130,23 +2673,22 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2130
2673
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2131
2674
|
const retired = slot?.retired ?? {};
|
|
2132
2675
|
if (slot) slot.retired = {};
|
|
2133
|
-
const { common,
|
|
2676
|
+
const { common, session } = await openCall(ctx, toolName, extra, params, retired);
|
|
2134
2677
|
const terminate = async (build, replacement) => {
|
|
2135
2678
|
if (!slot) {
|
|
2136
|
-
await emit(ctx.sink, build);
|
|
2679
|
+
if (build !== null) await emit(ctx.sink, build);
|
|
2137
2680
|
return;
|
|
2138
2681
|
}
|
|
2139
2682
|
const earlier = slot.flushTerminal;
|
|
2140
2683
|
if (earlier !== null) await earlier(CLEAN_OUTCOME);
|
|
2141
2684
|
slot.flushTerminal = async (outcome) => {
|
|
2142
|
-
await emit(
|
|
2143
|
-
|
|
2144
|
-
() => replacement !== null && outcome.failed ? replacement(outcome) : build()
|
|
2145
|
-
);
|
|
2685
|
+
if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));
|
|
2686
|
+
else if (build !== null) await emit(ctx.sink, build);
|
|
2146
2687
|
};
|
|
2147
2688
|
};
|
|
2148
2689
|
const parkFailure = (build) => terminate(build, null);
|
|
2149
2690
|
const parkSuccess = (build, replacement) => terminate(build, replacement);
|
|
2691
|
+
const parkPause = (replacement) => terminate(null, replacement);
|
|
2150
2692
|
const startedAt = performance.now();
|
|
2151
2693
|
let result;
|
|
2152
2694
|
try {
|
|
@@ -2156,18 +2698,20 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2156
2698
|
await parkFailure(
|
|
2157
2699
|
() => ToolCallErrorEventSchema.parse({
|
|
2158
2700
|
...common,
|
|
2159
|
-
sequence_number: ctx.counter.
|
|
2701
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2160
2702
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2161
2703
|
payload: {
|
|
2162
2704
|
tool_name: toolName,
|
|
2163
2705
|
error_type: errorTypeOf(err),
|
|
2164
|
-
//
|
|
2165
|
-
//
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2706
|
+
// SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
|
|
2707
|
+
// raised message public, so under "off" every one is withheld.
|
|
2708
|
+
...resultDerivedFields(
|
|
2709
|
+
ctx.resultCaptureMode,
|
|
2710
|
+
() => messageOf(err),
|
|
2711
|
+
null,
|
|
2712
|
+
(text) => errorBody(ctx, text),
|
|
2713
|
+
ctx.scrubber
|
|
2714
|
+
),
|
|
2171
2715
|
duration_ms: durationMs2,
|
|
2172
2716
|
// Explicit, though the field is `.optional()` and this is its
|
|
2173
2717
|
// absent value. The schema is deliberately not an emitter (see
|
|
@@ -2187,11 +2731,64 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2187
2731
|
throw err;
|
|
2188
2732
|
}
|
|
2189
2733
|
const durationMs = Math.round(performance.now() - startedAt);
|
|
2734
|
+
const failedAbove = (outcome, failureKind) => ToolCallErrorEventSchema.parse({
|
|
2735
|
+
...common,
|
|
2736
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2737
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2738
|
+
payload: {
|
|
2739
|
+
tool_name: toolName,
|
|
2740
|
+
// The lane the OUTER came back on, not this one's: on 2.x the
|
|
2741
|
+
// conversion failure is converted to a returned `isError` inside
|
|
2742
|
+
// `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
|
|
2743
|
+
// right there. A pause the SDK rejects on 2026-07-28 raises, so
|
|
2744
|
+
// both lanes are reachable.
|
|
2745
|
+
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2746
|
+
// ⚠ The INNER's measurement — the vendor's handler duration —
|
|
2747
|
+
// not the outer's. Every other leg means the same thing by this
|
|
2748
|
+
// member, and widening it here for one failure kind would make
|
|
2749
|
+
// `duration_ms` mean two things in one column.
|
|
2750
|
+
duration_ms: durationMs,
|
|
2751
|
+
// Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.
|
|
2752
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
2753
|
+
// ⚠ **WITHHELD under `"off"`, unlike the three request-side
|
|
2754
|
+
// kinds.** The message quotes the value the tool returned
|
|
2755
|
+
// ("`'not-an-int'` is not of type `integer`"), so it is
|
|
2756
|
+
// result-derived by provenance and goes — which leaves
|
|
2757
|
+
// `failure_kind` as the ONLY surviving signal for an
|
|
2758
|
+
// `output_schema_mismatch` under `"off"`, and is the measurement
|
|
2759
|
+
// that justified putting the member on the wire at all.
|
|
2760
|
+
//
|
|
2761
|
+
// ⚠ `result` is what the CLIENT received — the SDK's own error
|
|
2762
|
+
// envelope — not the vendor's rejected return value. §11.4.3
|
|
2763
|
+
// asks for the envelope that holds the flag and the reason, and
|
|
2764
|
+
// this package's own invariant is that it agrees with the
|
|
2765
|
+
// caller. Recording the rejected output TOO would need a member
|
|
2766
|
+
// nothing on the wire has; the loss is deliberate and worth
|
|
2767
|
+
// knowing when debugging one of these.
|
|
2768
|
+
...resultDerivedFields(
|
|
2769
|
+
ctx.resultCaptureMode,
|
|
2770
|
+
() => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
|
|
2771
|
+
// ⚠ `null` on the `raised` lane, never `undefined`, and the
|
|
2772
|
+
// union is what forces the branch rather than a comment: the
|
|
2773
|
+
// scrubber would answer `undefined` and DROP the key, where the
|
|
2774
|
+
// sibling raise lane a few lines up declares `result: null`
|
|
2775
|
+
// explicitly, for the reason `ToolCallErrorPayloadSchema`
|
|
2776
|
+
// records. One shape for "no result object existed", not two.
|
|
2777
|
+
outcome.raised ? null : outcome.result ?? null,
|
|
2778
|
+
(text) => errorBody(ctx, text),
|
|
2779
|
+
ctx.scrubber
|
|
2780
|
+
)
|
|
2781
|
+
}
|
|
2782
|
+
});
|
|
2783
|
+
if (isInputRequired(result)) {
|
|
2784
|
+
await parkPause(failedAbove);
|
|
2785
|
+
return result;
|
|
2786
|
+
}
|
|
2190
2787
|
if (isErrorResult(result)) {
|
|
2191
2788
|
await parkFailure(
|
|
2192
2789
|
() => ToolCallErrorEventSchema.parse({
|
|
2193
2790
|
...common,
|
|
2194
|
-
sequence_number: ctx.counter.
|
|
2791
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2195
2792
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2196
2793
|
payload: {
|
|
2197
2794
|
tool_name: toolName,
|
|
@@ -2221,7 +2818,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2221
2818
|
await parkSuccess(
|
|
2222
2819
|
() => ToolCallEndEventSchema.parse({
|
|
2223
2820
|
...common,
|
|
2224
|
-
sequence_number: ctx.counter.
|
|
2821
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2225
2822
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2226
2823
|
payload: {
|
|
2227
2824
|
tool_name: toolName,
|
|
@@ -2229,61 +2826,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2229
2826
|
...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
|
|
2230
2827
|
}
|
|
2231
2828
|
}),
|
|
2232
|
-
|
|
2233
|
-
// then the outer seam saw the call fail anyway — so what failed is the
|
|
2234
|
-
// producer's own conversion of the output (SPEC §11.4.3's
|
|
2235
|
-
// `output_schema_mismatch`). Correcting this is the whole point of the
|
|
2236
|
-
// second seam: without it this is a `tool_call_end` for a call the
|
|
2237
|
-
// CALLER saw fail, which is a success the product invented.
|
|
2238
|
-
(outcome) => ToolCallErrorEventSchema.parse({
|
|
2239
|
-
...common,
|
|
2240
|
-
sequence_number: ctx.counter.next(sessionId),
|
|
2241
|
-
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2242
|
-
payload: {
|
|
2243
|
-
tool_name: toolName,
|
|
2244
|
-
// The lane the OUTER came back on, not this one's: on 2.x the
|
|
2245
|
-
// conversion failure is converted to a returned `isError` inside
|
|
2246
|
-
// `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
|
|
2247
|
-
// right there. A throw out of the handler is unreachable on
|
|
2248
|
-
// either major today for this lane; spelled anyway, because the
|
|
2249
|
-
// alternative is a crash on the day it stops being.
|
|
2250
|
-
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2251
|
-
// ⚠ The INNER's measurement — the vendor's handler duration —
|
|
2252
|
-
// not the outer's. Every other leg means the same thing by this
|
|
2253
|
-
// member, and widening it here for one failure kind would make
|
|
2254
|
-
// `duration_ms` mean two things in one column.
|
|
2255
|
-
duration_ms: durationMs,
|
|
2256
|
-
failure_kind: OUTPUT_SCHEMA_MISMATCH,
|
|
2257
|
-
// ⚠ **WITHHELD under `"off"`, unlike the three request-side
|
|
2258
|
-
// kinds.** The message quotes the value the tool returned
|
|
2259
|
-
// ("`'not-an-int'` is not of type `integer`"), so it is
|
|
2260
|
-
// result-derived by provenance and goes — which leaves
|
|
2261
|
-
// `failure_kind` as the ONLY surviving signal for this failure
|
|
2262
|
-
// under `"off"`, and is the measurement that justified putting
|
|
2263
|
-
// the member on the wire at all.
|
|
2264
|
-
//
|
|
2265
|
-
// ⚠ `result` is what the CLIENT received — the SDK's own error
|
|
2266
|
-
// envelope — not the vendor's rejected return value. §11.4.3
|
|
2267
|
-
// asks for the envelope that holds the flag and the reason, and
|
|
2268
|
-
// this package's own invariant is that it agrees with the
|
|
2269
|
-
// caller. Recording the rejected output TOO would need a member
|
|
2270
|
-
// nothing on the wire has; the loss is deliberate and worth
|
|
2271
|
-
// knowing when debugging one of these.
|
|
2272
|
-
...resultDerivedFields(
|
|
2273
|
-
ctx.resultCaptureMode,
|
|
2274
|
-
() => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
|
|
2275
|
-
// ⚠ `null` on the `raised` lane, never `undefined`, and the
|
|
2276
|
-
// union is what forces the branch rather than a comment: the
|
|
2277
|
-
// scrubber would answer `undefined` and DROP the key, where the
|
|
2278
|
-
// sibling raise lane a few lines up declares `result: null`
|
|
2279
|
-
// explicitly, for the reason `ToolCallErrorPayloadSchema`
|
|
2280
|
-
// records. One shape for "no result object existed", not two.
|
|
2281
|
-
outcome.raised ? null : outcome.result ?? null,
|
|
2282
|
-
(text) => errorBody(ctx, text),
|
|
2283
|
-
ctx.scrubber
|
|
2284
|
-
)
|
|
2285
|
-
}
|
|
2286
|
-
})
|
|
2829
|
+
(outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
|
|
2287
2830
|
);
|
|
2288
2831
|
return result;
|
|
2289
2832
|
};
|
|
@@ -2304,7 +2847,7 @@ function popText(args, paramName) {
|
|
|
2304
2847
|
if (!(paramName in args)) return null;
|
|
2305
2848
|
const raw = args[paramName];
|
|
2306
2849
|
delete args[paramName];
|
|
2307
|
-
return typeof raw === "string" && raw
|
|
2850
|
+
return typeof raw === "string" && !isBlank(raw) ? raw : null;
|
|
2308
2851
|
}
|
|
2309
2852
|
function stripRetiredParams(params, ctx) {
|
|
2310
2853
|
const toolName = params?.name;
|
|
@@ -2320,7 +2863,6 @@ function stripRetiredParams(params, ctx) {
|
|
|
2320
2863
|
}
|
|
2321
2864
|
return retired;
|
|
2322
2865
|
}
|
|
2323
|
-
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2324
2866
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2325
2867
|
if (!ctx.surfaceState.dirty) return;
|
|
2326
2868
|
ctx.surfaceState.dirty = false;
|
|
@@ -2334,10 +2876,9 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2334
2876
|
`);
|
|
2335
2877
|
return;
|
|
2336
2878
|
}
|
|
2337
|
-
const
|
|
2338
|
-
if (
|
|
2339
|
-
|
|
2340
|
-
emitted.add(digest);
|
|
2879
|
+
const sent = ctx.surfaceState.sentSurfaces;
|
|
2880
|
+
if (sent.wasSent(digest)) return;
|
|
2881
|
+
sent.mark(digest);
|
|
2341
2882
|
const seam = buildSeamAugmentations({
|
|
2342
2883
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
2343
2884
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -2350,7 +2891,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2350
2891
|
} catch (err) {
|
|
2351
2892
|
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
2352
2893
|
`);
|
|
2353
|
-
|
|
2894
|
+
sent.unmark(digest);
|
|
2354
2895
|
ctx.surfaceState.dirty = true;
|
|
2355
2896
|
}
|
|
2356
2897
|
}
|
|
@@ -2445,17 +2986,18 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2445
2986
|
ctx.sink,
|
|
2446
2987
|
() => schema.parse({
|
|
2447
2988
|
...opened.common,
|
|
2448
|
-
sequence_number: ctx.counter.
|
|
2989
|
+
sequence_number: ctx.counter.nextFor(opened.session),
|
|
2449
2990
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2450
2991
|
payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
|
|
2451
2992
|
})
|
|
2452
2993
|
);
|
|
2453
2994
|
};
|
|
2454
|
-
await fire(spec.schemas.start, spec.startParams(requestParams));
|
|
2995
|
+
if (!resumesPausedCall(extra)) await fire(spec.schemas.start, spec.startParams(requestParams));
|
|
2455
2996
|
const startedAt = performance.now();
|
|
2456
2997
|
const elapsed = () => Math.round(performance.now() - startedAt);
|
|
2457
2998
|
try {
|
|
2458
2999
|
const result = await handler(...args);
|
|
3000
|
+
if (isInputRequired(result)) return result;
|
|
2459
3001
|
await fire(spec.schemas.end, {
|
|
2460
3002
|
...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
|
|
2461
3003
|
duration_ms: elapsed()
|
|
@@ -2477,26 +3019,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2477
3019
|
}
|
|
2478
3020
|
async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
2479
3021
|
try {
|
|
2480
|
-
const
|
|
3022
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2481
3023
|
const caller = await resolveCaller(ctx.resolvePrincipal, {
|
|
2482
3024
|
extra,
|
|
2483
3025
|
toolName: null,
|
|
2484
3026
|
arguments: {}
|
|
2485
3027
|
});
|
|
2486
3028
|
return {
|
|
2487
|
-
|
|
3029
|
+
session,
|
|
2488
3030
|
subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
|
|
2489
3031
|
common: {
|
|
2490
3032
|
tenant_id: ctx.tenantId,
|
|
2491
3033
|
vendor_id: ctx.vendorId,
|
|
2492
|
-
session_id:
|
|
3034
|
+
session_id: session.sessionId,
|
|
2493
3035
|
consent_token: ctx.consentToken,
|
|
2494
3036
|
principal: caller.principal,
|
|
2495
3037
|
organization: caller.organization,
|
|
2496
3038
|
transport_observed: observeTransport(extra),
|
|
2497
|
-
session_id_origin:
|
|
3039
|
+
session_id_origin: session.origin,
|
|
2498
3040
|
client_observed: observeClient(extra, ctx),
|
|
2499
|
-
runtime_meta:
|
|
3041
|
+
runtime_meta: scrubbedMeta
|
|
2500
3042
|
}
|
|
2501
3043
|
};
|
|
2502
3044
|
} catch (err) {
|
|
@@ -2625,7 +3167,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2625
3167
|
innerFired: false,
|
|
2626
3168
|
flushTerminal: null,
|
|
2627
3169
|
retired: stripRetiredParams(request?.params, ctx),
|
|
2628
|
-
validation:
|
|
3170
|
+
validation: "unseen"
|
|
2629
3171
|
};
|
|
2630
3172
|
let outcome = CLEAN_OUTCOME;
|
|
2631
3173
|
try {
|
|
@@ -2645,8 +3187,7 @@ var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
|
2645
3187
|
function installValidationProbe(server) {
|
|
2646
3188
|
const target = server;
|
|
2647
3189
|
const original = target.validateToolInput;
|
|
2648
|
-
if (typeof original !== "function"
|
|
2649
|
-
if (original[VALIDATION_PROBE]) return () => target.validateToolInput === original;
|
|
3190
|
+
if (typeof original !== "function" || original[VALIDATION_PROBE]) return;
|
|
2650
3191
|
const probe = async function(...args) {
|
|
2651
3192
|
const slot = callSlots.getStore();
|
|
2652
3193
|
try {
|
|
@@ -2660,7 +3201,6 @@ function installValidationProbe(server) {
|
|
|
2660
3201
|
};
|
|
2661
3202
|
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
2662
3203
|
target.validateToolInput = probe;
|
|
2663
|
-
return () => target.validateToolInput === probe;
|
|
2664
3204
|
}
|
|
2665
3205
|
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
2666
3206
|
try {
|
|
@@ -2674,6 +3214,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
2674
3214
|
if (!outcome.failed) return;
|
|
2675
3215
|
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
2676
3216
|
} catch (err) {
|
|
3217
|
+
PROCESS_DROPS.add("encode_failed");
|
|
2677
3218
|
process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
|
|
2678
3219
|
`);
|
|
2679
3220
|
}
|
|
@@ -2686,7 +3227,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
2686
3227
|
const entry = toolEntry(toolName);
|
|
2687
3228
|
if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
|
|
2688
3229
|
const params = { ...request?.params?.arguments ?? {} };
|
|
2689
|
-
const { common,
|
|
3230
|
+
const { common, session } = await openCall(
|
|
2690
3231
|
ctx,
|
|
2691
3232
|
toolName,
|
|
2692
3233
|
args[1],
|
|
@@ -2700,7 +3241,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
2700
3241
|
ctx.sink,
|
|
2701
3242
|
() => ToolCallErrorEventSchema.parse({
|
|
2702
3243
|
...common,
|
|
2703
|
-
sequence_number: ctx.counter.
|
|
3244
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2704
3245
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2705
3246
|
payload: {
|
|
2706
3247
|
tool_name: toolName,
|
|
@@ -2816,15 +3357,19 @@ function withBaton(server, supplied = {}) {
|
|
|
2816
3357
|
}
|
|
2817
3358
|
const resolved = resolveBatonConfig(supplied);
|
|
2818
3359
|
warnUnusedReportSettings(resolved);
|
|
2819
|
-
return install(server, supplied, resolved,
|
|
3360
|
+
return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
|
|
2820
3361
|
}
|
|
2821
3362
|
function createBaton(supplied = {}) {
|
|
2822
3363
|
const disabledBy = captureDisabled();
|
|
2823
3364
|
if (disabledBy !== null) {
|
|
2824
3365
|
logDisabled(disabledBy, "createBaton");
|
|
2825
3366
|
const unused = supplied.sink ?? new DisabledSink();
|
|
2826
|
-
return {
|
|
2827
|
-
|
|
3367
|
+
return {
|
|
3368
|
+
wrap: () => {
|
|
3369
|
+
},
|
|
3370
|
+
flush: () => boundedSinkCall(unused, "flush"),
|
|
3371
|
+
aclose: () => boundedSinkCall(unused, "aclose")
|
|
3372
|
+
};
|
|
2828
3373
|
}
|
|
2829
3374
|
const resolved = resolveBatonConfig(supplied);
|
|
2830
3375
|
warnUnusedReportSettings(resolved);
|
|
@@ -2835,17 +3380,17 @@ function createBaton(supplied = {}) {
|
|
|
2835
3380
|
sink,
|
|
2836
3381
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2837
3382
|
};
|
|
2838
|
-
const
|
|
3383
|
+
const sentSurfaces = new SentSurfaces();
|
|
2839
3384
|
const warned3 = /* @__PURE__ */ new Set();
|
|
2840
3385
|
return {
|
|
2841
3386
|
wrap: (server) => {
|
|
2842
|
-
install(server, supplied, config,
|
|
3387
|
+
install(server, supplied, config, sentSurfaces, warned3);
|
|
2843
3388
|
},
|
|
2844
|
-
flush: () => sink
|
|
2845
|
-
aclose: () => sink
|
|
3389
|
+
flush: () => boundedSinkCall(sink, "flush"),
|
|
3390
|
+
aclose: () => boundedSinkCall(sink, "aclose")
|
|
2846
3391
|
};
|
|
2847
3392
|
}
|
|
2848
|
-
function install(server, supplied, resolved,
|
|
3393
|
+
function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
2849
3394
|
const internals = server;
|
|
2850
3395
|
const serverName = usableServerName(() => ({
|
|
2851
3396
|
name: internals.server._serverInfo?.name,
|
|
@@ -2855,13 +3400,13 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2855
3400
|
const sink = config.sink ?? new StdoutSink();
|
|
2856
3401
|
const reports = reportsFor(config);
|
|
2857
3402
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
2858
|
-
const intentParamMode = config.intentParamMode ??
|
|
3403
|
+
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
2859
3404
|
const counter2 = new SessionCounter();
|
|
2860
3405
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
2861
3406
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
2862
3407
|
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
2863
3408
|
const serverMeta = buildServerMeta(server.server);
|
|
2864
|
-
const surfaceState = new SurfaceState(serverMeta,
|
|
3409
|
+
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
2865
3410
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
2866
3411
|
const event = SurfaceSnapshotEventSchema.parse({
|
|
2867
3412
|
tenant_id: tenantId,
|
|
@@ -2880,7 +3425,12 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2880
3425
|
seam_augmentations: snapshot.seam_augmentations
|
|
2881
3426
|
}
|
|
2882
3427
|
});
|
|
2883
|
-
|
|
3428
|
+
try {
|
|
3429
|
+
await sink.write(event);
|
|
3430
|
+
} catch (err) {
|
|
3431
|
+
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
3432
|
+
throw err;
|
|
3433
|
+
}
|
|
2884
3434
|
};
|
|
2885
3435
|
const bustSchemaMemo = (name) => {
|
|
2886
3436
|
const memo = internals._toolInputSchemaJson;
|
|
@@ -2927,6 +3477,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2927
3477
|
return { type: "object", properties: {} };
|
|
2928
3478
|
}
|
|
2929
3479
|
};
|
|
3480
|
+
installValidationProbe(server);
|
|
2930
3481
|
const ctx = {
|
|
2931
3482
|
sink,
|
|
2932
3483
|
counter: counter2,
|
|
@@ -2939,7 +3490,6 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2939
3490
|
annotationToolName,
|
|
2940
3491
|
intentParamMode,
|
|
2941
3492
|
resultCaptureMode: config.resultCaptureMode ?? "full",
|
|
2942
|
-
validationProbeLive: installValidationProbe(server),
|
|
2943
3493
|
paramRegistry: /* @__PURE__ */ new Map(),
|
|
2944
3494
|
resolvePrincipal: config.resolvePrincipal,
|
|
2945
3495
|
vendorToolJsonSchema,
|
|
@@ -3030,7 +3580,7 @@ function claimsOf(context) {
|
|
|
3030
3580
|
}
|
|
3031
3581
|
function stringClaim(claims, name) {
|
|
3032
3582
|
const value = claims[name];
|
|
3033
|
-
return typeof value === "string" &&
|
|
3583
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
3034
3584
|
}
|
|
3035
3585
|
function principalFromOAuthSub(context) {
|
|
3036
3586
|
const claims = claimsOf(context);
|
|
@@ -3062,33 +3612,46 @@ function sessionEnvelope(session) {
|
|
|
3062
3612
|
principal: session.principal,
|
|
3063
3613
|
organization: session.organization,
|
|
3064
3614
|
client_observed: session.clientObserved,
|
|
3065
|
-
runtime_meta: session.
|
|
3615
|
+
runtime_meta: session.runtimeMeta
|
|
3066
3616
|
};
|
|
3067
3617
|
}
|
|
3068
|
-
function
|
|
3618
|
+
function warn2(message) {
|
|
3069
3619
|
process.stderr.write(`baton: ${message}
|
|
3070
3620
|
`);
|
|
3071
3621
|
}
|
|
3072
3622
|
function vendorId(name, value) {
|
|
3073
|
-
const cleaned = typeof value === "string" ?
|
|
3623
|
+
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
3074
3624
|
if (cleaned !== "") return cleaned;
|
|
3075
3625
|
if (value !== void 0 && value !== null) {
|
|
3076
|
-
|
|
3626
|
+
warn2(`${name} is not a non-blank string \u2014 ignoring it.`);
|
|
3077
3627
|
}
|
|
3078
3628
|
return null;
|
|
3079
3629
|
}
|
|
3080
3630
|
function blank(sessionId, origin) {
|
|
3081
|
-
return { sessionId, origin, ...NO_CALLER, clientObserved: null,
|
|
3631
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
3632
|
+
}
|
|
3633
|
+
function requestMeta(meta) {
|
|
3634
|
+
if (isRecord(meta)) return meta;
|
|
3635
|
+
if (meta !== void 0 && meta !== null) warn2("meta is not an object \u2014 ignoring it.");
|
|
3636
|
+
return null;
|
|
3637
|
+
}
|
|
3638
|
+
function runtimeMeta(meta, turnId, scrubber) {
|
|
3639
|
+
const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));
|
|
3640
|
+
const cleaned = Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), "_meta") : null;
|
|
3641
|
+
const out = isRecord(cleaned) ? { ...cleaned } : {};
|
|
3642
|
+
if (turnId !== null) out[TURN_ID_META_KEY] = turnId;
|
|
3643
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
3082
3644
|
}
|
|
3083
3645
|
function newSession(values, scrubber, disabled) {
|
|
3084
3646
|
const id = vendorId("sessionId", values.sessionId);
|
|
3085
3647
|
const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
|
|
3086
3648
|
if (disabled) return base;
|
|
3649
|
+
const meta = requestMeta(values.meta);
|
|
3087
3650
|
return {
|
|
3088
3651
|
...base,
|
|
3089
|
-
...callerFor(values.principal, (_key, message) =>
|
|
3090
|
-
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
|
|
3091
|
-
|
|
3652
|
+
...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
|
|
3653
|
+
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
|
|
3654
|
+
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
3092
3655
|
};
|
|
3093
3656
|
}
|
|
3094
3657
|
var current = new AsyncLocalStorage2();
|
|
@@ -3099,11 +3662,71 @@ function sessionForCall(owner) {
|
|
|
3099
3662
|
const entry = current.getStore();
|
|
3100
3663
|
return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
|
|
3101
3664
|
}
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3665
|
+
|
|
3666
|
+
// src/library/surface.ts
|
|
3667
|
+
function serveTools(tools, options) {
|
|
3668
|
+
let served;
|
|
3669
|
+
try {
|
|
3670
|
+
served = tools.map(servedEntry);
|
|
3671
|
+
} catch (err) {
|
|
3672
|
+
process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
|
|
3673
|
+
`);
|
|
3674
|
+
return { served: tools, surface: null };
|
|
3675
|
+
}
|
|
3676
|
+
try {
|
|
3677
|
+
const nameOf = (tool) => isRecord(tool) ? String(tool.name) : "";
|
|
3678
|
+
const ordered = [...tools].sort((a, b) => {
|
|
3679
|
+
const [x, y] = [nameOf(a), nameOf(b)];
|
|
3680
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
3681
|
+
});
|
|
3682
|
+
const meta = {
|
|
3683
|
+
server_info: options.serverInfo ?? null,
|
|
3684
|
+
capabilities: options.capabilities ?? null,
|
|
3685
|
+
instructions: options.instructions ?? null
|
|
3686
|
+
};
|
|
3687
|
+
const surface = JSON.parse(
|
|
3688
|
+
JSON.stringify(assembleSurface(meta, ordered))
|
|
3689
|
+
);
|
|
3690
|
+
return { served, surface: { surface, digest: surfaceHash(surface) } };
|
|
3691
|
+
} catch (err) {
|
|
3692
|
+
process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
|
|
3693
|
+
`);
|
|
3694
|
+
return { served, surface: null };
|
|
3695
|
+
}
|
|
3696
|
+
}
|
|
3697
|
+
function snapshotPayload({ surface, digest }) {
|
|
3698
|
+
return {
|
|
3699
|
+
surface_hash: digest,
|
|
3700
|
+
...surface,
|
|
3701
|
+
seam_augmentations: buildSeamAugmentations({
|
|
3702
|
+
injectedToolNames: [],
|
|
3703
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
3704
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
3705
|
+
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
3706
|
+
instructionsSuffix: null
|
|
3707
|
+
})
|
|
3708
|
+
};
|
|
3709
|
+
}
|
|
3710
|
+
function servedEntry(tool) {
|
|
3711
|
+
if (!isRecord(tool)) return tool;
|
|
3712
|
+
const entry = { ...tool };
|
|
3713
|
+
if (isRecord(entry.inputSchema)) {
|
|
3714
|
+
const schema = { ...entry.inputSchema };
|
|
3715
|
+
if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
|
|
3716
|
+
injectGoalParam(schema);
|
|
3717
|
+
entry.inputSchema = schema;
|
|
3718
|
+
}
|
|
3719
|
+
return entry;
|
|
3720
|
+
}
|
|
3721
|
+
function injectGoalParam(schema) {
|
|
3722
|
+
if (schema.properties === void 0) schema.properties = {};
|
|
3723
|
+
if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
|
|
3724
|
+
schema.properties[USER_GOAL_PARAM_NAME] = {
|
|
3725
|
+
type: "string",
|
|
3726
|
+
description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
|
|
3727
|
+
};
|
|
3728
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3729
|
+
if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
|
|
3107
3730
|
}
|
|
3108
3731
|
|
|
3109
3732
|
// src/library/client.ts
|
|
@@ -3166,7 +3789,7 @@ function resolveClientOptions(options) {
|
|
|
3166
3789
|
resultCaptureMode
|
|
3167
3790
|
};
|
|
3168
3791
|
}
|
|
3169
|
-
var hasText2 = (value) => typeof value === "string" &&
|
|
3792
|
+
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
3170
3793
|
function describeError(err) {
|
|
3171
3794
|
let type = "Error";
|
|
3172
3795
|
let body = "";
|
|
@@ -3180,19 +3803,18 @@ function describeError(err) {
|
|
|
3180
3803
|
}
|
|
3181
3804
|
return [type, body];
|
|
3182
3805
|
}
|
|
3183
|
-
function isPlainObject3(value) {
|
|
3184
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3185
|
-
const proto = Object.getPrototypeOf(value);
|
|
3186
|
-
return proto === Object.prototype || proto === null;
|
|
3187
|
-
}
|
|
3188
3806
|
function paramsOf(args) {
|
|
3189
|
-
if (args.length === 1 &&
|
|
3807
|
+
if (args.length === 1 && isPlainObject(args[0])) return args[0];
|
|
3190
3808
|
return args.length === 0 ? {} : { args };
|
|
3191
3809
|
}
|
|
3192
3810
|
var Core = class {
|
|
3193
3811
|
closed = false;
|
|
3194
3812
|
pending = /* @__PURE__ */ new Set();
|
|
3195
3813
|
closedWarned = false;
|
|
3814
|
+
// A snapshot describes the server, so it takes no block's session,
|
|
3815
|
+
// principal or client: SPEC §11.5.1's join must not count it.
|
|
3816
|
+
surfaceSessionId = uuid7();
|
|
3817
|
+
sentSurfaces = new SentSurfaces();
|
|
3196
3818
|
sink;
|
|
3197
3819
|
vendorId;
|
|
3198
3820
|
tenantId;
|
|
@@ -3225,6 +3847,7 @@ var Core = class {
|
|
|
3225
3847
|
live() {
|
|
3226
3848
|
if (this.disabled) return false;
|
|
3227
3849
|
if (!this.closed) return true;
|
|
3850
|
+
PROCESS_DROPS.add("after_close");
|
|
3228
3851
|
if (!this.closedWarned) {
|
|
3229
3852
|
this.closedWarned = true;
|
|
3230
3853
|
process.stderr.write("baton: Client is closed; further events are dropped.\n");
|
|
@@ -3233,19 +3856,70 @@ var Core = class {
|
|
|
3233
3856
|
}
|
|
3234
3857
|
/** Never rejects. Tracked so `flush()` can wait for it. */
|
|
3235
3858
|
emit(build) {
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3859
|
+
return this.track(emit(this.sink, build));
|
|
3860
|
+
}
|
|
3861
|
+
track(work) {
|
|
3862
|
+
const tracked = work.finally(() => this.pending.delete(tracked));
|
|
3863
|
+
this.pending.add(tracked);
|
|
3864
|
+
return tracked;
|
|
3865
|
+
}
|
|
3866
|
+
/** Sends `surface` unless this client already has. Never rejects; a failed
|
|
3867
|
+
* write unmarks it, so the next `listTools` tries again. A surface that does
|
|
3868
|
+
* not fit the schema stays marked: it would fail the same way every time. */
|
|
3869
|
+
sendSurface(surface) {
|
|
3870
|
+
if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
|
|
3871
|
+
this.sentSurfaces.mark(surface.digest);
|
|
3872
|
+
let event;
|
|
3873
|
+
try {
|
|
3874
|
+
event = SurfaceSnapshotEventSchema.parse({
|
|
3875
|
+
tenant_id: this.tenantId,
|
|
3876
|
+
vendor_id: this.vendorId,
|
|
3877
|
+
session_id: this.surfaceSessionId,
|
|
3878
|
+
session_id_origin: "minted",
|
|
3879
|
+
sequence_number: nextClockSequence(),
|
|
3880
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3881
|
+
consent_token: this.consentToken,
|
|
3882
|
+
payload: snapshotPayload(surface)
|
|
3883
|
+
});
|
|
3884
|
+
} catch (err) {
|
|
3885
|
+
PROCESS_DROPS.add("encode_failed");
|
|
3886
|
+
process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
|
|
3887
|
+
`);
|
|
3888
|
+
return Promise.resolve();
|
|
3889
|
+
}
|
|
3890
|
+
return this.track(
|
|
3891
|
+
(async () => {
|
|
3892
|
+
try {
|
|
3893
|
+
await this.sink.write(event);
|
|
3894
|
+
} catch (err) {
|
|
3895
|
+
if (isSinkClosed(err)) return droppedAfterClose(this.sink);
|
|
3896
|
+
process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
|
|
3897
|
+
`);
|
|
3898
|
+
this.sentSurfaces.unmark(surface.digest);
|
|
3899
|
+
}
|
|
3900
|
+
})()
|
|
3901
|
+
);
|
|
3239
3902
|
}
|
|
3240
|
-
|
|
3241
|
-
|
|
3903
|
+
/** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
|
|
3904
|
+
* also for ones emitted while it waits. A write still pending when time runs
|
|
3905
|
+
* out is not waited on again, so one stuck write costs one wait. */
|
|
3906
|
+
async settleWithin(ms, untilEmpty) {
|
|
3907
|
+
const deadline = performance.now() + ms;
|
|
3908
|
+
do {
|
|
3909
|
+
const waiting = [...this.pending];
|
|
3910
|
+
if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
|
|
3911
|
+
const left = waiting.filter((write) => this.pending.delete(write));
|
|
3912
|
+
if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
|
|
3913
|
+
return;
|
|
3914
|
+
}
|
|
3915
|
+
} while (untilEmpty && this.pending.size > 0);
|
|
3242
3916
|
}
|
|
3243
3917
|
scrub(value, field) {
|
|
3244
3918
|
return scrubOrNull(this.scrubber, value, field);
|
|
3245
3919
|
}
|
|
3246
3920
|
annotate(session, consentToken, options) {
|
|
3247
3921
|
if (!this.live()) return Promise.resolve();
|
|
3248
|
-
const sequence =
|
|
3922
|
+
const sequence = nextClockSequence();
|
|
3249
3923
|
const text = (value) => value === void 0 ? null : this.scrubber(value);
|
|
3250
3924
|
return this.emit(
|
|
3251
3925
|
() => AnnotationEventSchema.parse({
|
|
@@ -3313,7 +3987,7 @@ var Trace = class _Trace {
|
|
|
3313
3987
|
try {
|
|
3314
3988
|
this.#result = this.#core.scrubber(result);
|
|
3315
3989
|
} catch (err) {
|
|
3316
|
-
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${
|
|
3990
|
+
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
|
|
3317
3991
|
`);
|
|
3318
3992
|
this.#result = SCRUB_FAILED;
|
|
3319
3993
|
}
|
|
@@ -3333,7 +4007,7 @@ var Trace = class _Trace {
|
|
|
3333
4007
|
#start() {
|
|
3334
4008
|
this.#startedAt = performance.now();
|
|
3335
4009
|
if (!this.#core.live()) return;
|
|
3336
|
-
const sequence =
|
|
4010
|
+
const sequence = nextClockSequence();
|
|
3337
4011
|
const o = this.#options;
|
|
3338
4012
|
const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
|
|
3339
4013
|
const textOf = (value, field) => {
|
|
@@ -3362,7 +4036,7 @@ var Trace = class _Trace {
|
|
|
3362
4036
|
const durationMs = this.#durationMs();
|
|
3363
4037
|
if (!this.#core.live()) return;
|
|
3364
4038
|
if (this.#result === UNSET && this.#error === null) this.observed(value);
|
|
3365
|
-
const sequence =
|
|
4039
|
+
const sequence = nextClockSequence();
|
|
3366
4040
|
const error = this.#error;
|
|
3367
4041
|
if (error !== null) {
|
|
3368
4042
|
this.#emitError(sequence, error.type, error.body, durationMs);
|
|
@@ -3384,7 +4058,7 @@ var Trace = class _Trace {
|
|
|
3384
4058
|
#fail(err) {
|
|
3385
4059
|
const durationMs = this.#durationMs();
|
|
3386
4060
|
if (!this.#core.live()) return;
|
|
3387
|
-
this.#emitError(
|
|
4061
|
+
this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
|
|
3388
4062
|
}
|
|
3389
4063
|
#emitError(sequence, type, body, durationMs) {
|
|
3390
4064
|
void this.#core.emit(
|
|
@@ -3460,7 +4134,7 @@ var Client = class {
|
|
|
3460
4134
|
try {
|
|
3461
4135
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
3462
4136
|
} catch (err) {
|
|
3463
|
-
process.stderr.write(`baton: session values could not be read; using a minted session: ${
|
|
4137
|
+
process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
|
|
3464
4138
|
`);
|
|
3465
4139
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
3466
4140
|
}
|
|
@@ -3490,30 +4164,41 @@ var Client = class {
|
|
|
3490
4164
|
const given = options ?? {};
|
|
3491
4165
|
return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
|
|
3492
4166
|
}
|
|
3493
|
-
/**
|
|
4167
|
+
/** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
|
|
4168
|
+
* to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
|
|
4169
|
+
* of `tools` as passed, sent once per distinct surface. For a vendor
|
|
4170
|
+
* serving MCP itself (SPEC §5.6).
|
|
4171
|
+
*
|
|
4172
|
+
* Pass the tools before anything of Baton's is added, so the snapshot
|
|
4173
|
+
* describes the vendor's own surface. `options` holds the vendor's own
|
|
4174
|
+
* `initialize` values. The input is not changed. Never rejects over the
|
|
4175
|
+
* tool list: one it cannot read is returned as it came. Does not wait for
|
|
4176
|
+
* the snapshot to be sent; `flush()` does. */
|
|
4177
|
+
async listTools(tools, options = {}) {
|
|
4178
|
+
if (this.#core.disabled) return tools;
|
|
4179
|
+
const { served, surface } = serveTools(tools, options);
|
|
4180
|
+
if (surface !== null) void this.#core.sendSurface(surface);
|
|
4181
|
+
return served;
|
|
4182
|
+
}
|
|
4183
|
+
/** Wait for events so far to reach the sink, then flush it. Never rejects;
|
|
4184
|
+
* returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
|
|
3494
4185
|
async flush() {
|
|
3495
|
-
await this.#
|
|
3496
|
-
try {
|
|
3497
|
-
await this.#core.sink.flush();
|
|
3498
|
-
} catch (err) {
|
|
3499
|
-
process.stderr.write(`baton: sink.flush failed: ${String(err)}
|
|
3500
|
-
`);
|
|
3501
|
-
}
|
|
4186
|
+
await this.#settleThen("flush");
|
|
3502
4187
|
}
|
|
3503
4188
|
/** Flush, then close the sink. Later events are dropped. */
|
|
3504
4189
|
aclose() {
|
|
3505
|
-
this.#closing ??= this.#
|
|
4190
|
+
this.#closing ??= this.#settleThen("aclose");
|
|
3506
4191
|
return this.#closing;
|
|
3507
4192
|
}
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
}
|
|
4193
|
+
/** One budget: events in flight get until its end to reach the sink, then
|
|
4194
|
+
* the sink gets the time left. */
|
|
4195
|
+
async #settleThen(method) {
|
|
4196
|
+
await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
|
|
4197
|
+
const deadline = performance.now() + budgetMs;
|
|
4198
|
+
await this.#core.settleWithin(budgetMs, method === "aclose");
|
|
4199
|
+
if (method === "aclose") this.#core.closed = true;
|
|
4200
|
+
await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
|
|
4201
|
+
});
|
|
3517
4202
|
}
|
|
3518
4203
|
};
|
|
3519
4204
|
export {
|
|
@@ -3521,13 +4206,18 @@ export {
|
|
|
3521
4206
|
AnnotationPayloadSchema,
|
|
3522
4207
|
BatonHandle,
|
|
3523
4208
|
Client,
|
|
4209
|
+
ClientReportEventSchema,
|
|
4210
|
+
ClientReportPayloadSchema,
|
|
3524
4211
|
DEFAULT_CONSENT_TOKEN,
|
|
3525
4212
|
DEPTH_LIMIT,
|
|
4213
|
+
DEPTH_MARKER,
|
|
3526
4214
|
EventSchema,
|
|
3527
4215
|
EventTypeSchema,
|
|
4216
|
+
FileSink,
|
|
3528
4217
|
HttpSink,
|
|
3529
4218
|
INTENT_INSTRUCTIONS,
|
|
3530
4219
|
INTENT_PARAMS,
|
|
4220
|
+
MultiSink,
|
|
3531
4221
|
PRINCIPAL_FORM_HASHED,
|
|
3532
4222
|
PRINCIPAL_FORM_RAW,
|
|
3533
4223
|
PRINCIPAL_SOURCE_ASSERTED,
|
|
@@ -3558,6 +4248,7 @@ export {
|
|
|
3558
4248
|
ResourceReadStartPayloadSchema,
|
|
3559
4249
|
SDK_VERSION,
|
|
3560
4250
|
Scrubber,
|
|
4251
|
+
SinkClosedError,
|
|
3561
4252
|
StdoutSink,
|
|
3562
4253
|
SurfaceSnapshotEventSchema,
|
|
3563
4254
|
SurfaceSnapshotPayloadSchema,
|