@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.cjs
CHANGED
|
@@ -34,13 +34,18 @@ __export(index_exports, {
|
|
|
34
34
|
AnnotationPayloadSchema: () => AnnotationPayloadSchema,
|
|
35
35
|
BatonHandle: () => BatonHandle,
|
|
36
36
|
Client: () => Client,
|
|
37
|
+
ClientReportEventSchema: () => ClientReportEventSchema,
|
|
38
|
+
ClientReportPayloadSchema: () => ClientReportPayloadSchema,
|
|
37
39
|
DEFAULT_CONSENT_TOKEN: () => DEFAULT_CONSENT_TOKEN,
|
|
38
40
|
DEPTH_LIMIT: () => DEPTH_LIMIT,
|
|
41
|
+
DEPTH_MARKER: () => DEPTH_MARKER,
|
|
39
42
|
EventSchema: () => EventSchema,
|
|
40
43
|
EventTypeSchema: () => EventTypeSchema,
|
|
44
|
+
FileSink: () => FileSink,
|
|
41
45
|
HttpSink: () => HttpSink,
|
|
42
46
|
INTENT_INSTRUCTIONS: () => INTENT_INSTRUCTIONS,
|
|
43
47
|
INTENT_PARAMS: () => INTENT_PARAMS,
|
|
48
|
+
MultiSink: () => MultiSink,
|
|
44
49
|
PRINCIPAL_FORM_HASHED: () => PRINCIPAL_FORM_HASHED,
|
|
45
50
|
PRINCIPAL_FORM_RAW: () => PRINCIPAL_FORM_RAW,
|
|
46
51
|
PRINCIPAL_SOURCE_ASSERTED: () => PRINCIPAL_SOURCE_ASSERTED,
|
|
@@ -71,6 +76,7 @@ __export(index_exports, {
|
|
|
71
76
|
ResourceReadStartPayloadSchema: () => ResourceReadStartPayloadSchema,
|
|
72
77
|
SDK_VERSION: () => SDK_VERSION,
|
|
73
78
|
Scrubber: () => Scrubber,
|
|
79
|
+
SinkClosedError: () => SinkClosedError,
|
|
74
80
|
StdoutSink: () => StdoutSink,
|
|
75
81
|
SurfaceSnapshotEventSchema: () => SurfaceSnapshotEventSchema,
|
|
76
82
|
SurfaceSnapshotPayloadSchema: () => SurfaceSnapshotPayloadSchema,
|
|
@@ -97,7 +103,7 @@ __export(index_exports, {
|
|
|
97
103
|
module.exports = __toCommonJS(index_exports);
|
|
98
104
|
|
|
99
105
|
// src/version.ts
|
|
100
|
-
var SDK_VERSION = "ts-0.6.
|
|
106
|
+
var SDK_VERSION = "ts-0.6.3";
|
|
101
107
|
|
|
102
108
|
// src/events.ts
|
|
103
109
|
var import_zod = require("zod");
|
|
@@ -218,6 +224,10 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
|
|
|
218
224
|
tools: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
|
|
219
225
|
seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
|
|
220
226
|
}).strict();
|
|
227
|
+
var ClientReportPayloadSchema = import_zod.z.object({
|
|
228
|
+
instance_id: import_zod.z.uuid(),
|
|
229
|
+
dropped: import_zod.z.record(import_zod.z.string(), import_zod.z.number().int().nonnegative())
|
|
230
|
+
}).strict();
|
|
221
231
|
var DEFAULT_CONSENT_TOKEN = "customer-consented";
|
|
222
232
|
var ClientObservedSchema = import_zod.z.object({
|
|
223
233
|
info: import_zod.z.object({ name: import_zod.z.string().optional(), version: import_zod.z.string().optional() }).strict().optional(),
|
|
@@ -255,6 +265,7 @@ var EventTypeSchema = import_zod.z.enum([
|
|
|
255
265
|
"tool_call_error",
|
|
256
266
|
"annotation",
|
|
257
267
|
"surface_snapshot",
|
|
268
|
+
"client_report",
|
|
258
269
|
// The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
|
|
259
270
|
// shapes were set by `baton-proxy`, which has been emitting all of them in
|
|
260
271
|
// production — see the payload schemas below.
|
|
@@ -364,6 +375,11 @@ var SurfaceSnapshotEventSchema = import_zod.z.object({
|
|
|
364
375
|
event_type: import_zod.z.literal("surface_snapshot").default("surface_snapshot"),
|
|
365
376
|
payload: SurfaceSnapshotPayloadSchema
|
|
366
377
|
}).strict();
|
|
378
|
+
var ClientReportEventSchema = import_zod.z.object({
|
|
379
|
+
...envelopeShape,
|
|
380
|
+
event_type: import_zod.z.literal("client_report").default("client_report"),
|
|
381
|
+
payload: ClientReportPayloadSchema
|
|
382
|
+
}).strict();
|
|
367
383
|
var ResourceListStartEventSchema = import_zod.z.object({
|
|
368
384
|
...envelopeShape,
|
|
369
385
|
event_type: import_zod.z.literal("resource_list_start").default("resource_list_start"),
|
|
@@ -445,6 +461,7 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
|
445
461
|
ToolCallErrorEventSchema,
|
|
446
462
|
AnnotationEventSchema,
|
|
447
463
|
SurfaceSnapshotEventSchema,
|
|
464
|
+
ClientReportEventSchema,
|
|
448
465
|
ResourceListStartEventSchema,
|
|
449
466
|
ResourceListEndEventSchema,
|
|
450
467
|
ResourceListErrorEventSchema,
|
|
@@ -462,8 +479,33 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
|
462
479
|
ToolListErrorEventSchema
|
|
463
480
|
]);
|
|
464
481
|
|
|
482
|
+
// src/warn.ts
|
|
483
|
+
function warn(message) {
|
|
484
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
485
|
+
process.emitWarning(message);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
function printable(err) {
|
|
489
|
+
try {
|
|
490
|
+
return String(err);
|
|
491
|
+
} catch {
|
|
492
|
+
return "(an error that cannot be printed)";
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// src/_object.ts
|
|
497
|
+
function isPlainObject(value) {
|
|
498
|
+
if (typeof value !== "object" || value === null) return false;
|
|
499
|
+
const proto = Object.getPrototypeOf(value);
|
|
500
|
+
return proto === Object.prototype || proto === null;
|
|
501
|
+
}
|
|
502
|
+
function isRecord(value) {
|
|
503
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
504
|
+
}
|
|
505
|
+
|
|
465
506
|
// src/scrub.ts
|
|
466
507
|
var DEPTH_LIMIT = 10;
|
|
508
|
+
var DEPTH_MARKER = "[REDACTED:depth-limit]";
|
|
467
509
|
var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
468
510
|
"email",
|
|
469
511
|
"phone",
|
|
@@ -474,16 +516,21 @@ var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
|
474
516
|
"password",
|
|
475
517
|
"user_name"
|
|
476
518
|
]);
|
|
519
|
+
var WS_CHARS = String.raw` \t\n\r\f\u00a0`;
|
|
520
|
+
var PHONE_SEP = String.raw`[${WS_CHARS}\-.]`;
|
|
477
521
|
var PATTERNS = [
|
|
478
522
|
["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
|
|
479
|
-
["bearer",
|
|
523
|
+
["bearer", new RegExp(String.raw`\bBearer[${WS_CHARS}]+[A-Za-z0-9_\-.+/=]{16,}`, "gi")],
|
|
480
524
|
["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
481
525
|
["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
482
526
|
["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
|
|
483
527
|
// Phone: optional `+1`, optional area-code parens, separators
|
|
484
|
-
//
|
|
528
|
+
// `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every
|
|
485
529
|
// international format, but won't trip on every 10-digit identifier.
|
|
486
|
-
[
|
|
530
|
+
[
|
|
531
|
+
"phone",
|
|
532
|
+
new RegExp(String.raw`\b(?:\+?1${PHONE_SEP}?)?\(?\d{3}\)?${PHONE_SEP}?\d{3}${PHONE_SEP}?\d{4}\b`, "g")
|
|
533
|
+
]
|
|
487
534
|
];
|
|
488
535
|
var CC_CANDIDATE = /\b\d{13,19}\b/g;
|
|
489
536
|
function luhnValid(digits) {
|
|
@@ -498,13 +545,9 @@ function luhnValid(digits) {
|
|
|
498
545
|
}
|
|
499
546
|
return total % 10 === 0;
|
|
500
547
|
}
|
|
501
|
-
function isPlainObject(value) {
|
|
502
|
-
if (typeof value !== "object" || value === null) return false;
|
|
503
|
-
const proto = Object.getPrototypeOf(value);
|
|
504
|
-
return proto === Object.prototype || proto === null;
|
|
505
|
-
}
|
|
506
548
|
var Scrubber = class {
|
|
507
549
|
counts = /* @__PURE__ */ new Map();
|
|
550
|
+
warnedDepth = false;
|
|
508
551
|
/** Bound so `new Scrubber().scrub` can be passed as a bare function
|
|
509
552
|
* reference — the closest TS gets to Python's `__call__`. */
|
|
510
553
|
scrub = (value) => this.walk(value, 0, null);
|
|
@@ -515,8 +558,20 @@ var Scrubber = class {
|
|
|
515
558
|
bump(category) {
|
|
516
559
|
this.counts.set(category, this.count(category) + 1);
|
|
517
560
|
}
|
|
561
|
+
pastTheDepthLimit() {
|
|
562
|
+
this.bump("depth_limit");
|
|
563
|
+
if (!this.warnedDepth) {
|
|
564
|
+
this.warnedDepth = true;
|
|
565
|
+
warn(
|
|
566
|
+
`baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
return DEPTH_MARKER;
|
|
570
|
+
}
|
|
518
571
|
walk(value, depth, forceField) {
|
|
519
|
-
if (depth >= DEPTH_LIMIT)
|
|
572
|
+
if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {
|
|
573
|
+
return this.pastTheDepthLimit();
|
|
574
|
+
}
|
|
520
575
|
if (isPlainObject(value)) {
|
|
521
576
|
const out = {};
|
|
522
577
|
for (const [k, v] of Object.entries(value)) {
|
|
@@ -557,12 +612,167 @@ function identityScrub(value) {
|
|
|
557
612
|
}
|
|
558
613
|
|
|
559
614
|
// src/sinks.ts
|
|
615
|
+
var import_node_fs = require("fs");
|
|
616
|
+
|
|
617
|
+
// src/_text.ts
|
|
618
|
+
var WHITE_SPACE = /^\p{White_Space}$/u;
|
|
619
|
+
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
620
|
+
function stripEdges(value, space) {
|
|
621
|
+
let start = 0;
|
|
622
|
+
let end = value.length;
|
|
623
|
+
while (start < end && space.test(value[start])) start++;
|
|
624
|
+
while (end > start && space.test(value[end - 1])) end--;
|
|
625
|
+
return value.slice(start, end);
|
|
626
|
+
}
|
|
627
|
+
function stripWhiteSpace(value) {
|
|
628
|
+
return stripEdges(value, WHITE_SPACE);
|
|
629
|
+
}
|
|
630
|
+
function isBlank(value) {
|
|
631
|
+
return ALL_WHITE_SPACE.test(value);
|
|
632
|
+
}
|
|
633
|
+
function exceedsCodePoints(value, max) {
|
|
634
|
+
if (value.length <= max) return false;
|
|
635
|
+
if (value.length > 2 * max) return true;
|
|
636
|
+
return [...value].length > max;
|
|
637
|
+
}
|
|
638
|
+
function capCodePoints(value, max) {
|
|
639
|
+
if (value.length <= max) return value;
|
|
640
|
+
return [...value].slice(0, max).join("");
|
|
641
|
+
}
|
|
642
|
+
function escapeForLog(value) {
|
|
643
|
+
return value.replace(/[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (c) => `\\u{${c.codePointAt(0).toString(16)}}`);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// src/deadline.ts
|
|
647
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timedOut");
|
|
648
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
649
|
+
async function raceDeadline(work, ms) {
|
|
650
|
+
let timer;
|
|
651
|
+
const deadline = new Promise((resolve) => {
|
|
652
|
+
timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));
|
|
653
|
+
timer.unref?.();
|
|
654
|
+
});
|
|
655
|
+
try {
|
|
656
|
+
return await Promise.race([work, deadline]);
|
|
657
|
+
} finally {
|
|
658
|
+
clearTimeout(timer);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
|
|
662
|
+
|
|
663
|
+
// src/drops.ts
|
|
664
|
+
var RECOVERY_LOG_MS = 6e4;
|
|
665
|
+
var DropCounts = class {
|
|
666
|
+
#instanceId = uuid7();
|
|
667
|
+
#total = /* @__PURE__ */ new Map();
|
|
668
|
+
#sinceDelivery = /* @__PURE__ */ new Map();
|
|
669
|
+
#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
670
|
+
add(reason, n = 1) {
|
|
671
|
+
if (n <= 0) return;
|
|
672
|
+
this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);
|
|
673
|
+
this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);
|
|
674
|
+
}
|
|
675
|
+
total() {
|
|
676
|
+
return Object.fromEntries(this.#total);
|
|
677
|
+
}
|
|
678
|
+
/** Called on each delivery: names what was lost before it, the other half of
|
|
679
|
+
* a drop's own warning, which says only that loss started. */
|
|
680
|
+
logRecovery() {
|
|
681
|
+
if (this.#sinceDelivery.size === 0) return;
|
|
682
|
+
const now = performance.now();
|
|
683
|
+
if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;
|
|
684
|
+
const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
|
|
685
|
+
this.#sinceDelivery.clear();
|
|
686
|
+
this.#lastRecoveryLog = now;
|
|
687
|
+
const total = lost.reduce((sum, [, n]) => sum + n, 0);
|
|
688
|
+
warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
|
|
689
|
+
}
|
|
690
|
+
/** For tests: the counts are one per process. */
|
|
691
|
+
/** Names this process in its loss reports (SPEC §11.4.7). */
|
|
692
|
+
get instanceId() {
|
|
693
|
+
return this.#instanceId;
|
|
694
|
+
}
|
|
695
|
+
clear() {
|
|
696
|
+
this.#instanceId = uuid7();
|
|
697
|
+
this.#total.clear();
|
|
698
|
+
this.#sinceDelivery.clear();
|
|
699
|
+
this.#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
var PROCESS_DROPS = new DropCounts();
|
|
703
|
+
|
|
704
|
+
// src/sequence.ts
|
|
705
|
+
var lastSequence = 0;
|
|
706
|
+
function nextClockSequence() {
|
|
707
|
+
const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
|
|
708
|
+
lastSequence = Math.max(lastSequence + 1, nowMicros);
|
|
709
|
+
return lastSequence;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// src/sinks.ts
|
|
713
|
+
var REFUSAL_BODY_MAX_LEN = 500;
|
|
714
|
+
var REFUSAL_LOG_MS = 6e4;
|
|
715
|
+
var SinkClosedError = class extends Error {
|
|
716
|
+
name = "SinkClosedError";
|
|
717
|
+
};
|
|
718
|
+
function isSinkClosed(err) {
|
|
719
|
+
return err instanceof Error && err.name === "SinkClosedError";
|
|
720
|
+
}
|
|
721
|
+
var warnedClosed = /* @__PURE__ */ new WeakSet();
|
|
722
|
+
function droppedAfterClose(sink) {
|
|
723
|
+
PROCESS_DROPS.add("after_close");
|
|
724
|
+
if (warnedClosed.has(sink)) return;
|
|
725
|
+
warnedClosed.add(sink);
|
|
726
|
+
warn("baton: the sink is closed; further events are dropped.");
|
|
727
|
+
}
|
|
560
728
|
async function safeWrite(sink, event) {
|
|
561
729
|
try {
|
|
562
730
|
await sink.write(event);
|
|
563
731
|
} catch (err) {
|
|
564
|
-
|
|
732
|
+
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
733
|
+
PROCESS_DROPS.add("write_failed");
|
|
734
|
+
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
|
|
735
|
+
`);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
function stderrLine(message) {
|
|
739
|
+
process.stderr.write(`${message}
|
|
565
740
|
`);
|
|
741
|
+
}
|
|
742
|
+
function isTimerMs(value) {
|
|
743
|
+
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
744
|
+
}
|
|
745
|
+
function shutdownFlushTimeoutOption(given) {
|
|
746
|
+
if (isTimerMs(given)) return given;
|
|
747
|
+
if (given !== void 0) {
|
|
748
|
+
warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
|
|
749
|
+
}
|
|
750
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
751
|
+
}
|
|
752
|
+
function shutdownBudgetMs(sink) {
|
|
753
|
+
try {
|
|
754
|
+
if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
|
|
755
|
+
const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
|
|
756
|
+
if (isTimerMs(budget)) return budget;
|
|
757
|
+
} catch {
|
|
758
|
+
}
|
|
759
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
760
|
+
}
|
|
761
|
+
function callWithin(sink, method, ms) {
|
|
762
|
+
if (sink[method] === HttpSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
763
|
+
if (sink[method] === MultiSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
764
|
+
return sink[method]();
|
|
765
|
+
}
|
|
766
|
+
async function boundedSinkCall(sink, method, work = () => sink[method]()) {
|
|
767
|
+
const what = `${method}()`;
|
|
768
|
+
const budget = shutdownBudgetMs(sink);
|
|
769
|
+
const ms = budget + 250;
|
|
770
|
+
const settled = Promise.resolve().then(() => work(budget)).then(
|
|
771
|
+
() => void 0,
|
|
772
|
+
(err) => warn(`baton: ${what} failed: ${printable(err)}`)
|
|
773
|
+
);
|
|
774
|
+
if (await raceDeadline(settled, ms) === TIMED_OUT) {
|
|
775
|
+
warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);
|
|
566
776
|
}
|
|
567
777
|
}
|
|
568
778
|
var StdoutSink = class {
|
|
@@ -572,7 +782,7 @@ var StdoutSink = class {
|
|
|
572
782
|
this.stream = options.stream ?? process.stderr;
|
|
573
783
|
}
|
|
574
784
|
async write(event) {
|
|
575
|
-
if (this.closed) throw new
|
|
785
|
+
if (this.closed) throw new SinkClosedError("StdoutSink is closed");
|
|
576
786
|
this.stream.write(JSON.stringify(event) + "\n");
|
|
577
787
|
}
|
|
578
788
|
async flush() {
|
|
@@ -581,6 +791,59 @@ var StdoutSink = class {
|
|
|
581
791
|
this.closed = true;
|
|
582
792
|
}
|
|
583
793
|
};
|
|
794
|
+
var FileSink = class {
|
|
795
|
+
constructor(path) {
|
|
796
|
+
this.path = path;
|
|
797
|
+
}
|
|
798
|
+
path;
|
|
799
|
+
fd = null;
|
|
800
|
+
closed = false;
|
|
801
|
+
async write(event) {
|
|
802
|
+
if (this.closed) throw new SinkClosedError("FileSink is closed");
|
|
803
|
+
this.fd ??= (0, import_node_fs.openSync)(this.path, "a");
|
|
804
|
+
(0, import_node_fs.writeSync)(this.fd, JSON.stringify(event) + "\n");
|
|
805
|
+
}
|
|
806
|
+
async flush() {
|
|
807
|
+
}
|
|
808
|
+
async aclose() {
|
|
809
|
+
if (this.closed) return;
|
|
810
|
+
this.closed = true;
|
|
811
|
+
if (this.fd !== null) {
|
|
812
|
+
(0, import_node_fs.closeSync)(this.fd);
|
|
813
|
+
this.fd = null;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
var MultiSink = class {
|
|
818
|
+
sinks;
|
|
819
|
+
constructor(sinks) {
|
|
820
|
+
if (sinks.length === 0) throw new Error("MultiSink requires at least one sink");
|
|
821
|
+
this.sinks = [...sinks];
|
|
822
|
+
}
|
|
823
|
+
write(event) {
|
|
824
|
+
return this.fanOut((sink) => sink.write(event));
|
|
825
|
+
}
|
|
826
|
+
flush() {
|
|
827
|
+
return this.flushWithin(Infinity);
|
|
828
|
+
}
|
|
829
|
+
aclose() {
|
|
830
|
+
return this.acloseWithin(Infinity);
|
|
831
|
+
}
|
|
832
|
+
flushWithin(ms) {
|
|
833
|
+
return this.fanOut((sink) => callWithin(sink, "flush", ms));
|
|
834
|
+
}
|
|
835
|
+
acloseWithin(ms) {
|
|
836
|
+
return this.fanOut((sink) => callWithin(sink, "aclose", ms));
|
|
837
|
+
}
|
|
838
|
+
async fanOut(op) {
|
|
839
|
+
const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
|
|
840
|
+
let errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
841
|
+
if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));
|
|
842
|
+
if (errors.length === 0) return;
|
|
843
|
+
if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];
|
|
844
|
+
throw new AggregateError(errors, "MultiSink fan-out failures");
|
|
845
|
+
}
|
|
846
|
+
};
|
|
584
847
|
var CircuitBreaker = class {
|
|
585
848
|
constructor(threshold, resetMs) {
|
|
586
849
|
this.threshold = threshold;
|
|
@@ -610,19 +873,43 @@ var HttpSink = class _HttpSink {
|
|
|
610
873
|
apiKey;
|
|
611
874
|
buffer = [];
|
|
612
875
|
bufferSize;
|
|
876
|
+
requestTimeoutMs;
|
|
877
|
+
shutdownFlushTimeoutMs;
|
|
878
|
+
/** Set when an exit pass ends; cleared once a normal drain empties the
|
|
879
|
+
* buffer, which means the process went on. */
|
|
880
|
+
exitPassRan = false;
|
|
881
|
+
/** Whether the exit pass warned about every event now buffered. */
|
|
882
|
+
unsentWarned = false;
|
|
613
883
|
maxRetries;
|
|
614
884
|
backoffBaseMs;
|
|
615
885
|
backoffMaxMs;
|
|
616
886
|
circuit;
|
|
617
887
|
fetchImpl;
|
|
618
888
|
overflowWarned = false;
|
|
619
|
-
|
|
889
|
+
/** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
|
|
890
|
+
refusals = /* @__PURE__ */ new Map();
|
|
891
|
+
/** Aborted once `aclose()` returns: nothing Baton started may keep the
|
|
892
|
+
* process alive after the vendor closed it. */
|
|
893
|
+
closing = new AbortController();
|
|
894
|
+
/** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */
|
|
895
|
+
stalledDrain = null;
|
|
896
|
+
skipWarnedFor = null;
|
|
897
|
+
closeOnce;
|
|
620
898
|
drainChain = Promise.resolve();
|
|
621
|
-
|
|
899
|
+
exitHooks = null;
|
|
900
|
+
/** The least time between two of this sink's loss reports. */
|
|
901
|
+
static reportIntervalMs = 6e4;
|
|
902
|
+
/** Totals only grow, so their sum tells whether they changed. */
|
|
903
|
+
reportedSum = 0;
|
|
904
|
+
lastReportAt = -Infinity;
|
|
905
|
+
reportsStopped = false;
|
|
906
|
+
reportInFlight = null;
|
|
622
907
|
constructor(url, options) {
|
|
623
908
|
this.url = url.replace(/\/+$/, "");
|
|
624
909
|
this.apiKey = options.apiKey;
|
|
625
910
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
911
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
912
|
+
this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
|
|
626
913
|
this.maxRetries = options.maxRetries ?? 3;
|
|
627
914
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
628
915
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -638,9 +925,7 @@ var HttpSink = class _HttpSink {
|
|
|
638
925
|
* ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
|
|
639
926
|
* hangs off `BatonHandle.sink` and off the resolved config, so
|
|
640
927
|
* `console.log(handle.sink)` or a structured logger serialising either one
|
|
641
|
-
*
|
|
642
|
-
* asserts the DSN's own string does not survive resolution: it does not, and
|
|
643
|
-
* the key was one field further down. Same treatment as the parsed DSN —
|
|
928
|
+
* would write a publishable key into the vendor's logs. Same treatment as the parsed DSN —
|
|
644
929
|
* `toJSON` for serialisers, the inspect symbol for `console.log`, and
|
|
645
930
|
* `Symbol.for` rather than importing `node:util`, since this package runs on
|
|
646
931
|
* runtimes that have no such module.
|
|
@@ -651,29 +936,84 @@ var HttpSink = class _HttpSink {
|
|
|
651
936
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
652
937
|
return this.toJSON();
|
|
653
938
|
}
|
|
939
|
+
get closed() {
|
|
940
|
+
return this.closing.signal.aborted;
|
|
941
|
+
}
|
|
654
942
|
async write(event) {
|
|
655
|
-
if (this.closed) throw new
|
|
943
|
+
if (this.closed) throw new SinkClosedError("HttpSink is closed");
|
|
656
944
|
this.enqueue(event);
|
|
945
|
+
this.unsentWarned = false;
|
|
657
946
|
void this.scheduleDrain();
|
|
658
|
-
this.
|
|
947
|
+
this.ensureExitHooksRegistered();
|
|
659
948
|
}
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
await this.scheduleDrain();
|
|
949
|
+
flush() {
|
|
950
|
+
return this.flushWithin(Infinity);
|
|
663
951
|
}
|
|
664
|
-
|
|
952
|
+
/** A second call waits for the first (SPEC §11.2 rule 7). */
|
|
953
|
+
aclose() {
|
|
954
|
+
return this.acloseWithin(Infinity);
|
|
955
|
+
}
|
|
956
|
+
async flushWithin(ms) {
|
|
665
957
|
if (this.closed) return;
|
|
666
|
-
await this.flush();
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
958
|
+
await this.drainWithinBudget("flush()", Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
959
|
+
}
|
|
960
|
+
acloseWithin(ms) {
|
|
961
|
+
this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
962
|
+
return this.closeOnce;
|
|
963
|
+
}
|
|
964
|
+
async close(ms) {
|
|
965
|
+
this.stopReports();
|
|
966
|
+
await this.drainWithinBudget("aclose()", ms);
|
|
967
|
+
this.closing.abort();
|
|
968
|
+
if (this.buffer.length > 0) {
|
|
969
|
+
PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
|
|
970
|
+
warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
|
|
971
|
+
}
|
|
972
|
+
this.warnUnloggedRefusals("the sink closed");
|
|
973
|
+
if (this.exitHooks) {
|
|
974
|
+
process.off("beforeExit", this.exitHooks.beforeExit);
|
|
975
|
+
process.off("exit", this.exitHooks.exit);
|
|
976
|
+
this.exitHooks = null;
|
|
671
977
|
}
|
|
672
978
|
}
|
|
979
|
+
/** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
|
|
980
|
+
* never rejects. While an earlier wait's drain is still stuck, a flush
|
|
981
|
+
* returns at once, without queuing a pass, and a close gives it `ms`. The
|
|
982
|
+
* drain is not cancelled here, so after `flush()` it goes on sending;
|
|
983
|
+
* `aclose()` stops it. */
|
|
984
|
+
async drainWithinBudget(what, ms) {
|
|
985
|
+
if (this.stalledDrain) {
|
|
986
|
+
if (what === "aclose()") {
|
|
987
|
+
await raceDeadline(this.stalledDrain, ms);
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
if (this.skipWarnedFor !== this.stalledDrain) {
|
|
991
|
+
this.skipWarnedFor = this.stalledDrain;
|
|
992
|
+
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
|
|
993
|
+
}
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
const settled = this.scheduleDrain().catch(() => void 0);
|
|
997
|
+
if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
|
|
998
|
+
if (ms < this.shutdownFlushTimeoutMs) return;
|
|
999
|
+
const stalled = this.drainChain.catch(() => void 0);
|
|
1000
|
+
this.stalledDrain = stalled;
|
|
1001
|
+
void stalled.then(() => {
|
|
1002
|
+
if (this.stalledDrain === stalled) this.stalledDrain = null;
|
|
1003
|
+
});
|
|
1004
|
+
if (what === "flush()") {
|
|
1005
|
+
warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
/** A full buffer may already have pushed `event` out while it was being sent. */
|
|
1009
|
+
dequeue(event) {
|
|
1010
|
+
if (this.buffer[0] === event) this.buffer.shift();
|
|
1011
|
+
}
|
|
673
1012
|
enqueue(event) {
|
|
674
1013
|
if (this.buffer.length >= this.bufferSize) {
|
|
1014
|
+
PROCESS_DROPS.add("buffer_full");
|
|
675
1015
|
if (!this.overflowWarned) {
|
|
676
|
-
|
|
1016
|
+
warn(
|
|
677
1017
|
`Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
|
|
678
1018
|
);
|
|
679
1019
|
this.overflowWarned = true;
|
|
@@ -695,18 +1035,58 @@ var HttpSink = class _HttpSink {
|
|
|
695
1035
|
return this.drainChain;
|
|
696
1036
|
}
|
|
697
1037
|
/** Best-effort flush when the process is about to exit without an
|
|
698
|
-
* explicit `aclose()`.
|
|
699
|
-
*
|
|
700
|
-
*
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
1038
|
+
* explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
|
|
1039
|
+
* both hooks: a vendor needing that guarantee must call `aclose()` from
|
|
1040
|
+
* their own handler. */
|
|
1041
|
+
ensureExitHooksRegistered() {
|
|
1042
|
+
if (this.exitHooks) return;
|
|
1043
|
+
const beforeExit = () => {
|
|
1044
|
+
if (this.buffer.length === 0 || this.exitPassRan) {
|
|
1045
|
+
this.warnUnloggedRefusals("process exiting");
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
this.drainChain = this.drainChain.then(
|
|
1049
|
+
() => this.exitPass(),
|
|
1050
|
+
() => this.exitPass()
|
|
1051
|
+
);
|
|
708
1052
|
};
|
|
709
|
-
|
|
1053
|
+
const exit = () => {
|
|
1054
|
+
try {
|
|
1055
|
+
if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
|
|
1056
|
+
this.warnUnloggedRefusals("process exiting", stderrLine);
|
|
1057
|
+
} catch {
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
this.exitHooks = { beforeExit, exit };
|
|
1061
|
+
process.on("beforeExit", beforeExit);
|
|
1062
|
+
process.on("exit", exit);
|
|
1063
|
+
}
|
|
1064
|
+
/** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
|
|
1065
|
+
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
1066
|
+
async exitPass() {
|
|
1067
|
+
const deadline = Date.now() + this.shutdownFlushTimeoutMs;
|
|
1068
|
+
while (this.buffer.length > 0 && this.circuit.canRequest()) {
|
|
1069
|
+
const timeLeft = deadline - Date.now();
|
|
1070
|
+
if (timeLeft <= 0) break;
|
|
1071
|
+
const event = this.buffer[0];
|
|
1072
|
+
const body = this.encode(event);
|
|
1073
|
+
if (body !== null) {
|
|
1074
|
+
const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
|
|
1075
|
+
if (outcome === "transient_failure") {
|
|
1076
|
+
this.circuit.recordFailure();
|
|
1077
|
+
break;
|
|
1078
|
+
}
|
|
1079
|
+
this.circuit.recordSuccess();
|
|
1080
|
+
}
|
|
1081
|
+
this.dequeue(event);
|
|
1082
|
+
}
|
|
1083
|
+
this.exitPassRan = true;
|
|
1084
|
+
this.unsentWarned = true;
|
|
1085
|
+
if (this.buffer.length > 0) warn(this.unsentAtExit());
|
|
1086
|
+
this.warnUnloggedRefusals("process exiting");
|
|
1087
|
+
}
|
|
1088
|
+
unsentAtExit() {
|
|
1089
|
+
return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
|
|
710
1090
|
}
|
|
711
1091
|
events_url() {
|
|
712
1092
|
return `${this.url}/v0/events`;
|
|
@@ -719,38 +1099,197 @@ var HttpSink = class _HttpSink {
|
|
|
719
1099
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
720
1100
|
return "transient_failure";
|
|
721
1101
|
}
|
|
1102
|
+
/** A refused event is otherwise dropped silently, which looks the same from
|
|
1103
|
+
* the vendor's process as an accepted one. The collector's own message is
|
|
1104
|
+
* logged because it names the field at fault; it is capped and escaped
|
|
1105
|
+
* because it is a remote server's text landing in the vendor's log. */
|
|
1106
|
+
static async logRefusal(response, unlogged) {
|
|
1107
|
+
const detail = await _HttpSink.readHead(response).then(
|
|
1108
|
+
(text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
|
|
1109
|
+
() => "<unreadable>"
|
|
1110
|
+
);
|
|
1111
|
+
warn(
|
|
1112
|
+
`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.` : "")
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
1115
|
+
warnUnloggedRefusals(when, emit2 = warn) {
|
|
1116
|
+
let total = 0;
|
|
1117
|
+
for (const seen of this.refusals.values()) {
|
|
1118
|
+
total += seen.unlogged;
|
|
1119
|
+
seen.unlogged = 0;
|
|
1120
|
+
}
|
|
1121
|
+
if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
|
|
1122
|
+
}
|
|
1123
|
+
/** How many refusals with `status` went unlogged before this one, or `null`
|
|
1124
|
+
* when this one goes unlogged too. */
|
|
1125
|
+
refusalToLog(status) {
|
|
1126
|
+
const now = performance.now();
|
|
1127
|
+
const seen = this.refusals.get(status);
|
|
1128
|
+
if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
|
|
1129
|
+
seen.unlogged++;
|
|
1130
|
+
return null;
|
|
1131
|
+
}
|
|
1132
|
+
this.refusals.set(status, { loggedAt: now, unlogged: 0 });
|
|
1133
|
+
return seen?.unlogged ?? 0;
|
|
1134
|
+
}
|
|
1135
|
+
/** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
|
|
1136
|
+
* cancelled unread, so a large error page does not hold the drain. */
|
|
1137
|
+
static async readHead(response) {
|
|
1138
|
+
const reader = response.body?.getReader();
|
|
1139
|
+
if (reader === void 0) return "";
|
|
1140
|
+
const decoder = new TextDecoder();
|
|
1141
|
+
let text = "";
|
|
1142
|
+
try {
|
|
1143
|
+
while (text.length < REFUSAL_BODY_MAX_LEN * 2) {
|
|
1144
|
+
const { done, value } = await reader.read();
|
|
1145
|
+
if (done) return text + decoder.decode();
|
|
1146
|
+
text += decoder.decode(value, { stream: true });
|
|
1147
|
+
}
|
|
1148
|
+
return text;
|
|
1149
|
+
} finally {
|
|
1150
|
+
void reader.cancel().catch(() => {
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
722
1154
|
async drainLocked() {
|
|
723
1155
|
while (this.buffer.length > 0) {
|
|
724
|
-
if (!this.circuit.canRequest()) return;
|
|
1156
|
+
if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
|
|
725
1157
|
const event = this.buffer[0];
|
|
726
1158
|
const outcome = await this.sendWithRetry(event);
|
|
727
1159
|
if (outcome === "success" || outcome === "permanent_failure") {
|
|
728
|
-
this.
|
|
1160
|
+
this.dequeue(event);
|
|
729
1161
|
this.circuit.recordSuccess();
|
|
1162
|
+
if (outcome === "success") {
|
|
1163
|
+
PROCESS_DROPS.logRecovery();
|
|
1164
|
+
this.maybeReport(event);
|
|
1165
|
+
}
|
|
1166
|
+
} else if (outcome === "unencodable") {
|
|
1167
|
+
this.dequeue(event);
|
|
730
1168
|
} else {
|
|
731
1169
|
this.circuit.recordFailure();
|
|
732
1170
|
return;
|
|
733
1171
|
}
|
|
734
1172
|
}
|
|
1173
|
+
this.exitPassRan = false;
|
|
1174
|
+
}
|
|
1175
|
+
/** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
|
|
1176
|
+
* drain and outside the buffer, so it never delays an event and is never
|
|
1177
|
+
* counted as one. */
|
|
1178
|
+
maybeReport({ tenant_id, vendor_id, consent_token }) {
|
|
1179
|
+
const now = performance.now();
|
|
1180
|
+
if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
|
|
1181
|
+
return;
|
|
1182
|
+
}
|
|
1183
|
+
const totals = PROCESS_DROPS.total();
|
|
1184
|
+
const sum = Object.values(totals).reduce((a, b) => a + b, 0);
|
|
1185
|
+
if (sum === this.reportedSum) return;
|
|
1186
|
+
this.lastReportAt = now;
|
|
1187
|
+
const abort = new AbortController();
|
|
1188
|
+
this.reportInFlight = abort;
|
|
1189
|
+
const envelope = { tenant_id, vendor_id, consent_token };
|
|
1190
|
+
void this.sendReport(envelope, totals, sum, abort).finally(() => {
|
|
1191
|
+
this.reportInFlight = null;
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
stopReports() {
|
|
1195
|
+
this.reportsStopped = true;
|
|
1196
|
+
this.reportInFlight?.abort();
|
|
1197
|
+
}
|
|
1198
|
+
async sendReport(envelope, totals, sum, abort) {
|
|
1199
|
+
const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
|
|
1200
|
+
try {
|
|
1201
|
+
const report = ClientReportEventSchema.parse({
|
|
1202
|
+
...envelope,
|
|
1203
|
+
session_id: PROCESS_DROPS.instanceId,
|
|
1204
|
+
sequence_number: nextClockSequence(),
|
|
1205
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1206
|
+
payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
|
|
1207
|
+
});
|
|
1208
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1209
|
+
method: "POST",
|
|
1210
|
+
headers: this.authHeaders(),
|
|
1211
|
+
body: JSON.stringify(report),
|
|
1212
|
+
signal: abort.signal
|
|
1213
|
+
});
|
|
1214
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1215
|
+
if (response.status === 400 || response.status === 422) this.reportsStopped = true;
|
|
1216
|
+
else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
|
|
1217
|
+
} catch {
|
|
1218
|
+
} finally {
|
|
1219
|
+
clearTimeout(timer);
|
|
1220
|
+
}
|
|
735
1221
|
}
|
|
736
1222
|
async sendWithRetry(event) {
|
|
737
|
-
const
|
|
738
|
-
|
|
739
|
-
const body = JSON.stringify(event);
|
|
1223
|
+
const body = this.encode(event);
|
|
1224
|
+
if (body === null) return "unencodable";
|
|
740
1225
|
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
const outcome = _HttpSink.classifyStatus(response.status);
|
|
744
|
-
if (outcome !== "transient_failure") return outcome;
|
|
745
|
-
} catch {
|
|
746
|
-
}
|
|
1226
|
+
const outcome = await this.postOnce(body, this.requestTimeoutMs);
|
|
1227
|
+
if (outcome !== "transient_failure") return outcome;
|
|
747
1228
|
if (attempt < this.maxRetries) {
|
|
748
1229
|
const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
|
|
749
|
-
await
|
|
1230
|
+
await this.sleepUnlessClosed(backoff);
|
|
1231
|
+
if (this.closing.signal.aborted) return "transient_failure";
|
|
750
1232
|
}
|
|
751
1233
|
}
|
|
752
1234
|
return "transient_failure";
|
|
753
1235
|
}
|
|
1236
|
+
/** `null`, with a warning, for an event `JSON.stringify` rejects. */
|
|
1237
|
+
encode(event) {
|
|
1238
|
+
try {
|
|
1239
|
+
return JSON.stringify(event);
|
|
1240
|
+
} catch (err) {
|
|
1241
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1242
|
+
warn(
|
|
1243
|
+
`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.`
|
|
1244
|
+
);
|
|
1245
|
+
return null;
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
sleepUnlessClosed(ms) {
|
|
1249
|
+
if (this.closed) return Promise.resolve();
|
|
1250
|
+
return new Promise((resolve) => {
|
|
1251
|
+
const done = () => {
|
|
1252
|
+
clearTimeout(timer);
|
|
1253
|
+
this.closing.signal.removeEventListener("abort", done);
|
|
1254
|
+
resolve();
|
|
1255
|
+
};
|
|
1256
|
+
const timer = setTimeout(done, ms);
|
|
1257
|
+
this.closing.signal.addEventListener("abort", done);
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
/** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
|
|
1261
|
+
* is missing before Node 20.3, and on some later versions it keeps every
|
|
1262
|
+
* combined signal alive as long as the long-lived `closing` signal. */
|
|
1263
|
+
async postOnce(body, timeoutMs) {
|
|
1264
|
+
const request = new AbortController();
|
|
1265
|
+
const abort = () => request.abort();
|
|
1266
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
1267
|
+
this.closing.signal.addEventListener("abort", abort);
|
|
1268
|
+
try {
|
|
1269
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1270
|
+
method: "POST",
|
|
1271
|
+
headers: this.authHeaders(),
|
|
1272
|
+
body,
|
|
1273
|
+
signal: request.signal
|
|
1274
|
+
});
|
|
1275
|
+
const outcome = _HttpSink.classifyStatus(response.status);
|
|
1276
|
+
if (outcome === "permanent_failure") {
|
|
1277
|
+
PROCESS_DROPS.add("refused");
|
|
1278
|
+
const unlogged = this.refusalToLog(response.status);
|
|
1279
|
+
if (unlogged !== null) {
|
|
1280
|
+
await _HttpSink.logRefusal(response, unlogged);
|
|
1281
|
+
return outcome;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1285
|
+
return outcome;
|
|
1286
|
+
} catch {
|
|
1287
|
+
return "transient_failure";
|
|
1288
|
+
} finally {
|
|
1289
|
+
clearTimeout(timer);
|
|
1290
|
+
this.closing.signal.removeEventListener("abort", abort);
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
754
1293
|
};
|
|
755
1294
|
|
|
756
1295
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -762,11 +1301,6 @@ var import_zod2 = require("zod");
|
|
|
762
1301
|
// src/metaCoordinates.ts
|
|
763
1302
|
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
764
1303
|
var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
765
|
-
function isPlainObject2(value) {
|
|
766
|
-
if (typeof value !== "object" || value === null) return false;
|
|
767
|
-
const proto = Object.getPrototypeOf(value);
|
|
768
|
-
return proto === Object.prototype || proto === null;
|
|
769
|
-
}
|
|
770
1304
|
function toOneDecimal(value) {
|
|
771
1305
|
const magnitude = Math.abs(value);
|
|
772
1306
|
if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
|
|
@@ -787,7 +1321,7 @@ function roundCoordinate(value) {
|
|
|
787
1321
|
}
|
|
788
1322
|
function walk(value, depth) {
|
|
789
1323
|
if (depth >= DEPTH_LIMIT) return value;
|
|
790
|
-
if (
|
|
1324
|
+
if (isPlainObject(value)) {
|
|
791
1325
|
const out = {};
|
|
792
1326
|
for (const [k, v] of Object.entries(value)) {
|
|
793
1327
|
const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
|
|
@@ -804,126 +1338,6 @@ function roundMetaCoordinates(meta) {
|
|
|
804
1338
|
return walk(meta, 0);
|
|
805
1339
|
}
|
|
806
1340
|
|
|
807
|
-
// src/_text.ts
|
|
808
|
-
function exceedsCodePoints(value, max) {
|
|
809
|
-
if (value.length <= max) return false;
|
|
810
|
-
if (value.length > 2 * max) return true;
|
|
811
|
-
return [...value].length > max;
|
|
812
|
-
}
|
|
813
|
-
function capCodePoints(value, max) {
|
|
814
|
-
if (value.length <= max) return value;
|
|
815
|
-
return [...value].slice(0, max).join("");
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
// src/identity.ts
|
|
819
|
-
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
820
|
-
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
821
|
-
var PRINCIPAL_FORM_RAW = "raw";
|
|
822
|
-
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
823
|
-
var DISPLAY_NAME_MAX_LEN = 128;
|
|
824
|
-
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
825
|
-
function wireDisplayName(value) {
|
|
826
|
-
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
827
|
-
if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
|
|
828
|
-
return value;
|
|
829
|
-
}
|
|
830
|
-
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
831
|
-
var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
832
|
-
var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
|
|
833
|
-
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
834
|
-
function pythonStrip(value) {
|
|
835
|
-
return value.replace(PYTHON_STRIP, "");
|
|
836
|
-
}
|
|
837
|
-
function usableId(id) {
|
|
838
|
-
if (typeof id !== "string") return false;
|
|
839
|
-
if (LONE_SURROGATE.test(id)) return false;
|
|
840
|
-
if (id.includes("\0")) return false;
|
|
841
|
-
return pythonStrip(id) !== "";
|
|
842
|
-
}
|
|
843
|
-
function readIdentity(result, idKey) {
|
|
844
|
-
if (result === null || typeof result !== "object") return null;
|
|
845
|
-
const candidate = result;
|
|
846
|
-
const id = candidate[idKey];
|
|
847
|
-
if (!usableId(id)) return null;
|
|
848
|
-
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
849
|
-
return { id, form: candidate.form, displayName };
|
|
850
|
-
}
|
|
851
|
-
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
852
|
-
function callerFor(result, warn4) {
|
|
853
|
-
try {
|
|
854
|
-
return readCaller(result, warn4);
|
|
855
|
-
} catch {
|
|
856
|
-
warn4("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
857
|
-
return NO_CALLER;
|
|
858
|
-
}
|
|
859
|
-
}
|
|
860
|
-
function readCaller(result, warn4) {
|
|
861
|
-
if (result === void 0 || result === null) return NO_CALLER;
|
|
862
|
-
if (typeof result !== "object") {
|
|
863
|
-
warn4("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
864
|
-
return NO_CALLER;
|
|
865
|
-
}
|
|
866
|
-
if (!("principalId" in result) && !("organization" in result)) {
|
|
867
|
-
if ("organizationId" in result) {
|
|
868
|
-
return { principal: null, organization: identityFor(result, "organization", warn4) };
|
|
869
|
-
}
|
|
870
|
-
if (typeof result.userId === "string") {
|
|
871
|
-
warn4(
|
|
872
|
-
"user-id",
|
|
873
|
-
"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."
|
|
874
|
-
);
|
|
875
|
-
} else {
|
|
876
|
-
warn4("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
877
|
-
}
|
|
878
|
-
return NO_CALLER;
|
|
879
|
-
}
|
|
880
|
-
if ("organizationId" in result) {
|
|
881
|
-
warn4("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
882
|
-
}
|
|
883
|
-
const nested = result.organization;
|
|
884
|
-
return {
|
|
885
|
-
principal: identityFor(result, "principal", warn4),
|
|
886
|
-
organization: nested == null ? null : identityFor(nested, "organization", warn4)
|
|
887
|
-
};
|
|
888
|
-
}
|
|
889
|
-
function identityFor(value, member, warn4) {
|
|
890
|
-
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
891
|
-
const identity = readIdentity(value, idKey);
|
|
892
|
-
if (identity === null) {
|
|
893
|
-
warn4(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
894
|
-
return null;
|
|
895
|
-
}
|
|
896
|
-
return identityWire(
|
|
897
|
-
identity.id,
|
|
898
|
-
identity.form,
|
|
899
|
-
identity.displayName,
|
|
900
|
-
(form) => warn4(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
901
|
-
);
|
|
902
|
-
}
|
|
903
|
-
function describeForm(form) {
|
|
904
|
-
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
905
|
-
}
|
|
906
|
-
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
907
|
-
let form = PRINCIPAL_FORM_RAW;
|
|
908
|
-
if (stated !== void 0) {
|
|
909
|
-
if (PRINCIPAL_FORMS.has(stated)) {
|
|
910
|
-
form = stated;
|
|
911
|
-
} else {
|
|
912
|
-
onUnregisteredForm?.(stated);
|
|
913
|
-
}
|
|
914
|
-
}
|
|
915
|
-
const wire = {
|
|
916
|
-
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
917
|
-
// an astral id cut at the boundary would ship a lone surrogate.
|
|
918
|
-
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
919
|
-
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
920
|
-
form
|
|
921
|
-
};
|
|
922
|
-
const name = wireDisplayName(displayName);
|
|
923
|
-
if (name !== null) wire.display_name = name;
|
|
924
|
-
return wire;
|
|
925
|
-
}
|
|
926
|
-
|
|
927
1341
|
// src/integrations/mcp/llmText.ts
|
|
928
1342
|
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.`;
|
|
929
1343
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -995,14 +1409,14 @@ var OURS_STARTS = [
|
|
|
995
1409
|
];
|
|
996
1410
|
function endsInOurs(current2, vendor) {
|
|
997
1411
|
if (typeof current2 !== "string") return false;
|
|
998
|
-
const prefix = typeof vendor === "string" && vendor
|
|
1412
|
+
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
999
1413
|
|
|
1000
1414
|
` : "";
|
|
1001
1415
|
if (!current2.startsWith(prefix)) return false;
|
|
1002
1416
|
const rest = current2.slice(prefix.length);
|
|
1003
1417
|
return OURS_STARTS.some((start) => start.test(rest));
|
|
1004
1418
|
}
|
|
1005
|
-
function withVendorInstructions(server, ours,
|
|
1419
|
+
function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
|
|
1006
1420
|
const holder = server;
|
|
1007
1421
|
const current2 = holder._instructions;
|
|
1008
1422
|
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
@@ -1010,12 +1424,12 @@ function withVendorInstructions(server, ours, warn4 = (message) => process.stder
|
|
|
1010
1424
|
vendor = current2;
|
|
1011
1425
|
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
1012
1426
|
}
|
|
1013
|
-
if (typeof vendor !== "string" ||
|
|
1427
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
1014
1428
|
const combined = `${vendor}
|
|
1015
1429
|
|
|
1016
1430
|
${ours}`;
|
|
1017
1431
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
1018
|
-
|
|
1432
|
+
warn3(
|
|
1019
1433
|
`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
|
|
1020
1434
|
`
|
|
1021
1435
|
);
|
|
@@ -1029,17 +1443,17 @@ var SUFFIX = "_annotate";
|
|
|
1029
1443
|
var SLUG_CAP = 30;
|
|
1030
1444
|
var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
|
|
1031
1445
|
var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
|
|
1446
|
+
var SEPARATORS = "\\x1c-\\x1f";
|
|
1447
|
+
var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
|
|
1448
|
+
function pythonStrip(value) {
|
|
1449
|
+
return stripEdges(value, PYTHON_SPACE);
|
|
1450
|
+
}
|
|
1032
1451
|
function isLibraryPlaceholder(serverName, className) {
|
|
1033
1452
|
const stripped = pythonStrip(serverName);
|
|
1034
1453
|
if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
|
|
1035
1454
|
const stem = stripped.replace(RANDOM_SUFFIX, "");
|
|
1036
1455
|
return stem !== stripped && stem === className;
|
|
1037
1456
|
}
|
|
1038
|
-
function warn(message) {
|
|
1039
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1040
|
-
process.emitWarning(message);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
1457
|
function usableServerName(read) {
|
|
1044
1458
|
let name;
|
|
1045
1459
|
let className;
|
|
@@ -1113,13 +1527,117 @@ async function emit(sink, build) {
|
|
|
1113
1527
|
try {
|
|
1114
1528
|
event = build();
|
|
1115
1529
|
} catch (err) {
|
|
1116
|
-
|
|
1530
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1531
|
+
process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
|
|
1117
1532
|
`);
|
|
1118
1533
|
return;
|
|
1119
1534
|
}
|
|
1120
1535
|
await safeWrite(sink, event);
|
|
1121
1536
|
}
|
|
1122
1537
|
|
|
1538
|
+
// src/identity.ts
|
|
1539
|
+
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
1540
|
+
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
1541
|
+
var PRINCIPAL_FORM_RAW = "raw";
|
|
1542
|
+
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
1543
|
+
var DISPLAY_NAME_MAX_LEN = 128;
|
|
1544
|
+
function wireDisplayName(value) {
|
|
1545
|
+
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
1546
|
+
if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
|
|
1547
|
+
return value;
|
|
1548
|
+
}
|
|
1549
|
+
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
1550
|
+
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
1551
|
+
function usableId(id) {
|
|
1552
|
+
if (typeof id !== "string") return false;
|
|
1553
|
+
if (LONE_SURROGATE.test(id)) return false;
|
|
1554
|
+
if (id.includes("\0")) return false;
|
|
1555
|
+
return !isBlank(id);
|
|
1556
|
+
}
|
|
1557
|
+
function readIdentity(result, idKey) {
|
|
1558
|
+
if (result === null || typeof result !== "object") return null;
|
|
1559
|
+
const candidate = result;
|
|
1560
|
+
const id = candidate[idKey];
|
|
1561
|
+
if (!usableId(id)) return null;
|
|
1562
|
+
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
1563
|
+
return { id, form: candidate.form, displayName };
|
|
1564
|
+
}
|
|
1565
|
+
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
1566
|
+
function callerFor(result, warn3) {
|
|
1567
|
+
try {
|
|
1568
|
+
return readCaller(result, warn3);
|
|
1569
|
+
} catch {
|
|
1570
|
+
warn3("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
1571
|
+
return NO_CALLER;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
function readCaller(result, warn3) {
|
|
1575
|
+
if (result === void 0 || result === null) return NO_CALLER;
|
|
1576
|
+
if (typeof result !== "object") {
|
|
1577
|
+
warn3("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
1578
|
+
return NO_CALLER;
|
|
1579
|
+
}
|
|
1580
|
+
if (!("principalId" in result) && !("organization" in result)) {
|
|
1581
|
+
if ("organizationId" in result) {
|
|
1582
|
+
return { principal: null, organization: identityFor(result, "organization", warn3) };
|
|
1583
|
+
}
|
|
1584
|
+
if (typeof result.userId === "string") {
|
|
1585
|
+
warn3(
|
|
1586
|
+
"user-id",
|
|
1587
|
+
"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."
|
|
1588
|
+
);
|
|
1589
|
+
} else {
|
|
1590
|
+
warn3("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
1591
|
+
}
|
|
1592
|
+
return NO_CALLER;
|
|
1593
|
+
}
|
|
1594
|
+
if ("organizationId" in result) {
|
|
1595
|
+
warn3("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
1596
|
+
}
|
|
1597
|
+
const nested = result.organization;
|
|
1598
|
+
return {
|
|
1599
|
+
principal: identityFor(result, "principal", warn3),
|
|
1600
|
+
organization: nested == null ? null : identityFor(nested, "organization", warn3)
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
function identityFor(value, member, warn3) {
|
|
1604
|
+
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
1605
|
+
const identity = readIdentity(value, idKey);
|
|
1606
|
+
if (identity === null) {
|
|
1607
|
+
warn3(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
1608
|
+
return null;
|
|
1609
|
+
}
|
|
1610
|
+
return identityWire(
|
|
1611
|
+
identity.id,
|
|
1612
|
+
identity.form,
|
|
1613
|
+
identity.displayName,
|
|
1614
|
+
(form) => warn3(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
1615
|
+
);
|
|
1616
|
+
}
|
|
1617
|
+
function describeForm(form) {
|
|
1618
|
+
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
1619
|
+
}
|
|
1620
|
+
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
1621
|
+
let form = PRINCIPAL_FORM_RAW;
|
|
1622
|
+
if (stated !== void 0) {
|
|
1623
|
+
if (PRINCIPAL_FORMS.has(stated)) {
|
|
1624
|
+
form = stated;
|
|
1625
|
+
} else {
|
|
1626
|
+
onUnregisteredForm?.(stated);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
const wire = {
|
|
1630
|
+
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
1631
|
+
// an astral id cut at the boundary would ship a lone surrogate.
|
|
1632
|
+
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
1633
|
+
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
1634
|
+
form
|
|
1635
|
+
};
|
|
1636
|
+
const name = wireDisplayName(displayName);
|
|
1637
|
+
if (name !== null) wire.display_name = name;
|
|
1638
|
+
return wire;
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1123
1641
|
// src/integrations/mcp/mcpTypes.ts
|
|
1124
1642
|
function extraAuthInfo(extra) {
|
|
1125
1643
|
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
@@ -1177,24 +1695,14 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
|
1177
1695
|
};
|
|
1178
1696
|
}
|
|
1179
1697
|
var HOOK_TIMEOUT_MS = 5e3;
|
|
1180
|
-
var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
|
|
1181
1698
|
async function withinHookBudget(answer) {
|
|
1182
1699
|
if (!isThenable(answer)) return answer;
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
const first = await Promise.race([answer, deadline]);
|
|
1190
|
-
if (first !== TIMED_OUT) return first;
|
|
1191
|
-
warn(
|
|
1192
|
-
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1193
|
-
);
|
|
1194
|
-
return null;
|
|
1195
|
-
} finally {
|
|
1196
|
-
clearTimeout(timer);
|
|
1197
|
-
}
|
|
1700
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
1701
|
+
if (first !== TIMED_OUT) return first;
|
|
1702
|
+
warn(
|
|
1703
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1704
|
+
);
|
|
1705
|
+
return null;
|
|
1198
1706
|
}
|
|
1199
1707
|
var warned = /* @__PURE__ */ new Set();
|
|
1200
1708
|
function warnOnce(key, message) {
|
|
@@ -1223,7 +1731,7 @@ function scrubOrNull(scrubber, value, field) {
|
|
|
1223
1731
|
if (!warned2.has(field)) {
|
|
1224
1732
|
warned2.add(field);
|
|
1225
1733
|
process.stderr.write(
|
|
1226
|
-
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${
|
|
1734
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
|
|
1227
1735
|
`
|
|
1228
1736
|
);
|
|
1229
1737
|
}
|
|
@@ -1322,9 +1830,9 @@ function registeredHeaders(input) {
|
|
|
1322
1830
|
}
|
|
1323
1831
|
return out;
|
|
1324
1832
|
}
|
|
1325
|
-
function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
1833
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
1326
1834
|
return assemble(
|
|
1327
|
-
orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
|
|
1835
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
1328
1836
|
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
1329
1837
|
);
|
|
1330
1838
|
}
|
|
@@ -1332,16 +1840,19 @@ function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
|
1332
1840
|
// src/integrations/mcp/sessionResolution.ts
|
|
1333
1841
|
async function resolveSessionId(fallbackSessionId, extra) {
|
|
1334
1842
|
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
1335
|
-
return { sessionId: extra.sessionId, origin: "observed" };
|
|
1843
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
1336
1844
|
}
|
|
1337
1845
|
const fromHeader = sessionIdFromHeader(extra);
|
|
1338
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
|
|
1339
|
-
|
|
1846
|
+
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
1847
|
+
if (observeTransport(extra) === "http") {
|
|
1848
|
+
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
1849
|
+
}
|
|
1850
|
+
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
1340
1851
|
}
|
|
1341
1852
|
function sessionIdFromHeader(extra) {
|
|
1342
1853
|
try {
|
|
1343
|
-
const value = extraHeaders(extra)?.get("mcp-session-id")
|
|
1344
|
-
return value ? value : null;
|
|
1854
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
1855
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
1345
1856
|
} catch {
|
|
1346
1857
|
return null;
|
|
1347
1858
|
}
|
|
@@ -1350,7 +1861,7 @@ function sessionIdFromHeader(extra) {
|
|
|
1350
1861
|
// src/integrations/mcp/annotation.ts
|
|
1351
1862
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
1352
1863
|
function isReport(whatHappened) {
|
|
1353
|
-
return typeof whatHappened === "string" && whatHappened
|
|
1864
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
1354
1865
|
}
|
|
1355
1866
|
function registerAnnotationTool(server, options) {
|
|
1356
1867
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
@@ -1393,7 +1904,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1393
1904
|
meta ? roundMetaCoordinates(meta) : null,
|
|
1394
1905
|
"_meta"
|
|
1395
1906
|
);
|
|
1396
|
-
const
|
|
1907
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
1397
1908
|
const caller = await resolveCaller(
|
|
1398
1909
|
options.resolvePrincipal,
|
|
1399
1910
|
{ extra, toolName: name, arguments: args }
|
|
@@ -1403,14 +1914,14 @@ function registerAnnotationTool(server, options) {
|
|
|
1403
1914
|
() => AnnotationEventSchema.parse({
|
|
1404
1915
|
tenant_id: options.tenantId,
|
|
1405
1916
|
vendor_id: options.vendorId,
|
|
1406
|
-
session_id: sessionId,
|
|
1407
|
-
sequence_number: options.counter.
|
|
1917
|
+
session_id: session.sessionId,
|
|
1918
|
+
sequence_number: options.counter.nextFor(session),
|
|
1408
1919
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1409
1920
|
consent_token: options.consentToken,
|
|
1410
1921
|
principal: caller.principal,
|
|
1411
1922
|
organization: caller.organization,
|
|
1412
1923
|
transport_observed: observeTransport(extra),
|
|
1413
|
-
session_id_origin: origin,
|
|
1924
|
+
session_id_origin: session.origin,
|
|
1414
1925
|
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1415
1926
|
runtime_meta: scrubbedMeta,
|
|
1416
1927
|
payload: {
|
|
@@ -1437,7 +1948,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1437
1948
|
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
1438
1949
|
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
1439
1950
|
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
1440
|
-
var NOT_IN_A_KEY = /[\x00\n\r]/;
|
|
1951
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
1441
1952
|
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
1442
1953
|
var SECRET_PREFIX = "baton_sk_";
|
|
1443
1954
|
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
@@ -1448,11 +1959,6 @@ function containsKey(value) {
|
|
|
1448
1959
|
return sweep(value) !== value;
|
|
1449
1960
|
}
|
|
1450
1961
|
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";
|
|
1451
|
-
function warn2(message) {
|
|
1452
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1453
|
-
process.emitWarning(message);
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
1962
|
function splitDsn(raw) {
|
|
1457
1963
|
const schemeEnd = raw.indexOf("://");
|
|
1458
1964
|
if (schemeEnd === -1) return null;
|
|
@@ -1512,7 +2018,7 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1512
2018
|
const ambient = dsnFromEnvironment();
|
|
1513
2019
|
if (ambient === void 0) return void 0;
|
|
1514
2020
|
if (conflicts.length > 0) {
|
|
1515
|
-
|
|
2021
|
+
warn(
|
|
1516
2022
|
`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.`
|
|
1517
2023
|
);
|
|
1518
2024
|
return void 0;
|
|
@@ -1520,10 +2026,8 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1520
2026
|
return ambient;
|
|
1521
2027
|
}
|
|
1522
2028
|
function parseDsn(raw) {
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
}
|
|
1526
|
-
const dsn = raw.trim();
|
|
2029
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
2030
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
1527
2031
|
if (looksLikeAKey(dsn)) {
|
|
1528
2032
|
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
1529
2033
|
}
|
|
@@ -1549,7 +2053,7 @@ function parseDsn(raw) {
|
|
|
1549
2053
|
}
|
|
1550
2054
|
if (NOT_IN_A_KEY.test(key)) {
|
|
1551
2055
|
fail(
|
|
1552
|
-
`dsn ${safe} has a line break or a null inside its key \u2014
|
|
2056
|
+
`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.`
|
|
1553
2057
|
);
|
|
1554
2058
|
}
|
|
1555
2059
|
if (key.includes(":")) {
|
|
@@ -1608,7 +2112,7 @@ function parseDsn(raw) {
|
|
|
1608
2112
|
);
|
|
1609
2113
|
}
|
|
1610
2114
|
if (key.startsWith(SECRET_PREFIX)) {
|
|
1611
|
-
|
|
2115
|
+
warn(
|
|
1612
2116
|
`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.`
|
|
1613
2117
|
);
|
|
1614
2118
|
}
|
|
@@ -1647,7 +2151,7 @@ function requestSideFailureKind(entry, validation) {
|
|
|
1647
2151
|
if (entry.enabled === false) return "tool_disabled";
|
|
1648
2152
|
if (validation === "rejected") return "invalid_argument";
|
|
1649
2153
|
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
1650
|
-
return
|
|
2154
|
+
return REFUSED;
|
|
1651
2155
|
}
|
|
1652
2156
|
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
1653
2157
|
function isErrorResult(value) {
|
|
@@ -1666,7 +2170,7 @@ function errorText(value) {
|
|
|
1666
2170
|
for (const part of content) {
|
|
1667
2171
|
const text = part?.text;
|
|
1668
2172
|
if (typeof text !== "string") continue;
|
|
1669
|
-
const trimmed = text
|
|
2173
|
+
const trimmed = stripWhiteSpace(text);
|
|
1670
2174
|
if (trimmed) parts.push(trimmed);
|
|
1671
2175
|
}
|
|
1672
2176
|
} catch {
|
|
@@ -1846,7 +2350,7 @@ var SWITCH = "BATON_DISABLED";
|
|
|
1846
2350
|
var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
|
|
1847
2351
|
function captureDisabled() {
|
|
1848
2352
|
const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
|
|
1849
|
-
if (value !== void 0 && !OFF_VALUES.has(value
|
|
2353
|
+
if (value !== void 0 && !OFF_VALUES.has(stripWhiteSpace(value).toLowerCase())) {
|
|
1850
2354
|
return SWITCH;
|
|
1851
2355
|
}
|
|
1852
2356
|
return null;
|
|
@@ -1873,13 +2377,31 @@ var DisabledSink = class {
|
|
|
1873
2377
|
}
|
|
1874
2378
|
};
|
|
1875
2379
|
|
|
2380
|
+
// src/integrations/mcp/inputRequired.ts
|
|
2381
|
+
function isInputRequired(result) {
|
|
2382
|
+
try {
|
|
2383
|
+
return isRecord(result) && result.resultType === "input_required";
|
|
2384
|
+
} catch {
|
|
2385
|
+
return false;
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
function resumesPausedCall(extra) {
|
|
2389
|
+
try {
|
|
2390
|
+
const req = extra?.mcpReq;
|
|
2391
|
+
if (req === void 0) return false;
|
|
2392
|
+
return req.inputResponses !== void 0 || req.requestState?.() !== void 0;
|
|
2393
|
+
} catch {
|
|
2394
|
+
return false;
|
|
2395
|
+
}
|
|
2396
|
+
}
|
|
2397
|
+
|
|
1876
2398
|
// src/integrations/mcp/handle.ts
|
|
1877
2399
|
var BatonHandle = class {
|
|
1878
2400
|
sink;
|
|
1879
2401
|
vendorId;
|
|
1880
|
-
/**
|
|
1881
|
-
* when no
|
|
1882
|
-
*
|
|
2402
|
+
/** The install's own session id: what stdio and in-memory calls, and the
|
|
2403
|
+
* surface snapshot, carry when no session id resolves. A call over HTTP
|
|
2404
|
+
* with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */
|
|
1883
2405
|
sessionId;
|
|
1884
2406
|
/** The resolved annotation tool name: `BatonConfig.annotationToolName` if
|
|
1885
2407
|
* set, else derived from the server's own name (`{slug}_annotate`), else
|
|
@@ -1891,19 +2413,25 @@ var BatonHandle = class {
|
|
|
1891
2413
|
this.sessionId = options.sessionId;
|
|
1892
2414
|
this.annotationToolName = options.annotationToolName;
|
|
1893
2415
|
}
|
|
1894
|
-
/** Flush any pending events held by the sink.
|
|
2416
|
+
/** Flush any pending events held by the sink. Never rejects; returns within
|
|
2417
|
+
* the shutdown budget (SPEC §11.2 rule 7). */
|
|
1895
2418
|
async flush() {
|
|
1896
|
-
await this.sink
|
|
2419
|
+
await boundedSinkCall(this.sink, "flush");
|
|
1897
2420
|
}
|
|
1898
|
-
/** Flush and release sink resources
|
|
2421
|
+
/** Flush and release sink resources, on the same terms as `flush()`. */
|
|
1899
2422
|
async aclose() {
|
|
1900
|
-
await this.sink
|
|
2423
|
+
await boundedSinkCall(this.sink, "aclose");
|
|
1901
2424
|
}
|
|
1902
2425
|
};
|
|
1903
2426
|
|
|
1904
2427
|
// src/integrations/mcp/sessionCounter.ts
|
|
1905
2428
|
var SessionCounter = class {
|
|
1906
2429
|
counters = /* @__PURE__ */ new Map();
|
|
2430
|
+
/** A per-call session is numbered by the clock: a counter would keep an
|
|
2431
|
+
* entry for every request the process serves. */
|
|
2432
|
+
nextFor(session) {
|
|
2433
|
+
return session.perCall ? nextClockSequence() : this.next(session.sessionId);
|
|
2434
|
+
}
|
|
1907
2435
|
next(sessionId) {
|
|
1908
2436
|
const current2 = this.counters.get(sessionId) ?? 0;
|
|
1909
2437
|
const next = current2 + 1;
|
|
@@ -1990,6 +2518,7 @@ function toJsonSchemaCompat(schema, opts) {
|
|
|
1990
2518
|
// src/integrations/mcp/schemaCompat.ts
|
|
1991
2519
|
var import_zod3 = require("zod");
|
|
1992
2520
|
var import_v3 = require("zod/v3");
|
|
2521
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
1993
2522
|
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
1994
2523
|
function injectGoalParams(inputSchema, intentParamMode) {
|
|
1995
2524
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
@@ -2068,9 +2597,9 @@ function surfaceHash(surface) {
|
|
|
2068
2597
|
}
|
|
2069
2598
|
function canonicalJson(value) {
|
|
2070
2599
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
2071
|
-
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
2600
|
+
if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
|
|
2072
2601
|
const record = value;
|
|
2073
|
-
const keys = Object.keys(record).sort();
|
|
2602
|
+
const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
|
|
2074
2603
|
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
|
|
2075
2604
|
}
|
|
2076
2605
|
function buildServerMeta(lowlevelServer) {
|
|
@@ -2092,6 +2621,25 @@ function assembleSurface(serverMeta, tools) {
|
|
|
2092
2621
|
tools
|
|
2093
2622
|
};
|
|
2094
2623
|
}
|
|
2624
|
+
var SENT_SURFACES_CAP = 256;
|
|
2625
|
+
var SentSurfaces = class {
|
|
2626
|
+
hashes = /* @__PURE__ */ new Set();
|
|
2627
|
+
wasSent(digest) {
|
|
2628
|
+
if (!this.hashes.has(digest)) return false;
|
|
2629
|
+
this.hashes.delete(digest);
|
|
2630
|
+
this.hashes.add(digest);
|
|
2631
|
+
return true;
|
|
2632
|
+
}
|
|
2633
|
+
mark(digest) {
|
|
2634
|
+
this.hashes.add(digest);
|
|
2635
|
+
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
2636
|
+
this.hashes.delete(this.hashes.values().next().value);
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
unmark(digest) {
|
|
2640
|
+
this.hashes.delete(digest);
|
|
2641
|
+
}
|
|
2642
|
+
};
|
|
2095
2643
|
function buildSeamAugmentations(options) {
|
|
2096
2644
|
return {
|
|
2097
2645
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
@@ -2110,12 +2658,12 @@ var wired = /* @__PURE__ */ new WeakSet();
|
|
|
2110
2658
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
2111
2659
|
var callSlots = new import_node_async_hooks.AsyncLocalStorage();
|
|
2112
2660
|
var SurfaceState = class {
|
|
2113
|
-
constructor(serverMeta,
|
|
2661
|
+
constructor(serverMeta, sentSurfaces) {
|
|
2114
2662
|
this.serverMeta = serverMeta;
|
|
2115
|
-
this.
|
|
2663
|
+
this.sentSurfaces = sentSurfaces;
|
|
2116
2664
|
}
|
|
2117
2665
|
serverMeta;
|
|
2118
|
-
|
|
2666
|
+
sentSurfaces;
|
|
2119
2667
|
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
2120
2668
|
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
2121
2669
|
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
@@ -2172,7 +2720,7 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
2172
2720
|
}
|
|
2173
2721
|
async function openCall(ctx, toolName, extra, params, retired, registered = true) {
|
|
2174
2722
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
2175
|
-
const {
|
|
2723
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2176
2724
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2177
2725
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2178
2726
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
@@ -2186,7 +2734,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2186
2734
|
const common = {
|
|
2187
2735
|
tenant_id: ctx.tenantId,
|
|
2188
2736
|
vendor_id: ctx.vendorId,
|
|
2189
|
-
session_id: sessionId,
|
|
2737
|
+
session_id: session.sessionId,
|
|
2190
2738
|
consent_token: ctx.consentToken,
|
|
2191
2739
|
// Every `...common` site is an event of this call, so `call_id` rides in
|
|
2192
2740
|
// it. `surface_snapshot` is deliberately not among them: it describes the
|
|
@@ -2195,16 +2743,17 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2195
2743
|
principal: caller.principal,
|
|
2196
2744
|
organization: caller.organization,
|
|
2197
2745
|
transport_observed: observeTransport(extra),
|
|
2198
|
-
session_id_origin: origin,
|
|
2746
|
+
session_id_origin: session.origin,
|
|
2199
2747
|
client_observed: observeClient(extra, ctx),
|
|
2200
2748
|
runtime_meta: scrubbedMeta,
|
|
2201
2749
|
call_id: uuid7()
|
|
2202
2750
|
};
|
|
2751
|
+
if (resumesPausedCall(extra)) return { common, session };
|
|
2203
2752
|
await emit(
|
|
2204
2753
|
ctx.sink,
|
|
2205
2754
|
() => ToolCallStartEventSchema.parse({
|
|
2206
2755
|
...common,
|
|
2207
|
-
sequence_number: ctx.counter.
|
|
2756
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2208
2757
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2209
2758
|
payload: {
|
|
2210
2759
|
tool_name: toolName,
|
|
@@ -2217,7 +2766,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2217
2766
|
}
|
|
2218
2767
|
})
|
|
2219
2768
|
);
|
|
2220
|
-
return { common,
|
|
2769
|
+
return { common, session };
|
|
2221
2770
|
}
|
|
2222
2771
|
function batonWrap(nameRef, original, ctx) {
|
|
2223
2772
|
return async (...callArgs) => {
|
|
@@ -2228,23 +2777,22 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2228
2777
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2229
2778
|
const retired = slot?.retired ?? {};
|
|
2230
2779
|
if (slot) slot.retired = {};
|
|
2231
|
-
const { common,
|
|
2780
|
+
const { common, session } = await openCall(ctx, toolName, extra, params, retired);
|
|
2232
2781
|
const terminate = async (build, replacement) => {
|
|
2233
2782
|
if (!slot) {
|
|
2234
|
-
await emit(ctx.sink, build);
|
|
2783
|
+
if (build !== null) await emit(ctx.sink, build);
|
|
2235
2784
|
return;
|
|
2236
2785
|
}
|
|
2237
2786
|
const earlier = slot.flushTerminal;
|
|
2238
2787
|
if (earlier !== null) await earlier(CLEAN_OUTCOME);
|
|
2239
2788
|
slot.flushTerminal = async (outcome) => {
|
|
2240
|
-
await emit(
|
|
2241
|
-
|
|
2242
|
-
() => replacement !== null && outcome.failed ? replacement(outcome) : build()
|
|
2243
|
-
);
|
|
2789
|
+
if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));
|
|
2790
|
+
else if (build !== null) await emit(ctx.sink, build);
|
|
2244
2791
|
};
|
|
2245
2792
|
};
|
|
2246
2793
|
const parkFailure = (build) => terminate(build, null);
|
|
2247
2794
|
const parkSuccess = (build, replacement) => terminate(build, replacement);
|
|
2795
|
+
const parkPause = (replacement) => terminate(null, replacement);
|
|
2248
2796
|
const startedAt = performance.now();
|
|
2249
2797
|
let result;
|
|
2250
2798
|
try {
|
|
@@ -2254,18 +2802,20 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2254
2802
|
await parkFailure(
|
|
2255
2803
|
() => ToolCallErrorEventSchema.parse({
|
|
2256
2804
|
...common,
|
|
2257
|
-
sequence_number: ctx.counter.
|
|
2805
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2258
2806
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2259
2807
|
payload: {
|
|
2260
2808
|
tool_name: toolName,
|
|
2261
2809
|
error_type: errorTypeOf(err),
|
|
2262
|
-
//
|
|
2263
|
-
//
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2810
|
+
// SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
|
|
2811
|
+
// raised message public, so under "off" every one is withheld.
|
|
2812
|
+
...resultDerivedFields(
|
|
2813
|
+
ctx.resultCaptureMode,
|
|
2814
|
+
() => messageOf(err),
|
|
2815
|
+
null,
|
|
2816
|
+
(text) => errorBody(ctx, text),
|
|
2817
|
+
ctx.scrubber
|
|
2818
|
+
),
|
|
2269
2819
|
duration_ms: durationMs2,
|
|
2270
2820
|
// Explicit, though the field is `.optional()` and this is its
|
|
2271
2821
|
// absent value. The schema is deliberately not an emitter (see
|
|
@@ -2285,11 +2835,64 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2285
2835
|
throw err;
|
|
2286
2836
|
}
|
|
2287
2837
|
const durationMs = Math.round(performance.now() - startedAt);
|
|
2838
|
+
const failedAbove = (outcome, failureKind) => ToolCallErrorEventSchema.parse({
|
|
2839
|
+
...common,
|
|
2840
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2841
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2842
|
+
payload: {
|
|
2843
|
+
tool_name: toolName,
|
|
2844
|
+
// The lane the OUTER came back on, not this one's: on 2.x the
|
|
2845
|
+
// conversion failure is converted to a returned `isError` inside
|
|
2846
|
+
// `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
|
|
2847
|
+
// right there. A pause the SDK rejects on 2026-07-28 raises, so
|
|
2848
|
+
// both lanes are reachable.
|
|
2849
|
+
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2850
|
+
// ⚠ The INNER's measurement — the vendor's handler duration —
|
|
2851
|
+
// not the outer's. Every other leg means the same thing by this
|
|
2852
|
+
// member, and widening it here for one failure kind would make
|
|
2853
|
+
// `duration_ms` mean two things in one column.
|
|
2854
|
+
duration_ms: durationMs,
|
|
2855
|
+
// Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.
|
|
2856
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
2857
|
+
// ⚠ **WITHHELD under `"off"`, unlike the three request-side
|
|
2858
|
+
// kinds.** The message quotes the value the tool returned
|
|
2859
|
+
// ("`'not-an-int'` is not of type `integer`"), so it is
|
|
2860
|
+
// result-derived by provenance and goes — which leaves
|
|
2861
|
+
// `failure_kind` as the ONLY surviving signal for an
|
|
2862
|
+
// `output_schema_mismatch` under `"off"`, and is the measurement
|
|
2863
|
+
// that justified putting the member on the wire at all.
|
|
2864
|
+
//
|
|
2865
|
+
// ⚠ `result` is what the CLIENT received — the SDK's own error
|
|
2866
|
+
// envelope — not the vendor's rejected return value. §11.4.3
|
|
2867
|
+
// asks for the envelope that holds the flag and the reason, and
|
|
2868
|
+
// this package's own invariant is that it agrees with the
|
|
2869
|
+
// caller. Recording the rejected output TOO would need a member
|
|
2870
|
+
// nothing on the wire has; the loss is deliberate and worth
|
|
2871
|
+
// knowing when debugging one of these.
|
|
2872
|
+
...resultDerivedFields(
|
|
2873
|
+
ctx.resultCaptureMode,
|
|
2874
|
+
() => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
|
|
2875
|
+
// ⚠ `null` on the `raised` lane, never `undefined`, and the
|
|
2876
|
+
// union is what forces the branch rather than a comment: the
|
|
2877
|
+
// scrubber would answer `undefined` and DROP the key, where the
|
|
2878
|
+
// sibling raise lane a few lines up declares `result: null`
|
|
2879
|
+
// explicitly, for the reason `ToolCallErrorPayloadSchema`
|
|
2880
|
+
// records. One shape for "no result object existed", not two.
|
|
2881
|
+
outcome.raised ? null : outcome.result ?? null,
|
|
2882
|
+
(text) => errorBody(ctx, text),
|
|
2883
|
+
ctx.scrubber
|
|
2884
|
+
)
|
|
2885
|
+
}
|
|
2886
|
+
});
|
|
2887
|
+
if (isInputRequired(result)) {
|
|
2888
|
+
await parkPause(failedAbove);
|
|
2889
|
+
return result;
|
|
2890
|
+
}
|
|
2288
2891
|
if (isErrorResult(result)) {
|
|
2289
2892
|
await parkFailure(
|
|
2290
2893
|
() => ToolCallErrorEventSchema.parse({
|
|
2291
2894
|
...common,
|
|
2292
|
-
sequence_number: ctx.counter.
|
|
2895
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2293
2896
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2294
2897
|
payload: {
|
|
2295
2898
|
tool_name: toolName,
|
|
@@ -2319,7 +2922,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2319
2922
|
await parkSuccess(
|
|
2320
2923
|
() => ToolCallEndEventSchema.parse({
|
|
2321
2924
|
...common,
|
|
2322
|
-
sequence_number: ctx.counter.
|
|
2925
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2323
2926
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2324
2927
|
payload: {
|
|
2325
2928
|
tool_name: toolName,
|
|
@@ -2327,61 +2930,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2327
2930
|
...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
|
|
2328
2931
|
}
|
|
2329
2932
|
}),
|
|
2330
|
-
|
|
2331
|
-
// then the outer seam saw the call fail anyway — so what failed is the
|
|
2332
|
-
// producer's own conversion of the output (SPEC §11.4.3's
|
|
2333
|
-
// `output_schema_mismatch`). Correcting this is the whole point of the
|
|
2334
|
-
// second seam: without it this is a `tool_call_end` for a call the
|
|
2335
|
-
// CALLER saw fail, which is a success the product invented.
|
|
2336
|
-
(outcome) => ToolCallErrorEventSchema.parse({
|
|
2337
|
-
...common,
|
|
2338
|
-
sequence_number: ctx.counter.next(sessionId),
|
|
2339
|
-
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2340
|
-
payload: {
|
|
2341
|
-
tool_name: toolName,
|
|
2342
|
-
// The lane the OUTER came back on, not this one's: on 2.x the
|
|
2343
|
-
// conversion failure is converted to a returned `isError` inside
|
|
2344
|
-
// `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
|
|
2345
|
-
// right there. A throw out of the handler is unreachable on
|
|
2346
|
-
// either major today for this lane; spelled anyway, because the
|
|
2347
|
-
// alternative is a crash on the day it stops being.
|
|
2348
|
-
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2349
|
-
// ⚠ The INNER's measurement — the vendor's handler duration —
|
|
2350
|
-
// not the outer's. Every other leg means the same thing by this
|
|
2351
|
-
// member, and widening it here for one failure kind would make
|
|
2352
|
-
// `duration_ms` mean two things in one column.
|
|
2353
|
-
duration_ms: durationMs,
|
|
2354
|
-
failure_kind: OUTPUT_SCHEMA_MISMATCH,
|
|
2355
|
-
// ⚠ **WITHHELD under `"off"`, unlike the three request-side
|
|
2356
|
-
// kinds.** The message quotes the value the tool returned
|
|
2357
|
-
// ("`'not-an-int'` is not of type `integer`"), so it is
|
|
2358
|
-
// result-derived by provenance and goes — which leaves
|
|
2359
|
-
// `failure_kind` as the ONLY surviving signal for this failure
|
|
2360
|
-
// under `"off"`, and is the measurement that justified putting
|
|
2361
|
-
// the member on the wire at all.
|
|
2362
|
-
//
|
|
2363
|
-
// ⚠ `result` is what the CLIENT received — the SDK's own error
|
|
2364
|
-
// envelope — not the vendor's rejected return value. §11.4.3
|
|
2365
|
-
// asks for the envelope that holds the flag and the reason, and
|
|
2366
|
-
// this package's own invariant is that it agrees with the
|
|
2367
|
-
// caller. Recording the rejected output TOO would need a member
|
|
2368
|
-
// nothing on the wire has; the loss is deliberate and worth
|
|
2369
|
-
// knowing when debugging one of these.
|
|
2370
|
-
...resultDerivedFields(
|
|
2371
|
-
ctx.resultCaptureMode,
|
|
2372
|
-
() => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
|
|
2373
|
-
// ⚠ `null` on the `raised` lane, never `undefined`, and the
|
|
2374
|
-
// union is what forces the branch rather than a comment: the
|
|
2375
|
-
// scrubber would answer `undefined` and DROP the key, where the
|
|
2376
|
-
// sibling raise lane a few lines up declares `result: null`
|
|
2377
|
-
// explicitly, for the reason `ToolCallErrorPayloadSchema`
|
|
2378
|
-
// records. One shape for "no result object existed", not two.
|
|
2379
|
-
outcome.raised ? null : outcome.result ?? null,
|
|
2380
|
-
(text) => errorBody(ctx, text),
|
|
2381
|
-
ctx.scrubber
|
|
2382
|
-
)
|
|
2383
|
-
}
|
|
2384
|
-
})
|
|
2933
|
+
(outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
|
|
2385
2934
|
);
|
|
2386
2935
|
return result;
|
|
2387
2936
|
};
|
|
@@ -2402,7 +2951,7 @@ function popText(args, paramName) {
|
|
|
2402
2951
|
if (!(paramName in args)) return null;
|
|
2403
2952
|
const raw = args[paramName];
|
|
2404
2953
|
delete args[paramName];
|
|
2405
|
-
return typeof raw === "string" && raw
|
|
2954
|
+
return typeof raw === "string" && !isBlank(raw) ? raw : null;
|
|
2406
2955
|
}
|
|
2407
2956
|
function stripRetiredParams(params, ctx) {
|
|
2408
2957
|
const toolName = params?.name;
|
|
@@ -2418,7 +2967,6 @@ function stripRetiredParams(params, ctx) {
|
|
|
2418
2967
|
}
|
|
2419
2968
|
return retired;
|
|
2420
2969
|
}
|
|
2421
|
-
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2422
2970
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2423
2971
|
if (!ctx.surfaceState.dirty) return;
|
|
2424
2972
|
ctx.surfaceState.dirty = false;
|
|
@@ -2432,10 +2980,9 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2432
2980
|
`);
|
|
2433
2981
|
return;
|
|
2434
2982
|
}
|
|
2435
|
-
const
|
|
2436
|
-
if (
|
|
2437
|
-
|
|
2438
|
-
emitted.add(digest);
|
|
2983
|
+
const sent = ctx.surfaceState.sentSurfaces;
|
|
2984
|
+
if (sent.wasSent(digest)) return;
|
|
2985
|
+
sent.mark(digest);
|
|
2439
2986
|
const seam = buildSeamAugmentations({
|
|
2440
2987
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
2441
2988
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -2448,7 +2995,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2448
2995
|
} catch (err) {
|
|
2449
2996
|
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
2450
2997
|
`);
|
|
2451
|
-
|
|
2998
|
+
sent.unmark(digest);
|
|
2452
2999
|
ctx.surfaceState.dirty = true;
|
|
2453
3000
|
}
|
|
2454
3001
|
}
|
|
@@ -2543,17 +3090,18 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2543
3090
|
ctx.sink,
|
|
2544
3091
|
() => schema.parse({
|
|
2545
3092
|
...opened.common,
|
|
2546
|
-
sequence_number: ctx.counter.
|
|
3093
|
+
sequence_number: ctx.counter.nextFor(opened.session),
|
|
2547
3094
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2548
3095
|
payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
|
|
2549
3096
|
})
|
|
2550
3097
|
);
|
|
2551
3098
|
};
|
|
2552
|
-
await fire(spec.schemas.start, spec.startParams(requestParams));
|
|
3099
|
+
if (!resumesPausedCall(extra)) await fire(spec.schemas.start, spec.startParams(requestParams));
|
|
2553
3100
|
const startedAt = performance.now();
|
|
2554
3101
|
const elapsed = () => Math.round(performance.now() - startedAt);
|
|
2555
3102
|
try {
|
|
2556
3103
|
const result = await handler(...args);
|
|
3104
|
+
if (isInputRequired(result)) return result;
|
|
2557
3105
|
await fire(spec.schemas.end, {
|
|
2558
3106
|
...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
|
|
2559
3107
|
duration_ms: elapsed()
|
|
@@ -2575,26 +3123,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2575
3123
|
}
|
|
2576
3124
|
async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
2577
3125
|
try {
|
|
2578
|
-
const
|
|
3126
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2579
3127
|
const caller = await resolveCaller(ctx.resolvePrincipal, {
|
|
2580
3128
|
extra,
|
|
2581
3129
|
toolName: null,
|
|
2582
3130
|
arguments: {}
|
|
2583
3131
|
});
|
|
2584
3132
|
return {
|
|
2585
|
-
|
|
3133
|
+
session,
|
|
2586
3134
|
subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
|
|
2587
3135
|
common: {
|
|
2588
3136
|
tenant_id: ctx.tenantId,
|
|
2589
3137
|
vendor_id: ctx.vendorId,
|
|
2590
|
-
session_id:
|
|
3138
|
+
session_id: session.sessionId,
|
|
2591
3139
|
consent_token: ctx.consentToken,
|
|
2592
3140
|
principal: caller.principal,
|
|
2593
3141
|
organization: caller.organization,
|
|
2594
3142
|
transport_observed: observeTransport(extra),
|
|
2595
|
-
session_id_origin:
|
|
3143
|
+
session_id_origin: session.origin,
|
|
2596
3144
|
client_observed: observeClient(extra, ctx),
|
|
2597
|
-
runtime_meta:
|
|
3145
|
+
runtime_meta: scrubbedMeta
|
|
2598
3146
|
}
|
|
2599
3147
|
};
|
|
2600
3148
|
} catch (err) {
|
|
@@ -2723,7 +3271,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2723
3271
|
innerFired: false,
|
|
2724
3272
|
flushTerminal: null,
|
|
2725
3273
|
retired: stripRetiredParams(request?.params, ctx),
|
|
2726
|
-
validation:
|
|
3274
|
+
validation: "unseen"
|
|
2727
3275
|
};
|
|
2728
3276
|
let outcome = CLEAN_OUTCOME;
|
|
2729
3277
|
try {
|
|
@@ -2743,8 +3291,7 @@ var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
|
2743
3291
|
function installValidationProbe(server) {
|
|
2744
3292
|
const target = server;
|
|
2745
3293
|
const original = target.validateToolInput;
|
|
2746
|
-
if (typeof original !== "function"
|
|
2747
|
-
if (original[VALIDATION_PROBE]) return () => target.validateToolInput === original;
|
|
3294
|
+
if (typeof original !== "function" || original[VALIDATION_PROBE]) return;
|
|
2748
3295
|
const probe = async function(...args) {
|
|
2749
3296
|
const slot = callSlots.getStore();
|
|
2750
3297
|
try {
|
|
@@ -2758,7 +3305,6 @@ function installValidationProbe(server) {
|
|
|
2758
3305
|
};
|
|
2759
3306
|
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
2760
3307
|
target.validateToolInput = probe;
|
|
2761
|
-
return () => target.validateToolInput === probe;
|
|
2762
3308
|
}
|
|
2763
3309
|
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
2764
3310
|
try {
|
|
@@ -2772,6 +3318,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
2772
3318
|
if (!outcome.failed) return;
|
|
2773
3319
|
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
2774
3320
|
} catch (err) {
|
|
3321
|
+
PROCESS_DROPS.add("encode_failed");
|
|
2775
3322
|
process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
|
|
2776
3323
|
`);
|
|
2777
3324
|
}
|
|
@@ -2784,7 +3331,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
2784
3331
|
const entry = toolEntry(toolName);
|
|
2785
3332
|
if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
|
|
2786
3333
|
const params = { ...request?.params?.arguments ?? {} };
|
|
2787
|
-
const { common,
|
|
3334
|
+
const { common, session } = await openCall(
|
|
2788
3335
|
ctx,
|
|
2789
3336
|
toolName,
|
|
2790
3337
|
args[1],
|
|
@@ -2798,7 +3345,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
2798
3345
|
ctx.sink,
|
|
2799
3346
|
() => ToolCallErrorEventSchema.parse({
|
|
2800
3347
|
...common,
|
|
2801
|
-
sequence_number: ctx.counter.
|
|
3348
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2802
3349
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2803
3350
|
payload: {
|
|
2804
3351
|
tool_name: toolName,
|
|
@@ -2914,15 +3461,19 @@ function withBaton(server, supplied = {}) {
|
|
|
2914
3461
|
}
|
|
2915
3462
|
const resolved = resolveBatonConfig(supplied);
|
|
2916
3463
|
warnUnusedReportSettings(resolved);
|
|
2917
|
-
return install(server, supplied, resolved,
|
|
3464
|
+
return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
|
|
2918
3465
|
}
|
|
2919
3466
|
function createBaton(supplied = {}) {
|
|
2920
3467
|
const disabledBy = captureDisabled();
|
|
2921
3468
|
if (disabledBy !== null) {
|
|
2922
3469
|
logDisabled(disabledBy, "createBaton");
|
|
2923
3470
|
const unused = supplied.sink ?? new DisabledSink();
|
|
2924
|
-
return {
|
|
2925
|
-
|
|
3471
|
+
return {
|
|
3472
|
+
wrap: () => {
|
|
3473
|
+
},
|
|
3474
|
+
flush: () => boundedSinkCall(unused, "flush"),
|
|
3475
|
+
aclose: () => boundedSinkCall(unused, "aclose")
|
|
3476
|
+
};
|
|
2926
3477
|
}
|
|
2927
3478
|
const resolved = resolveBatonConfig(supplied);
|
|
2928
3479
|
warnUnusedReportSettings(resolved);
|
|
@@ -2933,17 +3484,17 @@ function createBaton(supplied = {}) {
|
|
|
2933
3484
|
sink,
|
|
2934
3485
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2935
3486
|
};
|
|
2936
|
-
const
|
|
3487
|
+
const sentSurfaces = new SentSurfaces();
|
|
2937
3488
|
const warned3 = /* @__PURE__ */ new Set();
|
|
2938
3489
|
return {
|
|
2939
3490
|
wrap: (server) => {
|
|
2940
|
-
install(server, supplied, config,
|
|
3491
|
+
install(server, supplied, config, sentSurfaces, warned3);
|
|
2941
3492
|
},
|
|
2942
|
-
flush: () => sink
|
|
2943
|
-
aclose: () => sink
|
|
3493
|
+
flush: () => boundedSinkCall(sink, "flush"),
|
|
3494
|
+
aclose: () => boundedSinkCall(sink, "aclose")
|
|
2944
3495
|
};
|
|
2945
3496
|
}
|
|
2946
|
-
function install(server, supplied, resolved,
|
|
3497
|
+
function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
2947
3498
|
const internals = server;
|
|
2948
3499
|
const serverName = usableServerName(() => ({
|
|
2949
3500
|
name: internals.server._serverInfo?.name,
|
|
@@ -2953,13 +3504,13 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2953
3504
|
const sink = config.sink ?? new StdoutSink();
|
|
2954
3505
|
const reports = reportsFor(config);
|
|
2955
3506
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
2956
|
-
const intentParamMode = config.intentParamMode ??
|
|
3507
|
+
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
2957
3508
|
const counter2 = new SessionCounter();
|
|
2958
3509
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
2959
3510
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
2960
3511
|
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
2961
3512
|
const serverMeta = buildServerMeta(server.server);
|
|
2962
|
-
const surfaceState = new SurfaceState(serverMeta,
|
|
3513
|
+
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
2963
3514
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
2964
3515
|
const event = SurfaceSnapshotEventSchema.parse({
|
|
2965
3516
|
tenant_id: tenantId,
|
|
@@ -2978,7 +3529,12 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2978
3529
|
seam_augmentations: snapshot.seam_augmentations
|
|
2979
3530
|
}
|
|
2980
3531
|
});
|
|
2981
|
-
|
|
3532
|
+
try {
|
|
3533
|
+
await sink.write(event);
|
|
3534
|
+
} catch (err) {
|
|
3535
|
+
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
3536
|
+
throw err;
|
|
3537
|
+
}
|
|
2982
3538
|
};
|
|
2983
3539
|
const bustSchemaMemo = (name) => {
|
|
2984
3540
|
const memo = internals._toolInputSchemaJson;
|
|
@@ -3025,6 +3581,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
3025
3581
|
return { type: "object", properties: {} };
|
|
3026
3582
|
}
|
|
3027
3583
|
};
|
|
3584
|
+
installValidationProbe(server);
|
|
3028
3585
|
const ctx = {
|
|
3029
3586
|
sink,
|
|
3030
3587
|
counter: counter2,
|
|
@@ -3037,7 +3594,6 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
3037
3594
|
annotationToolName,
|
|
3038
3595
|
intentParamMode,
|
|
3039
3596
|
resultCaptureMode: config.resultCaptureMode ?? "full",
|
|
3040
|
-
validationProbeLive: installValidationProbe(server),
|
|
3041
3597
|
paramRegistry: /* @__PURE__ */ new Map(),
|
|
3042
3598
|
resolvePrincipal: config.resolvePrincipal,
|
|
3043
3599
|
vendorToolJsonSchema,
|
|
@@ -3128,7 +3684,7 @@ function claimsOf(context) {
|
|
|
3128
3684
|
}
|
|
3129
3685
|
function stringClaim(claims, name) {
|
|
3130
3686
|
const value = claims[name];
|
|
3131
|
-
return typeof value === "string" &&
|
|
3687
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
3132
3688
|
}
|
|
3133
3689
|
function principalFromOAuthSub(context) {
|
|
3134
3690
|
const claims = claimsOf(context);
|
|
@@ -3160,33 +3716,46 @@ function sessionEnvelope(session) {
|
|
|
3160
3716
|
principal: session.principal,
|
|
3161
3717
|
organization: session.organization,
|
|
3162
3718
|
client_observed: session.clientObserved,
|
|
3163
|
-
runtime_meta: session.
|
|
3719
|
+
runtime_meta: session.runtimeMeta
|
|
3164
3720
|
};
|
|
3165
3721
|
}
|
|
3166
|
-
function
|
|
3722
|
+
function warn2(message) {
|
|
3167
3723
|
process.stderr.write(`baton: ${message}
|
|
3168
3724
|
`);
|
|
3169
3725
|
}
|
|
3170
3726
|
function vendorId(name, value) {
|
|
3171
|
-
const cleaned = typeof value === "string" ?
|
|
3727
|
+
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
3172
3728
|
if (cleaned !== "") return cleaned;
|
|
3173
3729
|
if (value !== void 0 && value !== null) {
|
|
3174
|
-
|
|
3730
|
+
warn2(`${name} is not a non-blank string \u2014 ignoring it.`);
|
|
3175
3731
|
}
|
|
3176
3732
|
return null;
|
|
3177
3733
|
}
|
|
3178
3734
|
function blank(sessionId, origin) {
|
|
3179
|
-
return { sessionId, origin, ...NO_CALLER, clientObserved: null,
|
|
3735
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
3736
|
+
}
|
|
3737
|
+
function requestMeta(meta) {
|
|
3738
|
+
if (isRecord(meta)) return meta;
|
|
3739
|
+
if (meta !== void 0 && meta !== null) warn2("meta is not an object \u2014 ignoring it.");
|
|
3740
|
+
return null;
|
|
3741
|
+
}
|
|
3742
|
+
function runtimeMeta(meta, turnId, scrubber) {
|
|
3743
|
+
const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));
|
|
3744
|
+
const cleaned = Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), "_meta") : null;
|
|
3745
|
+
const out = isRecord(cleaned) ? { ...cleaned } : {};
|
|
3746
|
+
if (turnId !== null) out[TURN_ID_META_KEY] = turnId;
|
|
3747
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
3180
3748
|
}
|
|
3181
3749
|
function newSession(values, scrubber, disabled) {
|
|
3182
3750
|
const id = vendorId("sessionId", values.sessionId);
|
|
3183
3751
|
const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
|
|
3184
3752
|
if (disabled) return base;
|
|
3753
|
+
const meta = requestMeta(values.meta);
|
|
3185
3754
|
return {
|
|
3186
3755
|
...base,
|
|
3187
|
-
...callerFor(values.principal, (_key, message) =>
|
|
3188
|
-
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
|
|
3189
|
-
|
|
3756
|
+
...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
|
|
3757
|
+
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
|
|
3758
|
+
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
3190
3759
|
};
|
|
3191
3760
|
}
|
|
3192
3761
|
var current = new import_node_async_hooks2.AsyncLocalStorage();
|
|
@@ -3197,11 +3766,71 @@ function sessionForCall(owner) {
|
|
|
3197
3766
|
const entry = current.getStore();
|
|
3198
3767
|
return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
|
|
3199
3768
|
}
|
|
3200
|
-
|
|
3201
|
-
|
|
3202
|
-
|
|
3203
|
-
|
|
3204
|
-
|
|
3769
|
+
|
|
3770
|
+
// src/library/surface.ts
|
|
3771
|
+
function serveTools(tools, options) {
|
|
3772
|
+
let served;
|
|
3773
|
+
try {
|
|
3774
|
+
served = tools.map(servedEntry);
|
|
3775
|
+
} catch (err) {
|
|
3776
|
+
process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
|
|
3777
|
+
`);
|
|
3778
|
+
return { served: tools, surface: null };
|
|
3779
|
+
}
|
|
3780
|
+
try {
|
|
3781
|
+
const nameOf = (tool) => isRecord(tool) ? String(tool.name) : "";
|
|
3782
|
+
const ordered = [...tools].sort((a, b) => {
|
|
3783
|
+
const [x, y] = [nameOf(a), nameOf(b)];
|
|
3784
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
3785
|
+
});
|
|
3786
|
+
const meta = {
|
|
3787
|
+
server_info: options.serverInfo ?? null,
|
|
3788
|
+
capabilities: options.capabilities ?? null,
|
|
3789
|
+
instructions: options.instructions ?? null
|
|
3790
|
+
};
|
|
3791
|
+
const surface = JSON.parse(
|
|
3792
|
+
JSON.stringify(assembleSurface(meta, ordered))
|
|
3793
|
+
);
|
|
3794
|
+
return { served, surface: { surface, digest: surfaceHash(surface) } };
|
|
3795
|
+
} catch (err) {
|
|
3796
|
+
process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
|
|
3797
|
+
`);
|
|
3798
|
+
return { served, surface: null };
|
|
3799
|
+
}
|
|
3800
|
+
}
|
|
3801
|
+
function snapshotPayload({ surface, digest }) {
|
|
3802
|
+
return {
|
|
3803
|
+
surface_hash: digest,
|
|
3804
|
+
...surface,
|
|
3805
|
+
seam_augmentations: buildSeamAugmentations({
|
|
3806
|
+
injectedToolNames: [],
|
|
3807
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
3808
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
3809
|
+
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
3810
|
+
instructionsSuffix: null
|
|
3811
|
+
})
|
|
3812
|
+
};
|
|
3813
|
+
}
|
|
3814
|
+
function servedEntry(tool) {
|
|
3815
|
+
if (!isRecord(tool)) return tool;
|
|
3816
|
+
const entry = { ...tool };
|
|
3817
|
+
if (isRecord(entry.inputSchema)) {
|
|
3818
|
+
const schema = { ...entry.inputSchema };
|
|
3819
|
+
if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
|
|
3820
|
+
injectGoalParam(schema);
|
|
3821
|
+
entry.inputSchema = schema;
|
|
3822
|
+
}
|
|
3823
|
+
return entry;
|
|
3824
|
+
}
|
|
3825
|
+
function injectGoalParam(schema) {
|
|
3826
|
+
if (schema.properties === void 0) schema.properties = {};
|
|
3827
|
+
if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
|
|
3828
|
+
schema.properties[USER_GOAL_PARAM_NAME] = {
|
|
3829
|
+
type: "string",
|
|
3830
|
+
description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
|
|
3831
|
+
};
|
|
3832
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3833
|
+
if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
|
|
3205
3834
|
}
|
|
3206
3835
|
|
|
3207
3836
|
// src/library/client.ts
|
|
@@ -3264,7 +3893,7 @@ function resolveClientOptions(options) {
|
|
|
3264
3893
|
resultCaptureMode
|
|
3265
3894
|
};
|
|
3266
3895
|
}
|
|
3267
|
-
var hasText2 = (value) => typeof value === "string" &&
|
|
3896
|
+
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
3268
3897
|
function describeError(err) {
|
|
3269
3898
|
let type = "Error";
|
|
3270
3899
|
let body = "";
|
|
@@ -3278,19 +3907,18 @@ function describeError(err) {
|
|
|
3278
3907
|
}
|
|
3279
3908
|
return [type, body];
|
|
3280
3909
|
}
|
|
3281
|
-
function isPlainObject3(value) {
|
|
3282
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3283
|
-
const proto = Object.getPrototypeOf(value);
|
|
3284
|
-
return proto === Object.prototype || proto === null;
|
|
3285
|
-
}
|
|
3286
3910
|
function paramsOf(args) {
|
|
3287
|
-
if (args.length === 1 &&
|
|
3911
|
+
if (args.length === 1 && isPlainObject(args[0])) return args[0];
|
|
3288
3912
|
return args.length === 0 ? {} : { args };
|
|
3289
3913
|
}
|
|
3290
3914
|
var Core = class {
|
|
3291
3915
|
closed = false;
|
|
3292
3916
|
pending = /* @__PURE__ */ new Set();
|
|
3293
3917
|
closedWarned = false;
|
|
3918
|
+
// A snapshot describes the server, so it takes no block's session,
|
|
3919
|
+
// principal or client: SPEC §11.5.1's join must not count it.
|
|
3920
|
+
surfaceSessionId = uuid7();
|
|
3921
|
+
sentSurfaces = new SentSurfaces();
|
|
3294
3922
|
sink;
|
|
3295
3923
|
vendorId;
|
|
3296
3924
|
tenantId;
|
|
@@ -3323,6 +3951,7 @@ var Core = class {
|
|
|
3323
3951
|
live() {
|
|
3324
3952
|
if (this.disabled) return false;
|
|
3325
3953
|
if (!this.closed) return true;
|
|
3954
|
+
PROCESS_DROPS.add("after_close");
|
|
3326
3955
|
if (!this.closedWarned) {
|
|
3327
3956
|
this.closedWarned = true;
|
|
3328
3957
|
process.stderr.write("baton: Client is closed; further events are dropped.\n");
|
|
@@ -3331,19 +3960,70 @@ var Core = class {
|
|
|
3331
3960
|
}
|
|
3332
3961
|
/** Never rejects. Tracked so `flush()` can wait for it. */
|
|
3333
3962
|
emit(build) {
|
|
3334
|
-
|
|
3335
|
-
|
|
3336
|
-
|
|
3963
|
+
return this.track(emit(this.sink, build));
|
|
3964
|
+
}
|
|
3965
|
+
track(work) {
|
|
3966
|
+
const tracked = work.finally(() => this.pending.delete(tracked));
|
|
3967
|
+
this.pending.add(tracked);
|
|
3968
|
+
return tracked;
|
|
3969
|
+
}
|
|
3970
|
+
/** Sends `surface` unless this client already has. Never rejects; a failed
|
|
3971
|
+
* write unmarks it, so the next `listTools` tries again. A surface that does
|
|
3972
|
+
* not fit the schema stays marked: it would fail the same way every time. */
|
|
3973
|
+
sendSurface(surface) {
|
|
3974
|
+
if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
|
|
3975
|
+
this.sentSurfaces.mark(surface.digest);
|
|
3976
|
+
let event;
|
|
3977
|
+
try {
|
|
3978
|
+
event = SurfaceSnapshotEventSchema.parse({
|
|
3979
|
+
tenant_id: this.tenantId,
|
|
3980
|
+
vendor_id: this.vendorId,
|
|
3981
|
+
session_id: this.surfaceSessionId,
|
|
3982
|
+
session_id_origin: "minted",
|
|
3983
|
+
sequence_number: nextClockSequence(),
|
|
3984
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3985
|
+
consent_token: this.consentToken,
|
|
3986
|
+
payload: snapshotPayload(surface)
|
|
3987
|
+
});
|
|
3988
|
+
} catch (err) {
|
|
3989
|
+
PROCESS_DROPS.add("encode_failed");
|
|
3990
|
+
process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
|
|
3991
|
+
`);
|
|
3992
|
+
return Promise.resolve();
|
|
3993
|
+
}
|
|
3994
|
+
return this.track(
|
|
3995
|
+
(async () => {
|
|
3996
|
+
try {
|
|
3997
|
+
await this.sink.write(event);
|
|
3998
|
+
} catch (err) {
|
|
3999
|
+
if (isSinkClosed(err)) return droppedAfterClose(this.sink);
|
|
4000
|
+
process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
|
|
4001
|
+
`);
|
|
4002
|
+
this.sentSurfaces.unmark(surface.digest);
|
|
4003
|
+
}
|
|
4004
|
+
})()
|
|
4005
|
+
);
|
|
3337
4006
|
}
|
|
3338
|
-
|
|
3339
|
-
|
|
4007
|
+
/** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
|
|
4008
|
+
* also for ones emitted while it waits. A write still pending when time runs
|
|
4009
|
+
* out is not waited on again, so one stuck write costs one wait. */
|
|
4010
|
+
async settleWithin(ms, untilEmpty) {
|
|
4011
|
+
const deadline = performance.now() + ms;
|
|
4012
|
+
do {
|
|
4013
|
+
const waiting = [...this.pending];
|
|
4014
|
+
if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
|
|
4015
|
+
const left = waiting.filter((write) => this.pending.delete(write));
|
|
4016
|
+
if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
|
|
4017
|
+
return;
|
|
4018
|
+
}
|
|
4019
|
+
} while (untilEmpty && this.pending.size > 0);
|
|
3340
4020
|
}
|
|
3341
4021
|
scrub(value, field) {
|
|
3342
4022
|
return scrubOrNull(this.scrubber, value, field);
|
|
3343
4023
|
}
|
|
3344
4024
|
annotate(session, consentToken, options) {
|
|
3345
4025
|
if (!this.live()) return Promise.resolve();
|
|
3346
|
-
const sequence =
|
|
4026
|
+
const sequence = nextClockSequence();
|
|
3347
4027
|
const text = (value) => value === void 0 ? null : this.scrubber(value);
|
|
3348
4028
|
return this.emit(
|
|
3349
4029
|
() => AnnotationEventSchema.parse({
|
|
@@ -3411,7 +4091,7 @@ var Trace = class _Trace {
|
|
|
3411
4091
|
try {
|
|
3412
4092
|
this.#result = this.#core.scrubber(result);
|
|
3413
4093
|
} catch (err) {
|
|
3414
|
-
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${
|
|
4094
|
+
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
|
|
3415
4095
|
`);
|
|
3416
4096
|
this.#result = SCRUB_FAILED;
|
|
3417
4097
|
}
|
|
@@ -3431,7 +4111,7 @@ var Trace = class _Trace {
|
|
|
3431
4111
|
#start() {
|
|
3432
4112
|
this.#startedAt = performance.now();
|
|
3433
4113
|
if (!this.#core.live()) return;
|
|
3434
|
-
const sequence =
|
|
4114
|
+
const sequence = nextClockSequence();
|
|
3435
4115
|
const o = this.#options;
|
|
3436
4116
|
const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
|
|
3437
4117
|
const textOf = (value, field) => {
|
|
@@ -3460,7 +4140,7 @@ var Trace = class _Trace {
|
|
|
3460
4140
|
const durationMs = this.#durationMs();
|
|
3461
4141
|
if (!this.#core.live()) return;
|
|
3462
4142
|
if (this.#result === UNSET && this.#error === null) this.observed(value);
|
|
3463
|
-
const sequence =
|
|
4143
|
+
const sequence = nextClockSequence();
|
|
3464
4144
|
const error = this.#error;
|
|
3465
4145
|
if (error !== null) {
|
|
3466
4146
|
this.#emitError(sequence, error.type, error.body, durationMs);
|
|
@@ -3482,7 +4162,7 @@ var Trace = class _Trace {
|
|
|
3482
4162
|
#fail(err) {
|
|
3483
4163
|
const durationMs = this.#durationMs();
|
|
3484
4164
|
if (!this.#core.live()) return;
|
|
3485
|
-
this.#emitError(
|
|
4165
|
+
this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
|
|
3486
4166
|
}
|
|
3487
4167
|
#emitError(sequence, type, body, durationMs) {
|
|
3488
4168
|
void this.#core.emit(
|
|
@@ -3558,7 +4238,7 @@ var Client = class {
|
|
|
3558
4238
|
try {
|
|
3559
4239
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
3560
4240
|
} catch (err) {
|
|
3561
|
-
process.stderr.write(`baton: session values could not be read; using a minted session: ${
|
|
4241
|
+
process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
|
|
3562
4242
|
`);
|
|
3563
4243
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
3564
4244
|
}
|
|
@@ -3588,30 +4268,41 @@ var Client = class {
|
|
|
3588
4268
|
const given = options ?? {};
|
|
3589
4269
|
return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
|
|
3590
4270
|
}
|
|
3591
|
-
/**
|
|
4271
|
+
/** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
|
|
4272
|
+
* to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
|
|
4273
|
+
* of `tools` as passed, sent once per distinct surface. For a vendor
|
|
4274
|
+
* serving MCP itself (SPEC §5.6).
|
|
4275
|
+
*
|
|
4276
|
+
* Pass the tools before anything of Baton's is added, so the snapshot
|
|
4277
|
+
* describes the vendor's own surface. `options` holds the vendor's own
|
|
4278
|
+
* `initialize` values. The input is not changed. Never rejects over the
|
|
4279
|
+
* tool list: one it cannot read is returned as it came. Does not wait for
|
|
4280
|
+
* the snapshot to be sent; `flush()` does. */
|
|
4281
|
+
async listTools(tools, options = {}) {
|
|
4282
|
+
if (this.#core.disabled) return tools;
|
|
4283
|
+
const { served, surface } = serveTools(tools, options);
|
|
4284
|
+
if (surface !== null) void this.#core.sendSurface(surface);
|
|
4285
|
+
return served;
|
|
4286
|
+
}
|
|
4287
|
+
/** Wait for events so far to reach the sink, then flush it. Never rejects;
|
|
4288
|
+
* returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
|
|
3592
4289
|
async flush() {
|
|
3593
|
-
await this.#
|
|
3594
|
-
try {
|
|
3595
|
-
await this.#core.sink.flush();
|
|
3596
|
-
} catch (err) {
|
|
3597
|
-
process.stderr.write(`baton: sink.flush failed: ${String(err)}
|
|
3598
|
-
`);
|
|
3599
|
-
}
|
|
4290
|
+
await this.#settleThen("flush");
|
|
3600
4291
|
}
|
|
3601
4292
|
/** Flush, then close the sink. Later events are dropped. */
|
|
3602
4293
|
aclose() {
|
|
3603
|
-
this.#closing ??= this.#
|
|
4294
|
+
this.#closing ??= this.#settleThen("aclose");
|
|
3604
4295
|
return this.#closing;
|
|
3605
4296
|
}
|
|
3606
|
-
|
|
3607
|
-
|
|
3608
|
-
|
|
3609
|
-
|
|
3610
|
-
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
3614
|
-
}
|
|
4297
|
+
/** One budget: events in flight get until its end to reach the sink, then
|
|
4298
|
+
* the sink gets the time left. */
|
|
4299
|
+
async #settleThen(method) {
|
|
4300
|
+
await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
|
|
4301
|
+
const deadline = performance.now() + budgetMs;
|
|
4302
|
+
await this.#core.settleWithin(budgetMs, method === "aclose");
|
|
4303
|
+
if (method === "aclose") this.#core.closed = true;
|
|
4304
|
+
await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
|
|
4305
|
+
});
|
|
3615
4306
|
}
|
|
3616
4307
|
};
|
|
3617
4308
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -3620,13 +4311,18 @@ var Client = class {
|
|
|
3620
4311
|
AnnotationPayloadSchema,
|
|
3621
4312
|
BatonHandle,
|
|
3622
4313
|
Client,
|
|
4314
|
+
ClientReportEventSchema,
|
|
4315
|
+
ClientReportPayloadSchema,
|
|
3623
4316
|
DEFAULT_CONSENT_TOKEN,
|
|
3624
4317
|
DEPTH_LIMIT,
|
|
4318
|
+
DEPTH_MARKER,
|
|
3625
4319
|
EventSchema,
|
|
3626
4320
|
EventTypeSchema,
|
|
4321
|
+
FileSink,
|
|
3627
4322
|
HttpSink,
|
|
3628
4323
|
INTENT_INSTRUCTIONS,
|
|
3629
4324
|
INTENT_PARAMS,
|
|
4325
|
+
MultiSink,
|
|
3630
4326
|
PRINCIPAL_FORM_HASHED,
|
|
3631
4327
|
PRINCIPAL_FORM_RAW,
|
|
3632
4328
|
PRINCIPAL_SOURCE_ASSERTED,
|
|
@@ -3657,6 +4353,7 @@ var Client = class {
|
|
|
3657
4353
|
ResourceReadStartPayloadSchema,
|
|
3658
4354
|
SDK_VERSION,
|
|
3659
4355
|
Scrubber,
|
|
4356
|
+
SinkClosedError,
|
|
3660
4357
|
StdoutSink,
|
|
3661
4358
|
SurfaceSnapshotEventSchema,
|
|
3662
4359
|
SurfaceSnapshotPayloadSchema,
|